text
stringlengths
55
456k
metadata
dict
# Nanopb: API reference ## Compilation options The following options can be specified in one of two ways: 1. Using the -D switch on the C compiler command line. 2. Using a `#define` at the top of pb.h. > **NOTE:** You must have the same settings for the nanopb library and all code that includes nanopb headers. * `PB_ENABLE_MALLOC`: Enable dynamic allocation support in the decoder. * `PB_MAX_REQUIRED_FIELDS`: Maximum number of proto2 `required` fields to check for presence. Default value is 64. Compiler warning will tell if you need this. * `PB_FIELD_32BIT`: Add support for field tag numbers over 65535, fields larger than 64 kiB and arrays larger than 65535 entries. Compiler warning will tell if you need this. * `PB_NO_ERRMSG`: Disable error message support to save code size. Only error information is the `true`/`false` return value. * `PB_BUFFER_ONLY`: Disable support for custom streams. Only supports encoding and decoding with memory buffers. Speeds up execution and slightly decreases code size. * `PB_SYSTEM_HEADER`: Replace the standards header files with a single system-specific header file. Value must include quotes, for example `#define PB_SYSTEM_HEADER "foo.h"`. See [extra/pb_syshdr.h](https://github.com/nanopb/nanopb/blob/master/extra/pb_syshdr.h) for an example. * `PB_WITHOUT_64BIT`: Disable support of 64-bit integer fields, for old compilers or for a slight speedup on 8-bit platforms. * `PB_ENCODE_ARRAYS_UNPACKED`: Encode scalar arrays in the unpacked format, which takes up more space. Only to be used when the decoder on the receiving side cannot process packed arrays, such as [protobuf.js versions before 2020](https://github.com/protocolbuffers/protobuf/issues/1701). * `PB_CONVERT_DOUBLE_FLOAT`: Convert doubles to floats for platforms that do not support 64-bit `double` datatype. Mainly `AVR` processors. * `PB_VALIDATE_UTF8`: Check whether incoming strings are valid UTF-8 sequences. Adds a small performance and code size penalty. * `PB_C99_STATIC_ASSERT`: Use C99 style negative array trick for static assertions. For compilers that do not support C11 standard. * `PB_NO_STATIC_ASSERT`: Disable static assertions at compile time. Only for compilers with limited support of C standards. The `PB_MAX_REQUIRED_FIELDS` and `PB_FIELD_32BIT` settings allow raising some datatype limits to suit larger messages. Their need is recognized automatically by C-preprocessor `#if`-directives in the generated `.pb.c` files. The default setting is to use the smallest datatypes (least resources used). ## Proto file options The generator behaviour can be adjusted using several options, defined in the [nanopb.proto](https://github.com/nanopb/nanopb/blob/master/generator/proto/nanopb.proto) file in the generator folder. Here is a list of the most common options, but see the file for a full list: * `max_size`: Allocated maximum size for `bytes` and `string` fields. For strings, this includes the terminating zero. * `max_length`: Maximum length for `string` fields. Setting this is equivalent to setting `max_size` to a value of length + 1. * `max_count`: Allocated maximum number of entries in arrays (`repeated` fields). * `type`: Select how memory is allocated for the generated field. Default value is `FT_DEFAULT`, which defaults to `FT_STATIC` when possible and `FT_CALLBACK` if not possible. You can use `FT_CALLBACK`, `FT_POINTER`, `FT_STATIC` or `FT_IGNORE` to select a callback field, a dynamically allocate dfield, a statically allocated field or to completely ignore the field. * `long_names`: Prefix the enum name to the enum value in definitions, i.e. `EnumName_EnumValue`. Enabled by default. * `packed_struct`: Make the generated structures packed, which saves some RAM space but slows down execution. This can only be used if the CPU supports unaligned access to variables. * `skip_message`: Skip a whole message from generation. Can be used to remove message types that are not needed in an application. * `no_unions`: Generate `oneof` fields as multiple optional fields instead of a C `union {}`. * `anonymous_oneof`: Generate `oneof` fields as an anonymous union. * `msgid`: Specifies a unique id for this message type. Can be used by user code as an identifier. * `fixed_length`: Generate `bytes` fields with a constant length defined by `max_size`. A separate `.size` field will then not be generated. * `fixed_count`: Generate arrays with constant length defined by `max_count`. * `package`: Package name that applies only for nanopb generator. Defaults to name defined by `package` keyword in .proto file, which applies for all languages. * `int_size`: Override the integer type of a field. For example, specify `int_size = IS_8` to convert `int32` from protocol definition into `int8_t` in the structure. These options can be defined for the .proto files before they are converted using the nanopb-generatory.py. There are three ways to define the options: 1. Using a separate .options file. This allows using wildcards for applying same options to multiple fields. 2. Defining the options on the command line of nanopb_generator.py. This only makes sense for settings that apply to a whole file. 3. Defining the options in the .proto file using the nanopb extensions. This keeps the options close to the fields they apply to, but can be problematic if the same .proto file is shared with many projects. The effect of the options is the same no matter how they are given. The most common purpose is to define maximum size for string fields in order to statically allocate them. ### Defining the options in a .options file The preferred way to define options is to have a separate file 'myproto.options' in the same directory as the 'myproto.proto'. : # myproto.proto message MyMessage { required string name = 1; repeated int32 ids = 4; } # myproto.options MyMessage.name max_size:40 MyMessage.ids max_count:5 The generator will automatically search for this file and read the options from it. The file format is as follows: - Lines starting with `#` or `//` are regarded as comments. - Blank lines are ignored. - All other lines should start with a field name pattern, followed by one or more options. For example: `MyMessage.myfield max_size:5 max_count:10`. - The field name pattern is matched against a string of form `Message.field`. For nested messages, the string is `Message.SubMessage.field`. A whole file can be matched by its filename `dir/file.proto`. - The field name pattern may use the notation recognized by Python fnmatch(): - `*` matches any part of string, like `Message.*` for all fields - `?` matches any single character - `[seq]` matches any of characters `s`, `e` and `q` - `[!seq]` matches any other character - The options are written as `option_name:option_value` and several options can be defined on same line, separated by whitespace. - Options defined later in the file override the ones specified earlier, so it makes sense to define wildcard options first in the file and more specific ones later. To debug problems in applying the options, you can use the `-v` option for the nanopb generator. With protoc, plugin options are specified with `--nanopb_opt`: nanopb_generator -v message.proto # When invoked directly protoc ... --nanopb_opt=-v --nanopb_out=. message.proto # When invoked through protoc Protoc doesn't currently pass include path into plugins. Therefore if your `.proto` is in a subdirectory, nanopb may have trouble finding the associated `.options` file. A workaround is to specify include path separately to the nanopb plugin, like: protoc -Isubdir --nanopb_opt=-Isubdir --nanopb_out=. message.proto If preferred, the name of the options file can be set using generator argument `-f`. ### Defining the options on command line The nanopb_generator.py has a simple command line option `-s OPTION:VALUE`. The setting applies to the whole file that is being processed. ### Defining the options in the .proto file The .proto file format allows defining custom options for the fields. The nanopb library comes with *nanopb.proto* which does exactly that, allowing you do define the options directly in the .proto file: ~~~~ protobuf import "nanopb.proto"; message MyMessage { required string name = 1 [(nanopb).max_size = 40]; repeated int32 ids = 4 [(nanopb).max_count = 5]; } ~~~~ A small complication is that you have to set the include path of protoc so that nanopb.proto can be found. Therefore, to compile a .proto file which uses options, use a protoc command similar to: protoc -Inanopb/generator/proto -I. --nanopb_out=. message.proto The options can be defined in file, message and field scopes: ~~~~ protobuf option (nanopb_fileopt).max_size = 20; // File scope message Message { option (nanopb_msgopt).max_size = 30; // Message scope required string fieldsize = 1 [(nanopb).max_size = 40]; // Field scope } ~~~~ ## pb.h ### pb_byte_t Type used for storing byte-sized data, such as raw binary input and bytes-type fields. typedef uint_least8_t pb_byte_t; For most platforms this is equivalent to `uint8_t`. Some platforms however do not support 8-bit variables, and on those platforms 16 or 32 bits need to be used for each byte. ### pb_size_t Type used for storing tag numbers and sizes of message fields. By default the type is 16-bit: typedef uint_least16_t pb_size_t; If tag numbers or fields larger than 65535 are needed, `PB_FIELD_32BIT` option can be used to change the type to 32-bit value. ### pb_type_t Type used to store the type of each field, to control the encoder/decoder behaviour. typedef uint_least8_t pb_type_t; The low-order nibble of the enumeration values defines the function that can be used for encoding and decoding the field data: | LTYPE identifier |Value |Storage format | ---------------------------------|-------|------------------------------------------------ | `PB_LTYPE_BOOL` |0x00 |Boolean. | `PB_LTYPE_VARINT` |0x01 |Integer. | `PB_LTYPE_UVARINT` |0x02 |Unsigned integer. | `PB_LTYPE_SVARINT` |0x03 |Integer, zigzag encoded. | `PB_LTYPE_FIXED32` |0x04 |32-bit integer or floating point. | `PB_LTYPE_FIXED64` |0x05 |64-bit integer or floating point. | `PB_LTYPE_BYTES` |0x06 |Structure with `size_t` field and byte array. | `PB_LTYPE_STRING` |0x07 |Null-terminated string. | `PB_LTYPE_SUBMESSAGE` |0x08 |Submessage structure. | `PB_LTYPE_SUBMSG_W_CB` |0x09 |Submessage with pre-decoding callback. | `PB_LTYPE_EXTENSION` |0x0A |Pointer to `pb_extension_t`. | `PB_LTYPE_FIXED_LENGTH_BYTES` |0x0B |Inline `pb_byte_t` array of fixed size. The bits 4-5 define whether the field is required, optional or repeated. There are separate definitions for semantically different modes, even though some of them share values and are distinguished based on values of other fields: |HTYPE identifier |Value |Field handling |---------------------|-------|-------------------------------------------------------------------------------------------- |`PB_HTYPE_REQUIRED` |0x00 |Verify that field exists in decoded message. |`PB_HTYPE_OPTIONAL` |0x10 |Use separate `has_<field>` boolean to specify whether the field is present. |`PB_HTYPE_SINGULAR` |0x10 |Proto3 field, which is present when its value is non-zero. |`PB_HTYPE_REPEATED` |0x20 |A repeated field with preallocated array. Separate `<field>_count` for number of items. |`PB_HTYPE_FIXARRAY` |0x20 |A repeated field that has constant length. |`PB_HTYPE_ONEOF` |0x30 |Oneof-field, only one of each group can be present. The bits 6-7 define the how the storage for the field is allocated: |ATYPE identifier |Value |Allocation method |---------------------|-------|-------------------------------------------------------------------------------------------- |`PB_ATYPE_STATIC` |0x00 |Statically allocated storage in the structure. |`PB_ATYPE_POINTER` |0x80 |Dynamically allocated storage. Struct field contains a pointer to the storage. |`PB_ATYPE_CALLBACK` |0x40 |A field with dynamic storage size. Struct field contains a pointer to a callback function. ### pb_msgdesc_t Autogenerated structure that contains information about a message and pointers to the field descriptors. Use functions defined in `pb_common.h` to process the field information. typedef struct pb_msgdesc_s pb_msgdesc_t; struct pb_msgdesc_s { pb_size_t field_count; const uint32_t *field_info; const pb_msgdesc_t * const * submsg_info; const pb_byte_t *default_value; bool (*field_callback)(pb_istream_t *istream, pb_ostream_t *ostream, const pb_field_iter_t *field); }; | | | |-----------------|--------------------------------------------------------| |`field_count` | Total number of fields in the message. |`field_info` | Pointer to compact representation of the field information. |`submsg_info` | Pointer to array of pointers to descriptors for submessages. |`default_value` | Default values for this message as an encoded protobuf message. |`field_callback` | Function used to handle all callback fields in this message. By default `pb_default_field_callback()` which loads per-field callbacks from a `pb_callback_t` structure. ### pb_field_iter_t Describes a single structure field with memory position in relation to others. The field information is stored in a compact format and loaded into `pb_field_iter_t` by the functions defined in `pb_common.h`. typedef struct pb_field_iter_s pb_field_iter_t; struct pb_field_iter_s { const pb_msgdesc_t *descriptor; void *message; pb_size_t index; pb_size_t field_info_index; pb_size_t required_field_index; pb_size_t submessage_index; pb_size_t tag; pb_size_t data_size; pb_size_t array_size; pb_type_t type; void *pField; void *pData; void *pSize; const pb_msgdesc_t *submsg_desc; }; | | | |----------------------|--------------------------------------------------------| | descriptor | Pointer to `pb_msgdesc_t` for the message that contains this field. | message | Pointer to the start of the message structure. | index | Index of the field inside the message | field_info_index | Index to the internal `field_info` array | required_field_index | Index that counts only the required fields | submessage_index | Index that counts only submessages | tag | Tag number defined in `.proto` file for this field. | data_size | `sizeof()` of the field in the structure. For repeated fields this is for a single array entry. | array_size | Maximum number of items in a statically allocated array. | type | Type ([pb_type_t](#pb_type_t)) of the field. | pField | Pointer to the field storage in the structure. | pData | Pointer to data contents. For arrays and pointers this can be different than `pField`. | pSize | Pointer to count or has field, or NULL if this field doesn't have such. | submsg_desc | For submessage fields, points to the descriptor for the submessage. By default [pb_size_t](#pb_size_t) is 16-bit, limiting the sizes and tags to 65535. The limit can be raised by defining `PB_FIELD_32BIT`. ### pb_bytes_array_t An byte array with a field for storing the length: typedef struct { pb_size_t size; pb_byte_t bytes[1]; } pb_bytes_array_t; In an actual array, the length of `bytes` may be different. The macros `PB_BYTES_ARRAY_T()` and `PB_BYTES_ARRAY_T_ALLOCSIZE()` are used to allocate variable length storage for bytes fields. ### pb_callback_t Part of a message structure, for fields with type PB_HTYPE_CALLBACK: typedef struct _pb_callback_t pb_callback_t; struct _pb_callback_t { union { bool (*decode)(pb_istream_t *stream, const pb_field_iter_t *field, void **arg); bool (*encode)(pb_ostream_t *stream, const pb_field_iter_t *field, void * const *arg); } funcs; void *arg; }; A pointer to the *arg* is passed to the callback when calling. It can be used to store any information that the callback might need. Note that this is a double pointer. If you set `field.arg` to point to `&data` in your main code, in the callback you can access it like this: myfunction(*arg); /* Gives pointer to data as argument */ myfunction(*(data_t*)*arg); /* Gives value of data as argument */ *arg = newdata; /* Alters value of field.arg in structure */ When calling [pb_encode](#pb_encode), `funcs.encode` is used, and similarly when calling [pb_decode](#pb_decode), `funcs.decode` is used. The function pointers are stored in the same memory location but are of incompatible types. You can set the function pointer to NULL to skip the field. ### pb_wire_type_t Protocol Buffers wire types. These are used with [pb_encode_tag](#pb_encode_tag). : typedef enum { PB_WT_VARINT = 0, PB_WT_64BIT = 1, PB_WT_STRING = 2, PB_WT_32BIT = 5 } pb_wire_type_t; ### pb_extension_type_t Defines the handler functions and auxiliary data for a field that extends another message. Usually autogenerated by `nanopb_generator.py`. typedef struct { bool (*decode)(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type); bool (*encode)(pb_ostream_t *stream, const pb_extension_t *extension); const void *arg; } pb_extension_type_t; In the normal case, the function pointers are `NULL` and the decoder and encoder use their internal implementations. The internal implementations assume that `arg` points to a [pb_field_iter_t](#pb_field_iter_t) that describes the field in question. To implement custom processing of unknown fields, you can provide pointers to your own functions. Their functionality is mostly the same as for normal callback fields, except that they get called for any unknown field when decoding. ### pb_extension_t Ties together the extension field type and the storage for the field value. For message structs that have extensions, the generator will add a `pb_extension_t*` field. It should point to a linked list of extensions. typedef struct { const pb_extension_type_t *type; void *dest; pb_extension_t *next; bool found; } pb_extension_t; | | | |----------------------|--------------------------------------------------------| | type | Pointer to the structure that defines the callback functions. | dest | Pointer to the variable that stores the field value (as used by the default extension callback functions.) | next | Pointer to the next extension handler, or `NULL` for last handler. | found | Decoder sets this to true if the extension was found. ### PB_GET_ERROR Get the current error message from a stream, or a placeholder string if there is no error message: #define PB_GET_ERROR(stream) (string expression) This should be used for printing errors, for example: if (!pb_decode(...)) { printf("Decode failed: %s\n", PB_GET_ERROR(stream)); } The macro only returns pointers to constant strings (in code memory), so that there is no need to release the returned pointer. ### PB_RETURN_ERROR Set the error message and return false: #define PB_RETURN_ERROR(stream,msg) (sets error and returns false) This should be used to handle error conditions inside nanopb functions and user callback functions: if (error_condition) { PB_RETURN_ERROR(stream, "something went wrong"); } The *msg* parameter must be a constant string. ### PB_BIND This macro generates the [pb_msgdesc_t](#pb_msgdesc_t) and associated arrays, based on a list of fields in [X-macro](https://en.wikipedia.org/wiki/X_Macro) format. : #define PB_BIND(msgname, structname, width) ... | | | |----------------------|--------------------------------------------------------| | msgname | Name of the message type. Expects `msgname_FIELDLIST` macro to exist. | structname | Name of the C structure to bind to. | width | Number of words per field descriptor, or `AUTO` to use minimum size possible. This macro is automatically invoked inside the autogenerated `.pb.c` files. User code can also call it to bind message types with custom structures or class types. ## pb_encode.h ### pb_ostream_from_buffer Constructs an output stream for writing into a memory buffer. It uses an internal callback that stores the pointer in stream `state` field. : pb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize); | | | |----------------------|--------------------------------------------------------| | buf | Memory buffer to write into. | bufsize | Maximum number of bytes to write. | returns | An output stream. After writing, you can check `stream.bytes_written` to find out how much valid data there is in the buffer. This should be passed as the message length on decoding side. ### pb_write Writes data to an output stream. Always use this function, instead of trying to call stream callback manually. : bool pb_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count); | | | |----------------------|--------------------------------------------------------| | stream | Output stream to write to. | buf | Pointer to buffer with the data to be written. | count | Number of bytes to write. | returns | True on success, false if maximum length is exceeded or an IO error happens. > **NOTE:** If an error happens, *bytes_written* is not incremented. Depending on the callback used, calling pb_write again after it has failed once may cause undefined behavior. Nanopb itself never does this, instead it returns the error to user application. The builtin `pb_ostream_from_buffer` is safe to call again after failed write. ### pb_encode Encodes the contents of a structure as a protocol buffers message and writes it to output stream. : bool pb_encode(pb_ostream_t *stream, const pb_msgdesc_t *fields, const void *src_struct); | | | |----------------------|--------------------------------------------------------| | stream | Output stream to write to. | fields | Message descriptor, usually autogenerated. | src_struct | Pointer to the message structure. Must match `fields` descriptor. | returns | True on success, false on any error condition. Error message is set to `stream->errmsg`. Normally pb_encode simply walks through the fields description array and serializes each field in turn. However, submessages must be serialized twice: first to calculate their size and then to actually write them to output. This causes some constraints for callback fields, which must return the same data on every call. ### pb_encode_ex Encodes the message, with extended behavior set by flags: bool pb_encode_ex(pb_ostream_t *stream, const pb_msgdesc_t *fields, const void *src_struct, unsigned int flags); | | | |----------------------|--------------------------------------------------------| | stream | Output stream to write to. | fields | Message descriptor, usually autogenerated. | src_struct | Pointer to the message structure. Must match `fields` descriptor. | flags | Extended options, see below. | returns | True on success, false on any error condition. Error message is set to `stream->errmsg`. The options that can be defined are: * `PB_ENCODE_DELIMITED`: Indicate the length of the message by prefixing with a varint-encoded length. Compatible with `parseDelimitedFrom` in Google's protobuf library. * `PB_ENCODE_NULLTERMINATED`: Indicate the length of the message by appending a zero tag value after it. Supported by nanopb decoder, but not by most other protobuf libraries. ### pb_get_encoded_size Calculates the length of the encoded message. bool pb_get_encoded_size(size_t *size, const pb_msgdesc_t *fields, const void *src_struct); | | | |----------------------|--------------------------------------------------------| | size | Calculated size of the encoded message. | fields | Message descriptor, usually autogenerated. | src_struct | Pointer to the data that will be serialized. | returns | True on success, false on detectable errors in field description or if a field encoder returns false. ### Callback field encoders The functions with names `pb_encode_<datatype>` are used when dealing with callback fields. The typical reason for using callbacks is to have an array of unlimited size. In that case, [pb_encode](#pb_encode) will call your callback function, which in turn will call `pb_encode_<datatype>` functions repeatedly to write out values. The tag of a field must be encoded first with [pb_encode_tag_for_field](#pb_encode_tag_for_field). After that, you can call exactly one of the content-writing functions to encode the payload of the field. For repeated fields, you can repeat this process multiple times. Writing packed arrays is a little bit more involved: you need to use `pb_encode_tag` and specify `PB_WT_STRING` as the wire type. Then you need to know exactly how much data you are going to write, and use [pb_encode_varint](#pb_encode_varint) to write out the number of bytes before writing the actual data. Substreams can be used to determine the number of bytes beforehand; see [pb_encode_submessage](#pb_encode_submessage) source code for an example. See [Google Protobuf Encoding Format Documentation](https://developers.google.com/protocol-buffers/docs/encoding) for background information on the Protobuf wire format. #### pb_encode_tag Starts a field in the Protocol Buffers binary format: encodes the field number and the wire type of the data. bool pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, uint32_t field_number); | | | |----------------------|--------------------------------------------------------| | stream | Output stream to write to. 1-5 bytes will be written. | wiretype | `PB_WT_VARINT`, `PB_WT_64BIT`, `PB_WT_STRING` or `PB_WT_32BIT` | field_number | Identifier for the field, defined in the .proto file. You can get it from `field->tag`. | returns | True on success, false on IO error. #### pb_encode_tag_for_field Same as [pb_encode_tag](#pb_encode_tag), except takes the parameters from a `pb_field_iter_t` structure. bool pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_iter_t *field); | | | |----------------------|--------------------------------------------------------| | stream | Output stream to write to. 1-5 bytes will be written. | field | Field iterator for this field. | returns | True on success, false on IO error or unknown field type. This function only considers the `PB_LTYPE` of the field. You can use it from your field callbacks, because the source generator writes correct `LTYPE` also for callback type fields. Wire type mapping is as follows: | LTYPEs | Wire type |--------------------------------------------------|----------------- | BOOL, VARINT, UVARINT, SVARINT | PB_WT_VARINT | FIXED64 | PB_WT_64BIT | STRING, BYTES, SUBMESSAGE, FIXED_LENGTH_BYTES | PB_WT_STRING | FIXED32 | PB_WT_32BIT #### pb_encode_varint Encodes a signed or unsigned integer in the [varint](http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints) format. Works for fields of type `bool`, `enum`, `int32`, `int64`, `uint32` and `uint64`: bool pb_encode_varint(pb_ostream_t *stream, uint64_t value); | | | |----------------------|--------------------------------------------------------| | stream | Output stream to write to. 1-10 bytes will be written. | value | Value to encode, cast to `uint64_t`. | returns | True on success, false on IO error. > **NOTE:** Value will be converted to `uint64_t` in the argument. > To encode signed values, the argument should be cast to `int64_t` first for correct sign extension. #### pb_encode_svarint Encodes a signed integer in the [zig-zagged](https://developers.google.com/protocol-buffers/docs/encoding#signed_integers) format. Works for fields of type `sint32` and `sint64`: bool pb_encode_svarint(pb_ostream_t *stream, int64_t value); (parameters are the same as for [pb_encode_varint](#pb_encode_varint) #### pb_encode_string Writes the length of a string as varint and then contents of the string. Works for fields of type `bytes` and `string`: bool pb_encode_string(pb_ostream_t *stream, const pb_byte_t *buffer, size_t size); | | | |----------------------|--------------------------------------------------------| | stream | Output stream to write to. | buffer | Pointer to string data. | size | Number of bytes in the string. Pass `strlen(s)` for strings. | returns | True on success, false on IO error. #### pb_encode_fixed32 Writes 4 bytes to stream and swaps bytes on big-endian architectures. Works for fields of type `fixed32`, `sfixed32` and `float`: bool pb_encode_fixed32(pb_ostream_t *stream, const void *value); | | | |----------------------|--------------------------------------------------------| | stream | Output stream to write to. 4 bytes will be written. | value | Pointer to a 4-bytes large C variable, for example `uint32_t foo;`. | returns | True on success, false on IO error. #### pb_encode_fixed64 Writes 8 bytes to stream and swaps bytes on big-endian architecture. Works for fields of type `fixed64`, `sfixed64` and `double`: bool pb_encode_fixed64(pb_ostream_t *stream, const void *value); | | | |----------------------|--------------------------------------------------------| | stream | Output stream to write to. 8 bytes will be written. | value | Pointer to a 8-bytes large C variable, for example `uint64_t foo;`. | returns | True on success, false on IO error. #### pb_encode_float_as_double Encodes a 32-bit `float` value so that it appears like a 64-bit `double` in the encoded message. This is sometimes needed when platforms like AVR that do not support 64-bit `double` need to communicate using a message type that contains `double` fields. bool pb_encode_float_as_double(pb_ostream_t *stream, float value); | | | |----------------------|--------------------------------------------------------| | stream | Output stream to write to. 8 bytes will be written. | value | Float value to encode. | returns | True on success, false on IO error. #### pb_encode_submessage Encodes a submessage field, including the size header for it. Works for fields of any message type. bool pb_encode_submessage(pb_ostream_t *stream, const pb_msgdesc_t *fields, const void *src_struct); | | | |----------------------|--------------------------------------------------------| | stream | Output stream to write to. | fields | Pointer to the autogenerated message descriptor for the submessage type, e.g. `MyMessage_fields`. | src | Pointer to the structure where submessage data is. | returns | True on success, false on IO errors, pb_encode errors or if submessage size changes between calls. In Protocol Buffers format, the submessage size must be written before the submessage contents. Therefore, this function has to encode the submessage twice in order to know the size beforehand. If the submessage contains callback fields, the callback function might misbehave and write out a different amount of data on the second call. This situation is recognized and `false` is returned, but garbage will be written to the output before the problem is detected. ## pb_decode.h ### pb_istream_from_buffer Helper function for creating an input stream that reads data from a memory buffer. pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize); | | | |----------------------|--------------------------------------------------------| | buf | Pointer to byte array to read from. | bufsize | Size of the byte array. | returns | An input stream ready to use. ### pb_read Read data from input stream. Always use this function, don't try to call the stream callback directly. bool pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count); | | | |----------------------|--------------------------------------------------------| | stream | Input stream to read from. | buf | Buffer to store the data to, or `NULL` to just read data without storing it anywhere. | count | Number of bytes to read. | returns | True on success, false if `stream->bytes_left` is less than `count` or if an IO error occurs. End of file is signalled by `stream->bytes_left` being zero after pb_read returns false. ### pb_decode Read and decode all fields of a structure. Reads until EOF on input stream. bool pb_decode(pb_istream_t *stream, const pb_msgdesc_t *fields, void *dest_struct); | | | |----------------------|--------------------------------------------------------| | stream | Input stream to read from. | fields | Message descriptor, usually autogenerated. | dest_struct | Pointer to message structure where data will be stored. | returns | True on success, false on any error condition. Error message will be in `stream->errmsg`. In Protocol Buffers binary format, end-of-file is only allowed between fields. If it happens anywhere else, pb_decode will return `false`. If pb_decode returns `false`, you cannot trust any of the data in the structure. For optional fields, this function applies the default value and sets `has_<field>` to false if the field is not present. If `PB_ENABLE_MALLOC` is defined, this function may allocate storage for any pointer type fields. In this case, you have to call [pb_release](#pb_release) to release the memory after you are done with the message. On error return `pb_decode` will release the memory itself. ### pb_decode_ex Same as [pb_decode](#pb_decode), but allows extended options. bool pb_decode_ex(pb_istream_t *stream, const pb_msgdesc_t *fields, void *dest_struct, unsigned int flags); | | | |----------------------|--------------------------------------------------------| | stream | Input stream to read from. | fields | Message descriptor, usually autogenerated. | dest_struct | Pointer to message structure where data will be stored. | flags | Extended options, see below | returns | True on success, false on any error condition. Error message will be in `stream->errmsg`. The following options can be defined and combined with bitwise `|` operator: * `PB_DECODE_NOINIT`: Do not initialize structure before decoding. This can be used to combine multiple messages, or if you have already initialized the message structure yourself. * `PB_DECODE_DELIMITED`: Expect a length prefix in varint format before message. The counterpart of `PB_ENCODE_DELIMITED`. * `PB_DECODE_NULLTERMINATED`: Expect the message to be terminated with zero tag. The counterpart of `PB_ENCODE_NULLTERMINATED`. If `PB_ENABLE_MALLOC` is defined, this function may allocate storage for any pointer type fields. In this case, you have to call [pb_release](#pb_release) to release the memory after you are done with the message. On error return `pb_decode_ex` will release the memory itself. ### pb_release Releases any dynamically allocated fields: void pb_release(const pb_msgdesc_t *fields, void *dest_struct); | | | |----------------------|--------------------------------------------------------| | fields | Message descriptor, usually autogenerated. | dest_struct | Pointer to structure where data is stored. If `NULL`, function does nothing. This function is only available if `PB_ENABLE_MALLOC` is defined. It will release any pointer type fields in the structure and set the pointers to `NULL`. This function is safe to call multiple times, calling it again does nothing. ### pb_decode_tag Decode the tag that comes before field in the protobuf encoding: bool pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof); | | | |----------------------|--------------------------------------------------------| | stream | Input stream to read from. | wire_type | Pointer to variable where to store the wire type of the field. | tag | Pointer to variable where to store the tag of the field. | eof | Pointer to variable where to store end-of-file status. | returns | True on success, false on error or EOF. When the message (stream) ends, this function will return `false` and set `eof` to true. On other errors, `eof` will be set to false. ### pb_skip_field Remove the data for a field from the stream, without actually decoding it: bool pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type); | | | |----------------------|--------------------------------------------------------| | stream | Input stream to read from. | wire_type | Type of field to skip. | returns | True on success, false on IO error. This function determines the amount of bytes to read based on the wire type. For `PB_WT_STRING`, it will read the length prefix of a string or submessage to determine its length. ### Callback field decoders The functions with names `pb_decode_<datatype>` are used when dealing with callback fields. The typical reason for using callbacks is to have an array of unlimited size. In that case, [pb_decode](#pb_decode) will call your callback function repeatedly, which can then store the values into e.g. filesystem in the order received in. For decoding numeric (including enumerated and boolean) values, use [pb_decode_varint](#pb_decode_varint), [pb_decode_svarint](#pb_decode_svarint), [pb_decode_fixed32](#pb_decode_fixed32) and [pb_decode_fixed64](#pb_decode_fixed64). They take a pointer to a 32- or 64-bit C variable, which you may then cast to smaller datatype for storage. For decoding strings and bytes fields, the length has already been decoded and the callback function is given a length-limited substream. You can therefore check the total length in `stream->bytes_left` and read the data using [pb_read](#pb_read). Finally, for decoding submessages in a callback, use [pb_decode](#pb_decode) and pass it the `SubMessage_fields` descriptor array. #### pb_decode_varint Read and decode a [varint](http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints) encoded integer. bool pb_decode_varint(pb_istream_t *stream, uint64_t *dest); | | | |----------------------|--------------------------------------------------------| | stream | Input stream to read from. 1-10 bytes will be read. | dest | Storage for the decoded integer. Value is undefined on error. | returns | True on success, false if value exceeds uint64_t range or an IO error happens. #### pb_decode_varint32 Same as `pb_decode_varint`, but limits the value to 32 bits: bool pb_decode_varint32(pb_istream_t *stream, uint32_t *dest); Parameters are the same as `pb_decode_varint`. This function can be used for decoding lengths and other commonly occurring elements that you know shouldn't be larger than 32 bit. It will return an error if the value exceeds the `uint32_t` datatype. #### pb_decode_svarint Similar to [pb_decode_varint](#pb_decode_varint), except that it performs zigzag-decoding on the value. This corresponds to the Protocol Buffers `sint32` and `sint64` datatypes. : bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest); (parameters are the same as [pb_decode_varint](#pb_decode_varint)) #### pb_decode_fixed32 Decode a `fixed32`, `sfixed32` or `float` value. bool pb_decode_fixed32(pb_istream_t *stream, void *dest); | | | |----------------------|--------------------------------------------------------| | stream | Input stream to read from. 4 bytes will be read. | dest | Pointer to destination `int32_t`, `uint32_t` or `float`. | returns | True on success, false on IO errors. This function reads 4 bytes from the input stream. On big endian architectures, it then reverses the order of the bytes. Finally, it writes the bytes to `dest`. #### pb_decode_fixed64 Decode a `fixed64`, `sfixed64` or `double` value. : bool pb_decode_fixed64(pb_istream_t *stream, void *dest); | | | |----------------------|--------------------------------------------------------| | stream | Input stream to read from. 8 bytes will be read. | dest | Pointer to destination `int64_t`, `uint64_t` or `double`. | returns | True on success, false on IO errors. Same as [pb_decode_fixed32](#pb_decode_fixed32), except this reads 8 bytes. #### pb_decode_double_as_float Decodes a 64-bit `double` value into a 32-bit `float` variable. Counterpart of [pb_encode_float_as_double](#pb_encode_float_as_double). : bool pb_decode_double_as_float(pb_istream_t *stream, float *dest); | | | |----------------------|--------------------------------------------------------| | stream | Input stream to read from. 8 bytes will be read. | dest | Pointer to destination *float*. | returns | True on success, false on IO errors. #### pb_make_string_substream Decode the length for a field with wire type `PB_WT_STRING` and create a substream for reading the data. bool pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream); | | | |----------------------|--------------------------------------------------------| | stream | Original input stream to read the length and data from. | substream | Storage for a new substream that has limited length. Filled in by the function. | returns | True on success, false if reading the length fails. This function uses `pb_decode_varint` to read an integer from the stream. This is interpreted as a number of bytes, and the substream is set up so that its `bytes_left` is initially the same as the length, and its callback function and state the same as the parent stream. #### pb_close_string_substream Close the substream created with [pb_make_string_substream](#pb_make_string_substream). void pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream); | | | |----------------------|--------------------------------------------------------| | stream | Original input stream to read data from. | substream | Substream to close This function copies back the state from the substream to the parent stream, and throws away any unread data from the substream. It must be called after done with the substream. ## pb_common.h ### pb_field_iter_begin Begins iterating over the fields in a message type: bool pb_field_iter_begin(pb_field_iter_t *iter, const pb_msgdesc_t *desc, void *message); | | | |----------------------|--------------------------------------------------------| | iter | Pointer to destination [pb_field_iter_t](#pb_field_iter_t) variable. | desc | Autogenerated message descriptor. | message | Pointer to message structure. | returns | True on success, false if the message type has no fields. ### pb_field_iter_next Advance to the next field in the message: bool pb_field_iter_next(pb_field_iter_t *iter); | | | |----------------------|--------------------------------------------------------| | iter | Pointer to `pb_field_iter_t` previously initialized by [pb_field_iter_begin](#pb_field_iter_begin). | returns | True on success, false after last field in the message. When the last field in the message has been processed, this function will return false and initialize `iter` back to the first field in the message. ### pb_field_iter_find Find a field specified by tag number in the message: bool pb_field_iter_find(pb_field_iter_t *iter, uint32_t tag); | | | |----------------------|--------------------------------------------------------| | iter | Pointer to `pb_field_iter_t` previously initialized by [pb_field_iter_begin](#pb_field_iter_begin). | tag | Tag number to search for. | returns | True if field was found, false otherwise. This function is functionally identical to calling `pb_field_iter_next()` until `iter.tag` equals the searched value. Internally this function avoids fully processing the descriptor for intermediate fields. ### pb_validate_utf8 Validates an UTF8 encoded string: bool pb_validate_utf8(const char *s); | | | |----------------------|--------------------------------------------------------| | s | Pointer to beginning of a string. | returns | True, if string is valid UTF-8, false otherwise. The protobuf standard requires that `string` fields only contain valid UTF-8 encoded text, while `bytes` fields can contain arbitrary data. When the compilation option `PB_VALIDATE_UTF8` is defined, nanopb will automatically validate strings on both encoding and decoding. User code can call this function to validate strings in e.g. custom callbacks.
{ "source": "google/pebble", "title": "third_party/nanopb/docs/reference.md", "url": "https://github.com/google/pebble/blob/main/third_party/nanopb/docs/reference.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 49042 }
# Nanopb: Security model Importance of security in a Protocol Buffers library ---------------------------------------------------- In the context of protocol buffers, security comes into play when decoding untrusted data. Naturally, if the attacker can modify the contents of a protocol buffers message, he can feed the application any values possible. Therefore the application itself must be prepared to receive untrusted values. Where nanopb plays a part is preventing the attacker from running arbitrary code on the target system. Mostly this means that there must not be any possibility to cause buffer overruns, memory corruption or invalid pointers by the means of crafting a malicious message. Division of trusted and untrusted data -------------------------------------- The following data is regarded as **trusted**. It must be under the control of the application writer. Malicious data in these structures could cause security issues, such as execution of arbitrary code: 1. Callback, pointer and extension fields in message structures given to pb_encode() and pb_decode(). These fields are memory pointers, and are generated depending on the message definition in the .proto file. 2. The automatically generated field definitions, i.e. `pb_msgdesc_t`. 3. Contents of the `pb_istream_t` and `pb_ostream_t` structures (this does not mean the contents of the stream itself, just the stream definition). The following data is regarded as **untrusted**. Invalid/malicious data in these will cause "garbage in, garbage out" behaviour. It will not cause buffer overflows, information disclosure or other security problems: 1. All data read from `pb_istream_t`. 2. All fields in message structures, except: - callbacks (`pb_callback_t` structures) - pointer fields and `_count` fields for pointers - extensions (`pb_extension_t` structures) Invariants ---------- The following invariants are maintained during operation, even if the untrusted data has been maliciously crafted: 1. Nanopb will never read more than `bytes_left` bytes from `pb_istream_t`. 2. Nanopb will never write more than `max_size` bytes to `pb_ostream_t`. 3. Nanopb will never access memory out of bounds of the message structure. 4. After `pb_decode()` returns successfully, the message structure will be internally consistent: - The `count` fields of arrays will not exceed the array size. - The `size` field of bytes will not exceed the allocated size. - All string fields will have null terminator. - bool fields will have valid true/false values (since nanopb-0.3.9.4) - pointer fields will be either `NULL` or point to valid data 5. After `pb_encode()` returns successfully, the resulting message is a valid protocol buffers message. (Except if user-defined callbacks write incorrect data.) 6. All memory allocated by `pb_decode()` will be released by a subsequent call to `pb_release()` on the same message. Further considerations ---------------------- Even if the nanopb library is free of any security issues, there are still several possible attack vectors that the application author must consider. The following list is not comprehensive: 1. Stack usage may depend on the contents of the message. The message definition places an upper bound on how much stack will be used. Tests should be run with all fields present, to record the maximum possible stack usage. 2. Callbacks can do anything. The code for the callbacks must be carefully checked if they are used with untrusted data. 3. If using stream input, a maximum size should be set in `pb_istream_t` to stop a denial of service attack from using an infinite message. 4. If using network sockets as streams, a timeout should be set to stop denial of service attacks. 5. If using `malloc()` support, some method of limiting memory use should be employed. This can be done by defining custom `pb_realloc()` function. Nanopb will properly detect and handle failed memory allocations.
{ "source": "google/pebble", "title": "third_party/nanopb/docs/security.md", "url": "https://github.com/google/pebble/blob/main/third_party/nanopb/docs/security.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 4103 }
# Nanopb: New features in nanopb 0.4 ## What's new in nanopb 0.4 Long in the making, nanopb 0.4 has seen some wide reaching improvements in reaction to the development of the rest of the protobuf ecosystem. This document showcases features that are not immediately visible, but that you may want to take advantage of. A lot of effort has been spent in retaining backwards and forwards compatibility with previous nanopb versions. For a list of breaking changes, see [migration document](migration.html) ### New field descriptor format The basic design of nanopb has always been that the information about messages is stored in a compact descriptor format, which is iterated in runtime. Initially it was very tightly tied with encoder and decoder logic. In nanopb-0.3.0 the field iteration logic was separated to `pb_common.c`. Already at that point it was clear that the old format was getting too limited, but it wasn't extended at that time. Now in 0.4, the descriptor format was completely decoupled from the encoder and decoder logic, and redesigned to meet new demands. Previously each field was stored as `pb_field_t` struct, which was between 8 and 32 bytes in size, depending on compilation options and platform. Now information about fields is stored as a variable length sequence of `uint32_t` data words. There are 1, 2, 4 and 8 word formats, with the 8 word format containing plenty of space for future extensibility. One benefit of the variable length format is that most messages now take less storage space. Most fields use 2 words, while simple fields in small messages require only 1 word. Benefit is larger if code previously required `PB_FIELD_16BIT` or `PB_FIELD_32BIT` options. In the `AllTypes` test case, 0.3 had data size of 1008 bytes in 8-bit configuration and 1408 bytes in 16-bit configuration. New format in 0.4 takes 896 bytes for either of these. In addition, the new decoupling has allowed moving most of the field descriptor data into FLASH on Harvard architectures, such as AVR. Previously nanopb was quite RAM-heavy on AVR, which cannot put normal constants in flash like most other platforms do. ### Python packaging for generator Nanopb generator is now available as a Python package, installable using `pip` package manager. This will reduce the need for binary packages, as if you have Python already installed you can just `pip install nanopb` and have the generator available on path as `nanopb_generator`. The generator can also take advantage of the Python-based `protoc` available in `grpcio-tools` Python package. If you also install that, there is no longer a need to have binary `protoc` available. ### Generator now automatically calls protoc Initially, nanopb generator was used in two steps: first calling `protoc` to parse the `.proto` file into `.pb` binary format, and then calling `nanopb_generator.py` to output the `.pb.h` and `.pb.c` files. Nanopb 0.2.3 added support for running as a `protoc` plugin, which allowed single-step generation using `--nanopb_out` parameter. However, the plugin mode has two complications: passing options to nanopb generator itself becomes more difficult, and the generator does not know the actual path of input files. The second limitation has been particularly problematic for locating `.options` files. Both of these older methods still work and will remain supported. However, now `nanopb_generator` can also take `.proto` files directly and it will transparently call `protoc` in the background. ### Callbacks bound by function name Since its very beginnings, nanopb has supported field callbacks to allow processing structures that are larger than what could fit in memory at once. So far the callback functions have been stored in the message structure in a `pb_callback_t` struct. Storing pointers along with user data is somewhat risky from a security point of view. In addition it has caused problems with `oneof` fields, which reuse the same storage space for multiple submessages. Because there is no separate area for each submessage, there is no space to store the callback pointers either. Nanopb-0.4.0 introduces callbacks that are referenced by the function name instead of setting the pointers separately. This should work well for most applications that have a single callback function for each message type. For more complex needs, `pb_callback_t` will also remain supported. Function name callbacks also allow specifying custom data types for inclusion in the message structure. For example, you could have `MyObject*` pointer along with other message fields, and then process that object in custom way in your callback. This feature is demonstrated in [tests/oneof_callback](https://github.com/nanopb/nanopb/tree/master/tests/oneof_callback) test case and [examples/network_server](https://github.com/nanopb/nanopb/tree/master/examples/network_server) example. ### Message level callback for oneofs As mentioned above, callbacks inside submessages inside oneofs have been problematic to use. To make using `pb_callback_t`-style callbacks there possible, a new generator option `submsg_callback` was added. Setting this option to true will cause a new message level callback to be added before the `which_field` of the oneof. This callback will be called when the submessage tag number is known, but before the actual message is decoded. The callback can either choose to set callback pointers inside the submessage, or just completely decode the submessage there and then. If any unread data remains after the callback returns, normal submessage decoding will continue. There is an example of this in [tests/oneof_callback](https://github.com/nanopb/nanopb/tree/master/tests/oneof_callback) test case. ### Binding message types to custom structures It is often said that good C code is chock full of macros. Or maybe I got it wrong. But since nanopb 0.2, the field descriptor generation has heavily relied on macros. This allows it to automatically adapt to differences in type alignment on different platforms, and to decouple the Python generation logic from how the message descriptors are implemented on the C side. Now in 0.4.0, I've made the macros even more abstract. Time will tell whether this was such a great idea that I think it is, but now the complete list of fields in each message is available in `.pb.h` file. This allows a kind of metaprogramming using [X-macros]() One feature that this can be used for is binding the message descriptor to a custom structure or C++ class type. You could have a bunch of other fields in the structure and even the datatypes can be different to an extent, and nanopb will automatically detect the size and position of each field. The generated `.pb.c` files now just have calls of `PB_BIND(msgname, structname, width)`. Adding a similar call to your own code will bind the message to your own structure. ### UTF-8 validation Protobuf format defines that strings should consist of valid UTF-8 codepoints. Previously nanopb has not enforced this, requiring extra care in the user code. Now optional UTF-8 validation is available with compilation option `PB_VALIDATE_UTF8`. ### Double to float conversion Some platforms such as `AVR` do not support the `double` datatype, instead making it an alias for `float`. This has resulted in problems when trying to process message types containing `double` fields generated on other machines. There has been an example on how to manually perform the conversion between `double` and `float`. Now that example is integrated as an optional feature in nanopb core. By defining `PB_CONVERT_DOUBLE_FLOAT`, the required conversion between 32- and 64-bit floating point formats happens automatically on decoding and encoding. ### Improved testing Testing on embedded platforms has been integrated in the continuous testing environment. Now all of the 80+ test cases are automatically run on STM32 and AVR targets. Previously only a few specialized test cases were manually tested on embedded systems. Nanopb fuzzer has also been integrated in Google's [OSSFuzz](https://google.github.io/oss-fuzz/) platform, giving a huge boost in the CPU power available for randomized testing.
{ "source": "google/pebble", "title": "third_party/nanopb/docs/whats_new.md", "url": "https://github.com/google/pebble/blob/main/third_party/nanopb/docs/whats_new.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 8208 }
# pbl Like pebble-tool, but for internal things. Not to be confused with pebble-tool-dev. This repository is for internal tools that don't make sense to ever be public; pebble-tool-dev is for public tools that can't be public yet. Not sure where to put something? Ask Katharine! ## Installation pip install git+ssh://[email protected]/pebble/pbl.git ## Adding commands Create a new file in pbl/commands. Add a class inheriting from `BaseCommand` (or `PebbleCommand` if it connects to a pebble). The docstring will be used as help. Include a `command` field that gives the name of the command. The class's `__call__` method will be called when you run the command. Many examples can be found [in pebble-tool](https://github.com/pebble/pebble-tool/tree/master/pebble_tool/commands).
{ "source": "google/pebble", "title": "third_party/pbl/pbl/README.md", "url": "https://github.com/google/pebble/blob/main/third_party/pbl/pbl/README.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 788 }
pblconvert ========== pblconvert is a tool to convert pebble resources. Today, it can be used to convert SVGs to PDCs. Installing ----------- ``` $ pip install . ``` Running tests ------------- ``` $ nosetests tests ``` Usage ------ ``` pblconvert --infile <input> [--informat --outfile --outformat] ``` One of [outformat|outfile] is required
{ "source": "google/pebble", "title": "third_party/pbl/pblconvert/README.rst", "url": "https://github.com/google/pebble/blob/main/third_party/pbl/pblconvert/README.rst", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 350 }
--- # Copyright 2025 Google LLC # # 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. title: Animated Images description: | How to add animated image resources to a project in the APNG format, and display them in your app. guide_group: app-resources order: 0 platform_choice: true --- The Pebble SDK allows animated images to be played inside an app using the ``GBitmapSequence`` API, which takes [APNG](https://en.wikipedia.org/wiki/APNG) images as input files. APNG files are similar to well-known `.gif` files, which are not supported directly but can be converted to APNG. A similar effect can be achieved with multiple image resources, a ``BitmapLayer`` and an ``AppTimer``, but would require a lot more code. The ``GBitmapSequence`` API handles the reading, decompression, and frame duration/count automatically. ## Converting GIF to APNG A `.gif` file can be converted to the APNG `.png` format with [gif2apng](http://gif2apng.sourceforge.net/) and the `-z0` flag: ```text ./gif2apng -z0 animation.gif ``` > Note: The file extension must be `.png`, **not** `.apng`. ## Adding an APNG {% platform local %} Include the APNG file in the `resources` array in `package.json` as a `raw` resource: ```js "resources": { "media": [ { "type":"raw", "name":"ANIMATION", "file":"images/animation.png" } ] } ``` {% endplatform %} {% platform cloudpebble %} To add the APNG file as a raw resource, click 'Add New' in the Resources section of the sidebar, and set the 'Resource Type' as 'raw binary blob'. {% endplatform %} ## Displaying APNG Frames The ``GBitmapSequence`` will use a ``GBitmap`` as a container and update its contents each time a new frame is read from the APNG file. This means that the first step is to create a blank ``GBitmap`` to be this container. Declare file-scope variables to hold the data: ```c static GBitmapSequence *s_sequence; static GBitmap *s_bitmap; ``` Load the APNG from resources into the ``GBitmapSequence`` variable, and use the frame size to create the blank ``GBitmap`` frame container: ```c // Create sequence s_sequence = gbitmap_sequence_create_with_resource(RESOURCE_ID_ANIMATION); // Create blank GBitmap using APNG frame size GSize frame_size = gbitmap_sequence_get_bitmap_size(s_sequence); s_bitmap = gbitmap_create_blank(frame_size, GBitmapFormat8Bit); ``` Once the app is ready to begin playing the animated image, advance each frame using an ``AppTimer`` until the end of the sequence is reached. Loading the next APNG frame is handled for you and written to the container ``GBitmap``. Declare a ``BitmapLayer`` variable to display the current frame, and set it up as described under {% guide_link app-resources/images#displaying-an-image "Displaying An Image" %}. ```c static BitmapLayer *s_bitmap_layer; ``` Create the callback to be used when the ``AppTimer`` has elapsed, and the next frame should be displayed. This will occur in a loop until there are no more frames, and ``gbitmap_sequence_update_bitmap_next_frame()`` returns `false`: ```c static void timer_handler(void *context) { uint32_t next_delay; // Advance to the next APNG frame, and get the delay for this frame if(gbitmap_sequence_update_bitmap_next_frame(s_sequence, s_bitmap, &next_delay)) { // Set the new frame into the BitmapLayer bitmap_layer_set_bitmap(s_bitmap_layer, s_bitmap); layer_mark_dirty(bitmap_layer_get_layer(s_bitmap_layer)); // Timer for that frame's delay app_timer_register(next_delay, timer_handler, NULL); } } ``` When appropriate, schedule the first frame advance with an ``AppTimer``: ```c uint32_t first_delay_ms = 10; // Schedule a timer to advance the first frame app_timer_register(first_delay_ms, timer_handler, NULL); ``` When the app exits or the resource is no longer required, destroy the ``GBitmapSequence`` and the container ``GBitmap``: ```c gbitmap_sequence_destroy(s_sequence); gbitmap_destroy(s_bitmap); ```
{ "source": "google/pebble", "title": "devsite/source/_guides/app-resources/animated-images.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/app-resources/animated-images.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 4449 }
--- # Copyright 2025 Google LLC # # 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. title: App Assets description: | A collection of assets for use as resources in Pebble apps. guide_group: app-resources order: 1 --- This guide contains some resources available for developers to use in their apps to improve consistency, as well as for convenience. For example, most ``ActionBarLayer`` implementations will require at least one of the common icons given below. ## Pebble Timeline Pin Icons Many timeline pin icons [are available]({{ site.links.s3_assets }}/assets/other/pebble-timeline-icons-pdc.zip) in Pebble Draw Command or PDC format (as described in {% guide_link graphics-and-animations/vector-graphics %}) for use in watchfaces and watchapps. These are useful in many kinds of generic apps. ## Example PDC icon SVG Files Many of the system PDC animations are available for use in watchfaces and watchapps as part of the [`pdc-sequence`](https://github.com/pebble-examples/pdc-sequence/tree/master/resources) example project. ## Example Action Bar Icons There is a [set of example icons](https://s3.amazonaws.com/developer.getpebble.com/assets/other/actionbar-icons.zip) for developers to use for common actions. Each icon is shown below as a preview, along with a short description about its suggested usage. | Preview | Description | |---------|-------------| | ![](/images/guides/design-and-interaction/icons/action_bar_icon_check.png) | Check mark for confirmation actions. | | ![](/images/guides/design-and-interaction/icons/action_bar_icon_dismiss.png) | Cross mark for dismiss, cancel, or decline actions. | | ![](/images/guides/design-and-interaction/icons/action_bar_icon_up.png) | Up arrow for navigating or scrolling upwards. | | ![](/images/guides/design-and-interaction/icons/action_bar_icon_down.png) | Down arrow for navigating or scrolling downwards. | | ![](/images/guides/design-and-interaction/icons/action_bar_icon_edit.png) | Pencil icon for edit actions. | | ![](/images/guides/design-and-interaction/icons/action_bar_icon_delete.png) | Trash can icon for delete actions. | | ![](/images/guides/design-and-interaction/icons/action_bar_icon_snooze.png) | Stylized 'zzz' for snooze actions. | | ![](/images/guides/design-and-interaction/icons/music_icon_ellipsis.png) | Ellipsis to suggest further information or actions are available. | | ![](/images/guides/design-and-interaction/icons/music_icon_play.png) | Common icon for play actions. | | ![](/images/guides/design-and-interaction/icons/music_icon_pause.png) | Common icon for pause actions. | | ![](/images/guides/design-and-interaction/icons/music_icon_skip_forward.png) | Common icon for skip forward actions. | | ![](/images/guides/design-and-interaction/icons/music_icon_skip_backward.png) | Common icon for skip backward actions. | | ![](/images/guides/design-and-interaction/icons/music_icon_volume_up.png) | Common icon for raising volume. | | ![](/images/guides/design-and-interaction/icons/music_icon_volume_down.png) | Common icon for lowering volume. |
{ "source": "google/pebble", "title": "devsite/source/_guides/app-resources/app-assets.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/app-resources/app-assets.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 3562 }
--- # Copyright 2025 Google LLC # # 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. title: Converting SVG to PDC description: | How to create compatible SVG files using Inkscape and Illustrator. guide_group: app-resources order: 2 related_docs: - Draw Commands --- [Pebble Draw Commands](``Draw Commands``) (PDC) are a powerful method of creating vector images and icons that can be transformed and manipulated at runtime. These can be used as a low-cost alternative to APNGs or bitmap sequences. Currently the only simple way to create PDC files is to use the [`svg2pdc.py`](https://github.com/pebble-examples/cards-example/blob/master/tools/svg2pdc.py) tool. However, as noted in [*Vector Animations*](/tutorials/advanced/vector-animations/#creating-compatible-files) there are a some limitations to the nature of the input SVG file: > The `svg2pdc` tool currently supports SVG files that use **only** the > following elements: `g`, `layer`, `path`, `rect`, `polyline`, `polygon`, > `line`, `circle`. Fortunately, steps can be taken when creating SVG files in popular graphics packages to avoid these limitations and ensure the output file is compatible with `svg2pdc.py`. In this guide, we will be creating compatible PDC files using an example SVG - this [pencil icon](https://upload.wikimedia.org/wikipedia/commons/a/ac/Black_pencil.svg). ![pencil icon](/images/guides/pebble-apps/resources/pencil.svg =100x) ## Using Inkscape * First, open the SVG in [Inkscape](https://inkscape.org/en/): ![inkscape-open](/images/guides/pebble-apps/resources/inkscape-open.png) * Resize the viewport with *File*, *Document Properties*, *Page*, *Resize Page to Drawing*: ![inkscape-resize-page](/images/guides/pebble-apps/resources/inkscape-resize-page.png =350x) * Select the layer, then resize the image to fit Pebble (50 x 50 pixels in this example) with *Object*, *Transform*: ![inkscape-resize-pebble](/images/guides/pebble-apps/resources/inkscape-resize-pebble.png) * Now that the image has been resized, shrink the viewport again with *File*, *Document Properties*, *Page*, *Resize Page to Drawing*: * Remove groupings with *Edit*, *Select All*, then *Object*, *Ungroup* until no groups remain: ![inkscape-ungroup](/images/guides/pebble-apps/resources/inkscape-ungroup.png) * Disable relative move in *Object*, *Transform*. Hit *Apply*: ![inkscape-relative](/images/guides/pebble-apps/resources/inkscape-relative.png) * Finally, save the image as a 'Plain SVG': ![inkscape-plain](/images/guides/pebble-apps/resources/inkscape-plain.png) ## Using Illustrator * First, open the SVG in Illustrator: ![illustrator-open](/images/guides/pebble-apps/resources/illustrator-open.png) * Resize the image to fit Pebble (50 x 50 pixels in this example) by entering in the desired values in the 'W' and 'H' fields of the *Transform* panel: ![illustrator-resize](/images/guides/pebble-apps/resources/illustrator-resize.png) * Ungroup all items with *Select*, *All*, followed by *Object*, *Ungroup* until no groups remain: ![illustrator-ungroup](/images/guides/pebble-apps/resources/illustrator-ungroup.png) * Shrink the image bounds with *Object*, *Artboards*, *Fit to Selected Art*: ![illustrator-fit](/images/guides/pebble-apps/resources/illustrator-fit.png) * Save the SVG using *File*, *Save As* with the *SVG Tiny 1.1* profile and 1 decimal places: ![illustrator-settings](/images/guides/pebble-apps/resources/illustrator-settings.png =350x) ## Using the PDC Files Once the compatible SVG files have been created, it's time to use `svg2pdc.py` to convert into PDC resources, which will contain all the vector information needed to draw the image in the correct Pebble binary format. The command is shown below, with the Inkscape output SVG used as an example: ```nc|bash $ python svg2pdc.py pencil-inkscape.svg # Use python 2.x! ``` > If a coordinate value's precision value isn't supported, a warning will be > printed and the nearest compatible value will be used instead: > > ```text > Invalid point: (9.4, 44.5). Closest supported coordinate: (9.5, 44.5) > ``` To use the PDC file in a Pebble project, read [*Drawing a PDC Image*](/tutorials/advanced/vector-animations/#drawing-a-pdc-image). The result should look near-identical on Pebble: ![svg-output >{pebble-screenshot,pebble-screenshot--time-red}](/images/guides/pebble-apps/resources/svg-output.png) ## Example Output For reference, compatible output files are listed below: * Inkscape: [SVG](/assets/other/pdc/pencil-inkscape.svg) | [PDC](/assets/other/pdc/pencil-inkscape.pdc) * Illustrator: [SVG](/assets/other/pdc/pencil-illustrator.svg) | [PDC](/assets/other/pdc/pencil-illustrator.pdc)
{ "source": "google/pebble", "title": "devsite/source/_guides/app-resources/converting-svg-to-pdc.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/app-resources/converting-svg-to-pdc.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 5196 }
--- # Copyright 2025 Google LLC # # 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. title: Fonts description: | How to use built-in system fonts, or add your own font resources to a project. guide_group: app-resources order: 3 platform_choice: true --- ## Using Fonts Text drawn in a Pebble app can be drawn using a variety of built-in fonts or a custom font specified as a project resource. Custom font resources must be in the `.ttf` (TrueType font) format. When the app is built, the font file is processed by the SDK according to the `compatibility` (See [*Font Compatibility*](#font-compatibility)) and `characterRegex` fields (see [*Choosing Font Characters*](#choosing-font-characters)), the latter of which is a standard Python regex describing the character set of the resulting font. ## System Fonts All of the built-in system fonts are available to use with ``fonts_get_system_font()``. See {% guide_link app-resources/system-fonts %} for a complete list with sample images. Examples of using a built-in system font in code are [shown below](#using-a-system-font). ### Limitations There are limitations to the Bitham, Roboto, Droid and LECO fonts, owing to the memory space available on Pebble, which only contain a subset of the default character set. * Roboto 49 Bold Subset - contains digits and a colon. * Bitham 34/42 Medium Numbers - contain digits and a colon. * Bitham 18/34 Light Subset - only contains a few characters and is not suitable for displaying general text. * LECO Number sets - suitable for number-only usage. ## Using a System Font Using a system font is the easiest choice when displaying simple text. For more advanced cases, a custom font may be advantageous. A system font can be obtained at any time, and the developer is not responsible for destroying it when they are done with it. Fonts can be used in two modes: ```c // Use a system font in a TextLayer text_layer_set_font(s_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_24)); ``` ```c // Use a system font when drawing text manually graphics_draw_text(ctx, text, fonts_get_system_font(FONT_KEY_GOTHIC_24), bounds, GTextOverflowModeWordWrap, GTextAlignmentCenter, NULL); ``` ## Adding a Custom Font {% platform local %} After placing the font file in the project's `resources` directory, the custom font can be added to a project as `font` `type` item in the `media` array in `package.json`. The `name` field's contents will be made available at compile time with `RESOURCE_ID_` at the front, and must end with the desired font size. For example: ```js "resources": { "media": [ { "type": "font", "name": "EXAMPLE_FONT_20", "file": "example_font.ttf" } ] } ``` {% endplatform %} {% platform cloudpebble %} To add a custom font file to your project, click 'Add New' in the Resources section of the sidebar. Set the 'Resource Type' to 'TrueType font', and upload the file using the 'Choose file' button. Choose an 'Identifier', which will be made available at compile time with `RESOURCE_ID_` at the front. This must end with the desired font size ("EXAMPLE_FONT_20", for example). Configure the other options as appropriate, then hit 'Save' to save the resource. {% endplatform %} {% alert important %} The maximum recommended font size is 48. {% endalert %} ## Using a Custom Font Unlike a system font, a custom font must be loaded and unloaded by the developer. Once this has been done, the font can easily be used in a similar manner. When the app initializes, load the font from resources using the generated `RESOURCE_ID`: ```c // Declare a file-scope variable static GFont s_font; ``` ```c // Load the custom font s_font = fonts_load_custom_font( resource_get_handle(RESOURCE_ID_EXAMPLE_FONT_20)); ``` The font can now be used in two modes - with a ``TextLayer``, or when drawing text manually in a ``LayerUpdateProc``: ```c // Use a custom font in a TextLayer text_layer_set_font(s_text_layer, s_font); ``` ```c // Use a custom font when drawing text manually graphics_draw_text(ctx, text, s_font, bounds, GTextOverflowModeWordWrap, GTextAlignmentCenter, NULL); ``` ## Font Compatibility The font rendering process was improved in SDK 2.8. However, in some cases this may cause the appearance of custom fonts to change slightly. To revert to the old rendering process, add `"compatibility": "2.7"` to your font's object in the `media` array (shown above) in `package.json` or set the 'Compatibility' property in the font's resource view in CloudPebble to '2.7 and earlier'. ## Choosing Font Characters By default, the maximum number of supported characters is generated for a font resource. In most cases this will be far too many, and can bloat the size of the app. To optimize the size of your font resources you can use a standard regular expression (or 'regex') string to limit the number of characters to only those you require. The table below outlines some example regular expressions to use for limiting font character sets in common watchapp scenarios: | Expression | Result | |------------|--------| | `[ -~]` | ASCII characters only. | | `[0-9]` | Numbers only. | | `[0-9 ]` | Numbers and spaces only. | | `[a-zA-Z]` | Letters only. | | `[a-zA-Z ]` | Letters and spaces only. | | `[0-9:APM ]` | Time strings only (e.g.: "12:45 AM"). | | `[0-9:A-Za-z ]` | Time and date strings (e.g.: "12:43 AM Wednesday 3rd March 2015". | | `[0-9:A-Za-z° ]` | Time, date, and degree symbol for temperature gauges. | | `[0-9°CF ]` | Numbers and degree symbol with 'C' and 'F' for temperature gauges. | {% platform cloudpebble %} Open the font's configuration screen under 'Resources', then enter the desired regex in the 'Characters' field. Check the preview of the new set of characters, then choose 'Save'. {% endplatform %} {% platform local %} Add the `characterRegex` key to any font objects in `package.json`'s `media` array. ```js "media": [ { "characterRegex": "[:0-9]", "type": "font", "name": "EXAMPLE_FONT", "file": "example_font.ttf" } ] ``` {% endplatform %} Check out [regular-expressions.info](http://www.regular-expressions.info/tutorial.html) to learn more about how to use regular expressions.
{ "source": "google/pebble", "title": "devsite/source/_guides/app-resources/fonts.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/app-resources/fonts.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 6797 }
--- # Copyright 2025 Google LLC # # 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. title: Images description: | How to add image resources to a project and display them in your app. guide_group: app-resources order: 4 platform_choice: true --- Images can be displayed in a Pebble app by adding them as a project resource. They are stored in memory as a ``GBitmap`` while the app is running, and can be displayed either in a ``BitmapLayer`` or by using ``graphics_draw_bitmap_in_rect()``. ## Creating an Image In order to be compatible with Pebble, the image should be saved as a PNG file, ideally in a palettized format (see below for palette files) with the appropriate number of colors. The number of colors available on each platform is shown below: | Platform | Number of Colors | |----------|------------------| | Aplite | 2 (black and white) | | Basalt | 64 colors | | Chalk | 64 colors | ## Color Palettes Palette files for popular graphics packages that contain the 64 supported colors are available below. Use these when creating color image resources: * [Photoshop `.act`](/assets/other/pebble_colors_64.act) * [Illustrator `.ai`](/assets/other/pebble_colors_64.ai) * [GIMP `.pal`](/assets/other/pebble_colors_64.pal) * [ImageMagick `.gif`](/assets/other/pebble_colors_64.gif) ## Import the Image {% platform cloudpebble %} Add the `.png` file as a resource using the 'Add New' button next to 'Resources'. Give the resource a suitable 'Identifier' such as 'EXAMPLE_IMAGE' and click 'Save'. {% endplatform %} {% platform local %} After placing the image in the project's `resources` directory, add an entry to the `resources` item in `package.json`. Specify the `type` as `bitmap`, choose a `name` (to be used in code) and supply the path relative to the project's `resources` directory. Below is an example: ```js "resources": { "media": [ { "type": "bitmap", "name": "EXAMPLE_IMAGE", "file": "background.png" } ] }, ``` {% endplatform %} ## Specifying an Image Resource Image resources are used in a Pebble project when they are listed using the `bitmap` resource type. Resources of this type can be optimized using additional attributes: | Attribute | Description | Values | |-----------|-------------|--------| | `memoryFormat` | Optional. Determines the bitmap type. Reflects values in the `GBitmapFormat` `enum`. | `Smallest`, `SmallestPalette`, `1Bit`, `8Bit`, `1BitPalette`, `2BitPalette`, or `4BitPalette`. | | `storageFormat` | Optional. Determines the file format used for storage. Using `spaceOptimization` instead is preferred. | `pbi` or `png`. | | `spaceOptimization` | Optional. Determines whether the output resource is optimized for low runtime memory or low resource space usage. | `storage` or `memory`. | {% platform cloudpebble %} These attributes can be selected in CloudPebble from the resource's page: ![](/images/guides/app-resources/cp-bitmap-attributes.png) {% endplatform %} {% platform local %} An example usage of these attributes in `package.json` is shown below: ```js { "type": "bitmap", "name": "IMAGE_EXAMPLE", "file": "images/example_image.png" "memoryFormat": "Smallest", "spaceOptimization": "memory" } ``` {% endplatform %} On all platforms `memoryFormat` will default to `Smallest`. On Aplite `spaceOptimization` will default to `memory`, and `storage` on all other platforms. > If you specify a combination of attributes that is not supported, such as a > `1Bit` unpalettized PNG, the build will fail. Palettized 1-bit PNGs are > supported. When compared to using image resources in previous SDK versions: * `png` is equivalent to `bitmap` with no additional specifiers. * `pbi` is equivalent to `bitmap` with `"memoryFormat": "1Bit"`. * `pbi8` is equivalent to `bitmap` with `"memoryFormat": "8Bit"` and `"storageFormat": "pbi"`. Continuing to use the `png` resource type will result in a `bitmap` resource with `"storageFormat": "png"`, which is not optimized for memory usage on the Aplite platform due to less memory available in total, and is not encouraged. ## Specifying Resources Per Platform To save resource space, it is possible to include only certain image resources when building an app for specific platforms. For example, this is useful for the Aplite platform, which requires only black and white versions of images, which can be significantly smaller in size. Resources can also be selected according to platform and display shape. Read {% guide_link app-resources/platform-specific %} to learn more about how to do this. ## Displaying an Image Declare a ``GBitmap`` pointer. This will be the object type the image data is stored in while the app is running: ```c static GBitmap *s_bitmap; ``` {% platform cloudpebble %} Create the ``GBitmap``, specifying the 'Identifier' chosen earlier, prefixed with `RESOURCE_ID_`. This will manage the image data: {% endplatform %} {% platform local %} Create the ``GBitmap``, specifying the `name` chosen earlier, prefixed with `RESOURCE_ID_`. This will manage the image data: {% endplatform %} ```c s_bitmap = gbitmap_create_with_resource(RESOURCE_ID_EXAMPLE_IMAGE); ``` Declare a ``BitmapLayer`` pointer: ```c static BitmapLayer *s_bitmap_layer; ``` Create the ``BitmapLayer`` and set it to show the ``GBitmap``. Make sure to supply the correct width and height of your image in the ``GRect``, as well as using ``GCompOpSet`` to ensure color transparency is correctly applied: ```c s_bitmap_layer = bitmap_layer_create(GRect(5, 5, 48, 48)); bitmap_layer_set_compositing_mode(s_bitmap_layer, GCompOpSet); bitmap_layer_set_bitmap(s_bitmap_layer, s_bitmap); ``` Add the ``BitmapLayer`` as a child layer to the ``Window``: ```c layer_add_child(window_get_root_layer(window), bitmap_layer_get_layer(s_bitmap_layer)); ``` Destroy both the ``GBitmap`` and ``BitmapLayer`` when the app exits: ```c gbitmap_destroy(s_bitmap); bitmap_layer_destroy(s_bitmap_layer); ```
{ "source": "google/pebble", "title": "devsite/source/_guides/app-resources/images.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/app-resources/images.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 6499 }
--- # Copyright 2025 Google LLC # # 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. title: App Resources description: | Information on the many kinds of files that can be used inside Pebble apps. guide_group: app-resources menu: false permalink: /guides/app-resources/ generate_toc: false hide_comments: true platform_choice: true --- The Pebble SDK allows apps to include extra files as app resources. These files can include images, animated images, vector images, custom fonts, and raw data files. These resources are stored in flash memory and loaded when required by the SDK. Apps that use a large number of resources should consider only keeping in memory those that are immediately required. {% alert notice %} The maximum number of resources an app can include is **256**. In addition, the maximum size of all resources bundled into a built app is **128 kB** on the Aplite platform, and **256 kB** on the Basalt and Chalk platforms. These limits include resources used by included Pebble Packages. {% endalert %} {% platform local %} App resources are included in a project by being listed in the `media` property of `package.json`, and are converted into suitable firmware-compatible formats at build time. Examples of this are shown in each type of resource's respective guide. {% endplatform %} {% platform cloudpebble %} App resources are included in a project by clicking the 'Add New' button under 'Resources' and specifying the 'Resource Type' as appropriate. These are then converted into suitable firmware-compatible formats at build time. {% endplatform %} ## Contents {% include guides/contents-group.md group=page.group_data %}
{ "source": "google/pebble", "title": "devsite/source/_guides/app-resources/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/app-resources/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 2151 }
--- # Copyright 2025 Google LLC # # 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. title: Pebble Draw Command File Format description: | The binary file format description for Pebble Draw Command Frames, Images and Sequences. guide_group: app-resources order: 5 related_docs: - Draw Commands - LayerUpdateProc - Graphics related_examples: - title: PDC Sequence url: https://github.com/pebble-examples/pdc-sequence - title: Weather Cards Example url: https://github.com/pebble-examples/cards-example --- Pebble [`Draw Commands`](``Draw Commands``) (PDCs) are vector image files that consist of a binary resource containing the instructions for each stroke, fill, etc. that makes up the image. The byte format of all these components are described in tabular form below. > **Important**: All fields are in the little-endian format! An example implementation with some [usage limitations](/tutorials/advanced/vector-animations#creating-compatible-files) can be seen in [`svg2pdc.py`]({{site.links.examples_org}}/cards-example/blob/master/tools/svg2pdc.py). ## Component Types A PDC binary file consists of the following key components, in ascending order of abstraction: * [Draw Command](#pebble-draw-command) - an instruction for a single line or path to be drawn. * [Draw Command List](#pebble-draw-command-list) - a set of Draw Commands that make up a shape. * [Draw Command Frame](#pebble-draw-command-frame) - a Draw Command List with configurable duration making up one animation frame. Many of these are used in a Draw Command Sequence. * [Draw Command Image](#pebble-draw-command-image) - A single vector image. * [Draw Command Sequence](#pebble-draw-command-sequence) - A set of Draw Command Frames that make up an animated sequence of vector images. ## Versions | PDC Format Version | Implemented | |--------------------|-------------| | 1 | Firmware 3.0 | ## File Format Components ### Point | Field | Offset (bytes) | Size (bytes) | Description | |-------|----------------|--------------|-------------| | X | 0 | 2 | X axis coordinate. Has one of two formats depending on the Draw Command type (see below):<br/><br>Path/Circle type: signed integer. <br/>Precise path type: 13.3 fixed point. | | Y | 2 | 2 | Y axis coordinate. Has one of two formats depending on the Draw Command type (see below):<br/><br>Path/Circle type: signed integer. <br/>Precise path type: 13.3 fixed point. | ### View Box | Field | Offset (bytes) | Size (bytes) | Description | |-------|----------------|--------------|-------------| | Width | 0 | 2 | Width of the view box (signed integer). | | Height | 2 | 2 | Height of the view box (signed integer). | ### Pebble Draw Command | Field | Offset (bytes) | Size (bytes) | Description | |-------|----------------|--------------|-------------| | Type | 0 | 1 | Draw command type. Possible values are: <br/><br/>`0` - Invalid <br/>`1` - Path<br/>`2` - Circle<br/>`3` - Precise path | | Flags | 1 | 1 | Bit 0: Hidden (Draw Command should not be drawn). <br/> Bits 1-7: Reserved. | | Stroke color | 2 | 1 | Pebble color (integer). | | Stroke width | 3 | 1 | Stroke width (unsigned integer). | | Fill color | 4 | 1 | Pebble color (integer). | | Path open/radius | 5 | 2 | Path/Precise path type: Bit 0 indicates whether or not the path is drawn open (`1`) or closed (`0`).<br/>Circle type: radius of the circle. | | Number of points | 7 | 2 | Number of points (n) in the point array. See below. | | Point array | 9 | n x 4 | The number of points (n) points. | ### Pebble Draw Command List | Field | Offset (bytes) | Size (bytes) | Description | |-------|----------------|--------------|-------------| | Number of commands | 0 | 2 | Number of Draw Commands in this Draw Command List. (`0` is invalid). | | Draw Command array | 2 | n x size of Draw Command | List of Draw Commands in the format [specified above](#pebble-draw-command). | ### Pebble Draw Command Frame | Field | Offset (bytes) | Size (bytes) | Description | |-------|----------------|--------------|-------------| | Duration | 0 | 2 | Duration of the frame in milliseconds. If `0`, the frame will not be shown at all (unless it is the last frame in a sequence). | | Command list | 2 | Size of Draw Command List | Pebble Draw Command List in the format [specified above](#pebble-draw-command-list). | ### Pebble Draw Command Image | Field | Offset (bytes) | Size (bytes) | Description | |-------|----------------|--------------|-------------| | Version | 8 | 1 | File version. | | Reserved | 9 | 1 | Reserved field. Must be `0`. | | [View box](#view-box) | 10 | 4 | Bounding box of the image. All Draw Commands are drawn relative to the top left corner of the view box. | | Command list | 14 | Size of Draw Command List | Pebble Draw Command List in the format [specified above](#pebble-draw-command-list). | ### Pebble Draw Command Sequence | Field | Offset (bytes) | Size (bytes) | Description | |-------|----------------|--------------|-------------| | Version | 8 | 1 | File version. | | Reserved | 9 | 1 | Reserved field. Must be `0`. | | [View box](#view-box) | 10 | 4 | Bounding box of the sequence. All Draw Commands are drawn relative to the top left corner of the view box. | | Play count | 14 | 2 | Number of times to repeat the sequence. A value of `0` will result in no playback at all, whereas a value of `0xFFFF` will repeat indefinitely. | | Frame count | 16 | 2 | Number of frames in the sequence. `0` is invalid. | | Frame list | 18 | n x size of Draw Command Frame | Array of Draw Command Frames in the format [specified above](#pebble-draw-command-frame). | ## File Formats ### Pebble Draw Command Image File | Field | Offset (bytes) | Size (bytes) | Description | |-------|----------------|--------------|-------------| | Magic word | 0 | 4 | ASCII characters spelling "PDCI". | | Image size | 4 | 4 | Size of the Pebble Draw Command Image (in bytes). | | Image | 8 | Size of Pebble Draw Command Image. | The Draw Command Image in the format [specified above](#pebble-draw-command-image). | ### Pebble Draw Command Sequence File | Field | Offset (bytes) | Size (bytes) | Description | |-------|----------------|--------------|-------------| | Magic word | 0 | 4 | ASCII characters spelling "PDCS". | | Sequence size | 4 | 4 | Size of the Pebble Draw Command Sequence (in bytes). | | Sequence | 8 | Size of Draw Command Sequence | The Draw Command Sequence in the format [specified above](#pebble-draw-command-sequence). |
{ "source": "google/pebble", "title": "devsite/source/_guides/app-resources/pdc-format.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/app-resources/pdc-format.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 7003 }
--- # Copyright 2025 Google LLC # # 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. title: Platform-specific Resources description: | How to include different resources for different platforms, as well as how to include a resource only on a particular platform. guide_group: app-resources order: 6 --- You may want to use different versions of a resource on one or more of the Aplite, Basalt or Chalk platforms. To enable this, it is now possible to "tag" resource files with the attributes that make them relevant to a given platform. The follows tags exist for each platform: | Aplite | Basalt | Chalk | Diorite | Emery | |---------|------------|------------|---------|------------| | rect | rect | round | rect | rect | | bw | color | color | bw | color | | aplite | basalt | chalk | diroite | emery | | 144w | 144w | 180w | 144w | 220w | | 168h | 168h | 180h | 168h | 228h | | compass | compass | compass | | compass | | | mic | mic | mic | mic | | | strap | strap | strap | strap | | | strappower | strappower | | strappower | | | health | health | health | health | To tag a resource, add the tags after the file's using tildes (`~`) — for instance, `example-image~color.png` to use the resource on only color platforms, or `example-image~color~round.png` to use the resource on only platforms with round, color displays. All tags must match for the file to be used. If no file matches for a platform, a compilation error will occur. If the correct file for a platform is ambiguous, an error will occur at compile time. You cannot, for instance, have both `example~color.png` and `example~round.png`, because it is unclear which image to use when building for Chalk. Instead, use `example~color~rect.png` and `example~round.png`. If multiple images could match, the one with the most tags wins. We recommend avoiding the platform specific tags (aplite, basalt etc). When we release new platforms in the future, you will need to create new files for that platform. However, if you use the descriptive tags we will automatically use them as appropriate. It is also worth noting that the platform tags are _not_ special: if you have `example~basalt.png` and `example~rect.png`, that is ambiguous (they both match Basalt) and will cause a compilation error. An example file structure is shown below. ```text my-project/ resources/ images/ example-image~bw.png example-image~color~rect.png example-image~color~round.png src/ main.c package.json wscript ``` This resource will appear in `package.json` as shown below. ``` "resources": { "media": [ { "type": "bitmap", "name": "EXAMPLE_IMAGE", "file": "images/example-image.png" } ] } ``` **Single-platform Resources** If you want to only include a resource on a **specific** platform, you can add a `targetPlatforms` field to the resource's entry in the `media` array in `package.json`. For example, the resource shown below will only be included for the Basalt build. ``` "resources": { "media": [ { "type": "bitmap", "name": "BACKGROUND_IMAGE", "file": "images/background.png", "targetPlatforms": [ "basalt" ] } ] } ```
{ "source": "google/pebble", "title": "devsite/source/_guides/app-resources/platform-specific.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/app-resources/platform-specific.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 3936 }
--- # Copyright 2025 Google LLC # # 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. title: Raw Data Files description: | How to add raw data resources to a project and read them in your app. guide_group: app-resources order: 7 platform_choice: true --- Some kinds of apps will require extra data that is not a font or an image. In these cases, the file can be included in a Pebble project as a raw resource. When a file is included as a raw resource, it is not modified in any way from the original when the app is built. Applications of this resource type can be found in the Pebble SDK for APIs such as ``GDrawCommand`` and ``GBitmapSequence``, which both use raw resources as input files. Other possible applications include localized string dictionaries, CSV data files, etc. ## Adding Raw Data Files {% platform local %} To add a file as a raw resource, specify its `type` as `raw` in `package.json`. An example is shown below: ```js "resources": { "media": [ { "type": "raw", "name": "EXAMPLE_DATA_FILE", "file": "data.bin" } ] } ``` {% endplatform %} {% platform cloudpebble %} To add a file as a raw resource, click 'Add New' in the Resources section of the sidebar, and set the 'Resource Type' as 'raw binary blob'. {% endplatform %} ## Reading Bytes and Byte Ranges Once a raw resource has been added to a project, it can be loaded at runtime in a manner similar to other resources types: ```c // Get resource handle ResHandle handle = resource_get_handle(RESOURCE_ID_DATA); ``` With a handle to the resource now available in the app, the size of the resource can be determined: ```c // Get size of the resource in bytes size_t res_size = resource_size(handle); ``` To read bytes from the resource, create an appropriate byte buffer and copy data into it: ```c // Create a buffer the exact size of the raw resource uint8_t *s_buffer = (uint8_t*)malloc(res_size); ``` The example below copies the entire resource into a `uint8_t` buffer: ```c // Copy all bytes to a buffer resource_load(handle, s_buffer, res_size); ``` It is also possible to read a specific range of bytes from a given offset into the buffer: ```c // Read the second set of 8 bytes resource_load_byte_range(handle, 8, s_buffer, 8); ```
{ "source": "google/pebble", "title": "devsite/source/_guides/app-resources/raw-data-files.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/app-resources/raw-data-files.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 2758 }
--- # Copyright 2025 Google LLC # # 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. title: System Fonts description: | A complete list of all the system fonts available for use in Pebble projects. guide_group: app-resources order: 8 --- The tables below show all the system font identifiers available in the Pebble SDK, sorted by family. A sample of each is also shown. ## Available System Fonts ### Raster Gothic <table> <thead> <th>Available Font Keys</th> <th>Preview</th> </thead> <tbody> <tr> <td><code>FONT_KEY_GOTHIC_14</code></td> <td><img src="/assets/images/guides/app-resources/fonts/gothic_14_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_GOTHIC_14_BOLD</code></td> <td><img src="/assets/images/guides/app-resources/fonts/gothic_14_bold_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_GOTHIC_18</code></td> <td><img src="/assets/images/guides/app-resources/fonts/gothic_18_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_GOTHIC_18_BOLD</code></td> <td><img src="/assets/images/guides/app-resources/fonts/gothic_18_bold_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_GOTHIC_24</code></td> <td><img src="/assets/images/guides/app-resources/fonts/gothic_24_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_GOTHIC_24_BOLD</code></td> <td><img src="/assets/images/guides/app-resources/fonts/gothic_24_bold_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_GOTHIC_28</code></td> <td><img src="/assets/images/guides/app-resources/fonts/gothic_28_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_GOTHIC_28_BOLD</code></td> <td><img src="/assets/images/guides/app-resources/fonts/gothic_28_bold_preview.png"/></td> </tr> </tbody> </table> ### Bitham <table> <thead> <th>Available Font Keys</th> <th>Preview</th> </thead> <tbody> <tr> <td><code>FONT_KEY_BITHAM_30_BLACK</code></td> <td><img src="/assets/images/guides/app-resources/fonts/bitham_30_black_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_BITHAM_34_MEDIUM_NUMBERS</code></td> <td><img src="/assets/images/guides/app-resources/fonts/bitham_34_medium_numbers_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_BITHAM_42_BOLD</code></td> <td><img src="/assets/images/guides/app-resources/fonts/bitham_42_bold_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_BITHAM_42_LIGHT</code></td> <td><img src="/assets/images/guides/app-resources/fonts/bitham_42_light_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_BITHAM_42_MEDIUM_NUMBERS</code></td> <td><img src="/assets/images/guides/app-resources/fonts/bitham_42_medium_numbers_preview.png"/></td> </tr> </tbody> </table> ### Roboto/Droid Serif <table> <thead> <th>Available Font Keys</th> <th>Preview</th> </thead> <tbody> <tr> <td><code>FONT_KEY_ROBOTO_CONDENSED_21</code></td> <td><img src="/assets/images/guides/app-resources/fonts/roboto_21_condensed_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_ROBOTO_BOLD_SUBSET_49</code></td> <td><img src="/assets/images/guides/app-resources/fonts/roboto_49_bold_subset_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_DROID_SERIF_28_BOLD</code></td> <td><img src="/assets/images/guides/app-resources/fonts/droid_28_bold_preview.png"/></td> </tr> </tbody> </table> ### LECO <table> <thead> <th>Available Font Keys</th> <th>Preview</th> </thead> <tbody> <tr> <td><code>FONT_KEY_LECO_20_BOLD_NUMBERS</code></td> <td><img src="/assets/images/guides/app-resources/fonts/leco_20_bold_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_LECO_26_BOLD_NUMBERS_AM_PM</code></td> <td><img src="/assets/images/guides/app-resources/fonts/leco_26_bold_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_LECO_28_LIGHT_NUMBERS</code></td> <td><img src="/assets/images/guides/app-resources/fonts/leco_28_light_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_LECO_32_BOLD_NUMBERS</code></td> <td><img src="/assets/images/guides/app-resources/fonts/leco_32_bold_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_LECO_36_BOLD_NUMBERS</code></td> <td><img src="/assets/images/guides/app-resources/fonts/leco_36_bold_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_LECO_38_BOLD_NUMBERS</code></td> <td><img src="/assets/images/guides/app-resources/fonts/leco_38_bold_preview.png"/></td> </tr><tr> <td><code>FONT_KEY_LECO_42_NUMBERS</code></td> <td><img src="/assets/images/guides/app-resources/fonts/leco_42_preview.png"/></td> </tr> </tbody> </table> ## Obtaining System Font Files The following system fonts are available to developers in the SDK can be found online for use in design mockups: * [Raster Gothic](http://www.marksimonson.com/) - By Mark Simonson * [Gotham (Bitham)](http://www.typography.com/fonts/gotham/overview/) - Available from Typography.com * [Droid Serif](https://www.google.com/fonts/specimen/Droid+Serif) - Available from Google Fonts * [LECO 1976](https://www.myfonts.com/fonts/carnoky/leco-1976/) - Available from Myfonts.com ## Using Emoji Fonts A subset of the built-in system fonts support the use of a set of emoji characters. These are the Gothic 24, Gothic 24 Bold, Gothic 18, and Gothic 18 Bold fonts, but do not include the full range. To print an emoji on Pebble, specify the code in a character string like the one shown below when using a ``TextLayer``, or ``graphics_draw_text()``: ```c text_layer_set_text(s_layer, "Smiley face: \U0001F603"); ``` An app containing a ``TextLayer`` displaying the above string will look similar to this: ![emoji-screenshot >{pebble-screenshot,pebble-screenshot--steel-black}](/images/guides/pebble-apps/resources/emoji-screenshot.png) The supported characters are displayed below with their corresponding unicode values. <img style="align: center;" src="/assets/images/guides/pebble-apps/resources/emoji1.png"/> ### Deprecated Emoji Symbols The following emoji characters are no longer available on the Aplite platform. <img style="align: center;" src="/assets/images/guides/pebble-apps/resources/emoji-unsupported.png"/>
{ "source": "google/pebble", "title": "devsite/source/_guides/app-resources/system-fonts.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/app-resources/system-fonts.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 6814 }
--- # Copyright 2025 Google LLC # # 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. title: Appstore Analytics description: | How to view and use analytics about your app's usage. guide_group: appstore-publishing order: 2 --- After publishing an app, developers can view automatic analytical data and graphs for a variety of metrics. These can be used to help track the performance of an app, identify when crashes start occuring, measure how fast an update is adopted, or which platforms are most popular with users. > Due to latencies in the analytics gathering process, data from the last 7 days > may not be very accurate. ## Available Metrics Several different metrics are available to developers, and are reported on a daily basis. These metrics can be sorted or viewed according to a number of categories: * App version - Which release of the app the user is running. * Hardware platform - Which Pebble hardware version the user is wearing. * Mobile platform - Which mobile phone platform (such as Android or iOS) the user is using. An example graph is shown with each metric type below, grouped by hardware platform. ### Installations The total number of times an app has been installed. ![installations-example](/images/guides/appstore-publishing/installations-example.png) ### Unique Users The total number of unique users who have installed the app. This is different to the installation metric due to users installing the same app multiple times. ![unique-users-example](/images/guides/appstore-publishing/unique-users-example.png) ### Launches The total number of times the app has been launched. ![launches-example](/images/guides/appstore-publishing/launches-example.png) ### Crash Count The total number of times the app has crashed. Use the filters to view crash count by platform or app version to help identify the source of a crash. ![crash-count-example](/images/guides/appstore-publishing/crash-count-example.png) ### Run Time The total run time of the app in hours. ![run-time-example](/images/guides/appstore-publishing/run-time-example.png) ### Run Time per launch The average run time of the app each time it was launched in minutes. ![run-time-per-launch-example](/images/guides/appstore-publishing/run-time-per-launch-example.png) ### Buttons Pressed Per Launch > Watchfaces only The average number of button presses per launch of the app. ![buttons-pressed-example](/images/guides/appstore-publishing/buttons-pressed-example.png) ### Timeline: Users Opening Pin > Timeline-enabled apps only The number of users opening timeline pins associated with the app. ![opening-pin-example](/images/guides/appstore-publishing/opening-pin-example.png) ### Timeline: Pins Opened > Timeline-enabled apps only The number of timeline pins opened. ![pins-opened-example](/images/guides/appstore-publishing/pins-opened-example.png) ### Timeline: Users Launching App from Pin > Timeline-enabled apps only The number of users launching the app from a timeline pin. ![launching-app-from-pin-example](/images/guides/appstore-publishing/launching-app-from-pin-example.png) ### Timeline: Times App Launched from Pin > Timeline-enabled apps only Number of times the app was launched from a timeline pin. ![times-launched-example](/images/guides/appstore-publishing/times-launched-example.png) ## Battery Stats In addition to installation, run time, and launch statistics, developers can also view a battery grade for their app. Grade 'A' is the best available, indicating that the app is very battery friendly, while grade 'F' is the opposite (the app is severely draining the user's battery). > An app must reach a certain threshold of data before battery statistics can be > reliably calculated. This is around 200 users. This is calculated based upon how much a user's battery decreased while the app was open, and so does not take into other factors such as account notifications or backlight activity during that time. ![grade](/images/guides/appstore-publishing/grade.png) Clicking 'View More Details' will show a detailed breakdown for all the data available across all app versions. ![grade-versions](/images/guides/appstore-publishing/grade-versions.png)
{ "source": "google/pebble", "title": "devsite/source/_guides/appstore-publishing/appstore-analytics.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/appstore-publishing/appstore-analytics.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 4732 }
--- # Copyright 2025 Google LLC # # 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. title: Appstore Assets description: | A collection of downloads to help developers create and improve their appstore listings. guide_group: appstore-publishing order: 3 --- A number of graphical assets are required when publishing an app on the [Developer Portal](https://dev-portal.getpebble.com/), such as a marketing banners. The resources on this page serve to help developers give these assets a more authentic feel. ## Example Marketing Banners Example [marketing banners](https://s3.amazonaws.com/developer.getpebble.com/assets/other/banner-examples.zip) from existing apps may help provide inspiration for an app's appstore banner design. Readable fonts, an appropriate background image, and at least one framed screenshot are all recommended. ## Marketing Banner Templates ![](/images/guides/appstore-publishing/perspective-right.png =400x) Use these [blank PSD templates](https://s3.amazonaws.com/developer.getpebble.com/assets/other/banner-templates-design.zip) to start a new app marketing banner in Photoshop from a template. ## App Screenshot Frames Use these [example screenshot frames](https://s3.amazonaws.com/developer.getpebble.com/assets/other/pebble-frames.zip) for Pebble, Pebble Steel, Pebble Time, Pebble Time Steel, and Pebble Time Round to decorate app screenshots in marketing banners and other assets. > Note: The screenshots added to the listing itself must not be framed.
{ "source": "google/pebble", "title": "devsite/source/_guides/appstore-publishing/appstore-assets.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/appstore-publishing/appstore-assets.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 2002 }
--- # Copyright 2025 Google LLC # # 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. title: Appstore Publishing description: | How to get your app ready for going live in the Pebble appstore. guide_group: appstore-publishing menu: false permalink: /guides/appstore-publishing/ generate_toc: false hide_comments: true --- When a developer is happy that their app is feature-complete and stable, they can upload the compiled `.pbw` file to the [Developer Portal](https://dev-portal.getpebble.com) to make it available on the Pebble appstore for all users with compatible watches to share and enjoy. In order to be successfully listed in the Pebble appstore the developer must: * Provide all required assets and marketing material. * Provide at least one `.pbw` release. * Use a unique and valid UUID. * Build their app with a non-beta SDK. * Ensure their app complies with the various legal agreements. Information on how to meet these requirements is given in this group of guides, as well as details about available analytical data for published apps and example asset material templates. ## Contents {% include guides/contents-group.md group=page.group_data %}
{ "source": "google/pebble", "title": "devsite/source/_guides/appstore-publishing/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/appstore-publishing/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 1669 }
--- # Copyright 2025 Google LLC # # 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. title: Preparing a Submission description: | How to prepare an app submission for the Pebble appstore. guide_group: appstore-publishing order: 0 --- Once a new Pebble watchface or watchapp has been created, the [Pebble Developer Portal](https://dev-portal.getpebble.com/) allows the developer to publish their creation to the appstore either publicly, or privately. The appstore is built into the official mobile apps and means that every new app can be found and also featured for increased exposure and publicity. > Note: An app can only be published privately while it is not already published > publicly. If an app is already public, it must be unpublished before it can be > made private. To build the appstore listing for a new app, the following resources are required from the developer. Some may not be required, depending on the type of app being listed. Read {% guide_link appstore-publishing/publishing-an-app#listing-resources "Listing Resources" %} for a comparison. ## Basic Info | Resource | Details | |----------|---------| | App title | Title of the app. | | Website URL | Link to the brand or other website related to the app. | | Source code URL | Link to the source code of the app (such as GitHub or BitBucket). | | Support email address | An email address for support issues. If left blank, the developer's account email address will be used. | | Category | A watchapp may be categorized depending on the kind of functionality it offers. Users can browse the appstore by these categories. | | Icons | A large and small icons representing the app. | ## Asset Collections An asset collection must be created for each of the platforms that the app supports. These are used to tailor the description and screenshots shown to users browing with a specific platform connected. | Resource | Details | |----------|---------| | Description | The details and features of the app. Maximum 1600 characters. | | Screenshots | Screenshots showing off the design and features of the app. Maximum 5 per platform in PNG, GIF, or Animated GIF format. | | Marketing banner | Large image used at the top of a listing in some places, as well as if an app is featured on one of the main pages. | ## Releases In addition to the visual assets in an appstore listing, the developer must upload at least one valid release build in the form of a `.pbw` file generated by the Pebble SDK. This is the file that will be distributed to users if they choose to install your app. The appstore will automatically select the appropriate version to download based on the SDK version. This is normally the latest release, with the one exception of the latest release built for SDK 2.x (deprecated) distributed to users running a watch firmware less than 3.0. A release is considered valid if the UUID is not in use and the version is greater than all previously published releases. ## Companion Apps If your app requires an Android or iOS companion app to function, it can be listed here by providing the name, icon, and URL that users can use to obtain the companion app. When a user install the watchapp, they will be prompted to also download the companion app automatically. ## Timeline Developers that require the user of the timeline API will need to click 'Enable timeline' to obtain API keys used for pushing pins. See the {% guide_link pebble-timeline %} guides for more information. ## Promotion Once published, the key to growth in an app is through promotion. Aside from users recommending the app to each other, posting on websites such as the [Pebble Forums](https://forums.getpebble.com/categories/watchapp-directory), [Reddit](https://www.reddit.com/r/pebble), and [Twitter](https://twitter.com) can help increase exposure. ## Developer Retreat Video Watch the presentation given by Aaron Cannon at the 2016 Developer Retreat to learn more about preparing asset collections for the appstore. [EMBED](//www.youtube.com/watch?v=qXmz3eINObU&index=10&list=PLDPHNsf1sb48bgS5oNr8hgFz0pL92XqtO)
{ "source": "google/pebble", "title": "devsite/source/_guides/appstore-publishing/preparing-a-submission.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/appstore-publishing/preparing-a-submission.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 4603 }
--- # Copyright 2025 Google LLC # # 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. title: Publishing an App description: | How to upload and publish an app in the Pebble appstore. guide_group: appstore-publishing order: 1 --- When an app is ready for publishing, the `.pbw` file needs to be uploaded to the Pebble [Developer Portal](https://dev-portal.getpebble.com/), where a listing is created. Depending on the type of app, different sets of additional resources are required. These resources are then used to generate the listing pages visible to potential users in the Pebble appstore, which is embedded within the Pebble mobile app. You can also view the [watchfaces](http://apps.getpebble.com/en_US/watchfaces) and [watchapps](http://apps.getpebble.com/en_US/watchapps) from a desktop computer, as well as perform searches and get shareable links. ## Listing Resources The table below gives a summary of which types of resources required by different types of app. Use this to quickly assess how complete assets and resources are before creating the listing. | Resource | Watchface | Watchapp | Companion | |----------|-----------|----------|-----------| | Title | Yes | Yes | Yes | | `.pbw` release build | Yes | Yes | - | | Asset collections | Yes | Yes | Yes | | Category | - | Yes | Yes | | Large and small icons | - | Yes | Yes | | Compatible platforms | - | - | Yes | | Android or iOS companion appstore listing | - | - | Yes | ## Publishing a Watchface 1. After logging in, click 'Add a Watchface'. 2. Enter the basic details of the watchface, such as the title, source code URL, and support email (if different from the one associated with this developer account): ![face-title](/images/guides/appstore-publishing/face-title.png) 3. Click 'Create' to be taken to the listing page. This page details the status of the listing, including links to subpages, a preview of the public page, and any missing information preventing release. ![face-listing](/images/guides/appstore-publishing/face-listing.png) 4. The status now says 'Missing: At least one published release'. Click 'Add a release' to upload the `.pbw`, optionally adding release notes: ![face-release](/images/guides/appstore-publishing/face-release.png) 5. Click 'Save'. After reloading the page, make the release public by clicking 'Publish' next to the release: ![face-release-publish](/images/guides/appstore-publishing/face-release-publish.png) 6. The status now says 'Missing: A complete X asset collection' for each X supported platform. Click 'Manage Asset Collections', then click 'Create' for a supported platform. 7. Add a description, up to 5 screenshots, and optionally a marketing banner before clicking 'Create Asset Collection'. ![face-assets](/images/guides/appstore-publishing/face-assets.png) 8. Once all asset collections required have been created, click 'Publish' or 'Publish Privately' to make the app available only to those viewing it through the direct link. Note that once made public, an app cannot then be made private. 9. After publishing, reload the page to get the public appstore link for social sharing, as well as a deep link that can be used to directly open the appstore in the mobile app. ## Publishing a Watchapp 1. After logging in, click 'Add a Watchapp'. 2. Enter the basic details of the watchapp, such as the title, source code URL, and support email (if different from the one associated with this developer account): ![app-title](/images/guides/appstore-publishing/app-title.png) 3. Select the most appropriate category for the app, depending on the features it provides: ![app-category](/images/guides/appstore-publishing/app-category.png) 4. Upload the large and small icons representing the app: ![app-icons](/images/guides/appstore-publishing/app-icons.png) 5. Click 'Create' to be taken to the listing page. This page details the status of the listing, including links to subpages, a preview of the public page, and any missing information preventing release. ![app-listing](/images/guides/appstore-publishing/app-listing.png) 6. The status now says 'Missing: At least one published release'. Click 'Add a release' to upload the `.pbw`, optionally adding release notes: ![app-release](/images/guides/appstore-publishing/app-release.png) 7. Click 'Save'. After reloading the page, make the release public by clicking 'Publish' next to the release: ![face-release-publish](/images/guides/appstore-publishing/face-release-publish.png) 8. The status now says 'Missing: A complete X asset collection' for each X supported platform. Click 'Manage Asset Collections', then click 'Create' for a supported platform. 9. Add a description, up to 5 screenshots, optionally up to three header images, and a marketing banner before clicking 'Create Asset Collection'. ![app-assets](/images/guides/appstore-publishing/app-assets.png) 10. Once all asset collections required have been created, click 'Publish' or 'Publish Privately' to make the app available only to those viewing it through the direct link. 11. After publishing, reload the page to get the public appstore link for social sharing, as well as a deep link that can be used to directly open the appstore in the mobile app. ## Publishing a Companion App > A companion app is one that is written for Pebble, but exists on the Google > Play store, or the Appstore. Adding it to the Pebble appstore allows users to > discover it from the mobile app. 1. After logging in, click 'Add a Companion App'. 2. Enter the basic details of the companion app, such as the title, source code URL, and support email (if different from the one associated with this developer account): ![companion-title](/images/guides/appstore-publishing/companion-title.png) 3. Select the most appropriate category for the app, depending on the features it provides: ![companion-category](/images/guides/appstore-publishing/companion-category.png) 4. Check a box beside each hardware platform that the companion app supports. For example, it may be a photo viewer app that does not support Aplite. 5. Upload the large and small icons representing the app: ![companion-icons](/images/guides/appstore-publishing/companion-icons.png) 6. Click 'Create' to be taken to the listing page. The status will now read 'Missing: At least one iOS or Android application'. Add the companion app with eithr the 'Add Android Companion' or 'Add iOS Companion' buttons (or both!). 7. Add the companion app's small icon, the name of the other appstore app's name, as well as the direct link to it's location in the appropriate appstore. If it has been compiled with a PebbleKit 3.0, check that box: ![companion-link](/images/guides/appstore-publishing/companion-link.png) 8. Once the companion appstore link has been added, click 'Publish' or 'Publish Privately' to make the app available only to those viewing it through the direct link. 9. After publishing, reload the page to get the public appstore link for social sharing, as well as a deep link that can be used to directly open the appstore in the mobile app.
{ "source": "google/pebble", "title": "devsite/source/_guides/appstore-publishing/publishing-an-app.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/appstore-publishing/publishing-an-app.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 7788 }
--- # Copyright 2025 Google LLC # # 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. title: iOS App Whitelisting description: | Instructions to iOS developers to get their Pebble apps whitelisted. guide_group: appstore-publishing generate_toc: false order: 4 --- Pebble is part of the Made For iPhone program, a requirement that hardware accessories must meet to interact with iOS apps. If an iOS app uses PebbleKit iOS, it must be whitelisted **before** it can be submitted to the Apple App Store for approval. ## Requirements * The iOS companion app must only start communication with a Pebble watch on an explicit action in the UI. It cannot auto­start upon connection and it must stop whenever the user stops using it. Refer to the {% guide_link communication/using-pebblekit-ios %} guide for details. * `com.getpebble.public` is the only external accessory protocol that can be used by 3rd party apps. Make sure this is listed in the `Info.plist` in the `UISupportedExternalAccessoryProtocols` array. * Pebble may request a build of the iOS application. If this happens, the developer will be supplied with UDIDs to add to the provisioning profile. TestFlight/HockeyApp is the recommended way to share builds with Pebble. [Whitelist a New App >{center,bg-lightblue,fg-white}](http://pbl.io/whitelist) After whitelisting of the new app has been confirmed, add the following information to the "Review Notes" section of the app's Apple app submission: <div style="text-align: center;"> <strong>MFI PPID 126683­-0003</strong> </div> > Note: An iOS app does not need to be re-whitelisted every time a new update is > released. However, Pebble reserves the right to remove an application from the > whitelist if it appears that the app no longer meets these requirements.
{ "source": "google/pebble", "title": "devsite/source/_guides/appstore-publishing/whitelisting.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/appstore-publishing/whitelisting.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 2293 }
--- # Copyright 2025 Google LLC # # 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. title: Building for Every Pebble description: How to write one app compatible with all Pebble smartwatches. guide_group: best-practices order: 0 --- The difference in capabilities between the various Pebble hardware platforms are listed in {% guide_link tools-and-resources/hardware-information %}. For example, the Basalt, Chalk and Emery platforms support 64 colors, whereas the Aplite and Diorite platforms only support two colors. This can make developing apps with rich color layouts difficult when considering compatibility with other non-color hardware. Another example is using platform specific APIs such as Health or Dictation. To make life simple for users, developers should strive to write one app that can be used on all platforms. To help make this task simpler for developers, the Pebble SDK provides numerous methods to accommodate different hardware capabilities in code. ## Preprocessor Directives It is possible to specify certain blocks of code to be compiled for specific purposes by using the `#ifdef` preprocessor statement. For example, the ``Dictation`` API should be excluded on platforms with no microphone: ```c #if defined(PBL_MICROPHONE) // Start dictation UI dictation_session_start(s_dictation_session); #else // Microphone is not available text_layer_set_text(s_some_layer, "Dictation not available!"); #endif ``` When designing UI layouts, any use of colors on compatible platforms can be adapted to either black or white on non-color platforms. The `PBL_COLOR` and `PBL_BW` symbols will be defined at compile time when appropriate capabilities are available: ```c #if defined(PBL_COLOR) text_layer_set_text_color(s_text_layer, GColorRed); text_layer_set_background_color(s_text_layer, GColorChromeYellow); #else text_layer_set_text_color(s_text_layer, GColorWhite); text_layer_set_background_color(s_text_layer, GColorBlack); #endif ``` This is useful for blocks of multiple statements that change depending on the availability of color support. For single statements, this can also be achieved by using the ``PBL_IF_COLOR_ELSE()`` macro. ```c window_set_background_color(s_main_window, PBL_IF_COLOR_ELSE(GColorJaegerGreen, GColorBlack)); ``` See below for a complete list of defines and macros available. ## Available Defines and Macros The tables below show a complete summary of all the defines and associated macros available to conditionally compile or omit feature-dependant code. The macros are well-suited for individual value selection, whereas the defines are better used to select an entire block of code. | Define | MACRO |Available | |--------|-------|----------| | `PBL_BW` | `PBL_IF_BW_ELSE()` | Running on hardware that supports only black and white. | | `PBL_COLOR` | `PBL_IF_COLOR_ELSE()` | Running on hardware that supports 64 colors. | | `PBL_MICROPHONE` | `PBL_IF_MICROPHONE_ELSE()` | Running on hardware that includes a microphone. | | `PBL_COMPASS` | None | Running on hardware that includes a compass. | | `PBL_SMARTSTRAP` | `PBL_IF_SMARTSTRAP_ELSE()` | Running on hardware that includes a smartstrap connector, but does not indicate that the connector is capable of supplying power. | | `PBL_SMARTSTRAP_POWER` | None | Running on hardware that includes a smartstrap connector capable of supplying power. | | `PBL_HEALTH` | `PBL_IF_HEALTH_ELSE()` | Running on hardware that supports Pebble Health and the `HealthService` API. | | `PBL_RECT` | `PBL_IF_RECT_ELSE()` | Running on hardware with a rectangular display. | | `PBL_ROUND` | `PBL_IF_ROUND_ELSE()` | Running on hardware with a round display. | | `PBL_DISPLAY_WIDTH` | None | Determine the screen width in pixels. | | `PBL_DISPLAY_HEIGHT` | None | Determine the screen height in pixels. | | `PBL_PLATFORM_APLITE` | None | Built for Pebble/Pebble Steel. | | `PBL_PLATFORM_BASALT` | None | Built for Pebble Time/Pebble Time Steel. | | `PBL_PLATFORM_CHALK` | None | Built for Pebble Time Round. | | `PBL_PLATFORM_DIORITE` | None | Built for Pebble 2. | | `PBL_PLATFORM_EMERY` | None | Built for Pebble Time 2. | | `PBL_SDK_2` | None | Compiling with SDK 2.x (deprecated). | | `PBL_SDK_3` | None | Compiling with SDK 3.x. or 4.x. | > Note: It is strongly recommended to conditionally compile code using > applicable feature defines instead of `PBL_PLATFORM` defines to be as specific > as possible. ## API Detection In addition to platform and capabilities detection, we now provide API detection to detect if a specific API method is available. This approach could be considered future-proof, since platforms and capabilities may come and go. Let's take a look at a simple example: ```c #if PBL_API_EXISTS(health_service_peek_current_value) // Do something if specific Health API exists #endif ``` ## Avoid Hardcoded Layout Values With the multiple display shapes and resolutions available, developers should try and avoid hardcoding layout values. Consider the example below: ```c static void window_load(Window *window) { // Create a full-screen Layer - BAD s_some_layer = layer_create(GRect(0, 0, 144, 168)); } ``` The hardcoded width and height of this layer will cover the entire screen on Aplite, Basalt and Diorite, but not on Chalk or Emery. This kind of screen size-dependant calculation should use the ``UnobstructedArea`` bounds of the ``Window`` itself: ```c static void window_load(Window *window) { // Get the unobstructed bounds of the Window Layer window_layer = window_get_root_layer(window); GRect window_bounds = layer_get_unobstructed_bounds(window_layer); // Properly create a full-screen Layer - GOOD s_some_layer = layer_create(window_bounds); } ``` Another common use of this sort of construction is to make a ``Layer`` that is half the unobstructed screen height. This can also be correctly achieved using the ``Window`` unobstructed bounds: ```c GRect layer_bounds = window_bounds; layer_bounds.size.h /= 2; // Create a Layer that is half the screen height s_some_layer = layer_create(layer_bounds); ``` This approach is also advantageous in simplifying updating an app for a future new screen size, as proportional layout values will adapt as appropriate when the ``Window`` unobstructed bounds change. ## Screen Sizes To ease the introduction of the Emery platform, the Pebble SDK introduced new compiler directives to allow developers to determine the screen width and height. This is preferable to using platform detection, since multiple platforms share the same screen width and height. ```c #if PBL_DISPLAY_HEIGHT == 228 uint8_t offset_y = 100; #elif PBL_DISPLAY_HEIGHT == 180 uint8_t offset_y = 80; #else uint8_t offset_y = 60; #endif ``` > Note: Although this method is preferable to platform detection, it is better to dynamically calculate the display width and height based on the unobstructed bounds of the root layer. ## Pebble C WatchInfo The ``WatchInfo`` API can be used to determine exactly which Pebble model and color an app is running on. Apps can use this information to dynamically modify their layout or behavior depending on which Pebble the user is wearing. For example, the display on Pebble Steel is located at a different vertical position relative to the buttons than on Pebble Time. Any on-screen button hints can be adjusted to compensate for this using ``WatchInfoModel``. ```c static void window_load(Window *window) { Layer window_layer = window_get_root_layer(window); GRect window_bounds = layer_get_bounds(window_layer); int button_height, y_offset; // Conditionally set layout parameters switch(watch_info_get_model()) { case WATCH_INFO_MODEL_PEBBLE_STEEL: y_offset = 64; button_height = 44; break; case WATCH_INFO_MODEL_PEBBLE_TIME: y_offset = 58; button_height = 56; break; /* Other cases */ default: y_offset = 0; button_height = 0; break; } // Set the Layer frame GRect layer_frame = GRect(0, y_offset, window_bounds.size.w, button_height); // Create the Layer s_label_layer = text_layer_create(layer_frame); layer_add_child(window_layer, text_layer_get_layer(s_label_layer)); /* Other UI code */ } ``` Developers can also use ``WatchInfoColor`` values to theme an app for each available color of Pebble. ```c static void window_load(Window *window) { GColor text_color, background_color; // Choose different theme colors per watch color switch(watch_info_get_color()) { case WATCH_INFO_COLOR_RED: // Red theme text_color = GColorWhite; background_color = GColorRed; break; case WATCH_INFO_COLOR_BLUE: // Blue theme text_color = GColorBlack; background_color = GColorVeryLightBlue; break; /* Other cases */ default: text_color = GColorBlack; background_color = GColorWhite; break; } // Use the conditionally set value text_layer_set_text_color(s_label_layer, text_color); text_layer_set_background_color(s_label_layer, background_color); /* Other UI code */ } ``` ## PebbleKit JS Watch Info Similar to [*Pebble C WatchInfo*](#pebble-c-watchinfo) above, the PebbleKit JS ``Pebble.getActiveWatchInfo()`` method allows developers to determine which model and color of Pebble the user is wearing, as well as the firmware version running on it. For example, to obtain the model of the watch: > Note: See the section below to avoid problem using this function on older app > version. ```js // Get the watch info var info = Pebble.getActiveWatchInfo(); console.log('Pebble model: ' + info.model); ``` ## Detecting Platform-specific JS Features A number of features in PebbleKit JS (such as ``Pebble.timelineSubscribe()`` and ``Pebble.getActiveWatchInfo()``) exist on SDK 3.x. If an app tries to use any of these on an older Pebble mobile app version where they are not available, the JS app will crash. To prevent this, be sure to check for the availability of the function before calling it. For example, in the case of ``Pebble.getActiveWatchInfo()``: ```js if (Pebble.getActiveWatchInfo) { // Available. var info = Pebble.getActiveWatchInfo(); console.log('Pebble model: ' + info.model); } else { // Gracefully handle no info available } ``` ## Platform-specific Resources With the availability of color support on Basalt, Chalk and Emery, developers may wish to include color versions of resources that had previously been pre-processed for Pebble's black and white display. Including both versions of the resource is expensive from a resource storage perspective, and lays the burden of packing redundant color resources in an Aplite or Diorite app when built for multiple platforms. To solve this problem, the Pebble SDK allows developers to specify which version of an image resource is to be used for each display type, using `~bw` or `~color` appended to a file name. Resources can also be bundled only with specific platforms using the `targetPlatforms` property for each resource. For more details about packaging resources specific to each platform, as well as more tags available similar to `~color`, read {% guide_link app-resources/platform-specific %}. ## Multiple Display Shapes With the introduction of the Chalk platform, a new round display type is available with increased pixel resolution. To distinguish between the two possible shapes of display, developers can use defines to conditionally include code segments: ```c #if defined(PBL_RECT) printf("This is a rectangular display!"); #elif defined(PBL_ROUND) printf("This is a round display!"); #endif ``` Another approach to this conditional compilation is to use the ``PBL_IF_RECT_ELSE()`` and ``PBL_IF_ROUND_ELSE()`` macros, allowing values to be inserted into expressions that might otherwise require a set of `#define` statements similar to the previous example. This would result in needless verbosity of four extra lines of code when only one is actually needed. These are used in the following manner: ```c // Conditionally print out the shape of the display printf("This is a %s display!", PBL_IF_RECT_ELSE("rectangular", "round")); ``` This mechanism is best used with window bounds-derived layout size and position value. See the [*Avoid Hardcoded Layout Values*](#avoid-hardcoded-layout-values) section above for more information. Making good use of the builtin ``Layer`` types will also help safeguard apps against display shape and size changes. Another thing to consider is rendering text on a round display. Due to the rounded corners, each horizontal line of text will have a different available width, depending on its vertical position.
{ "source": "google/pebble", "title": "devsite/source/_guides/best-practices/building-for-every-pebble.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/best-practices/building-for-every-pebble.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 13204 }
--- # Copyright 2025 Google LLC # # 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. title: Conserving Battery Life description: How to write an app to consume power as efficiently as possible. guide_group: best-practices order: 1 related_docs: - Animation - Timer - AccelerometerService - BatteryStateService - TickTimerService - CompassService - Vibes - Light related_examples: - title: Pebble Glancing Demo url: https://github.com/pebble-hacks/pebble_glancing_demo --- One of Pebble's strengths is its long battery life. This is due in part to using a low-power display technology, conservative use of the backlight, and allowing the processor to sleep whenever possible. It therefore follows that apps which misuse high-power APIs or prevent power-saving mechanisms from working will detract from the user's battery life. Several common causes of battery drain in apps are discussed in this guide, alongside suggestions to help avoid them. ## Battery Ratings Any app published in the [Developer Portal](https://dev-portal.getpebble.com) will have a battery grade associated with it, once a minimum threshold of data has been collected. This can be used to get a rough idea of how much battery power the app consumes. For watchfaces and apps that will be launched for long periods of time, making sure this grade is in the A - C range should be a priority. Read {% guide_link appstore-publishing/appstore-analytics %} to learn more about this rating system. ## Time Awake Because the watch tries to sleep as much as possible to conserve power, any app that keeps the watch awake will incur significant a battery penalty. Examples of such apps include those that frequently use animations, sensors, Bluetooth communications, and vibrations. ### Animations and Display Updates A common cause of such a drain are long-running animations that cause frequent display updates. For example, a watchface that plays a half-second ``Animation`` for every second that ticks by will drain the battery faster than one that does so only once per minute. The latter approach will allow a lot more time for the watch to sleep. ```c static void tick_handler(struct tm *tick_time, TimeUnits changed) { // Update time set_time_digits(tick_time); // Only update once a minute if(tick_time->tm_sec == 0) { play_animation(); } } ``` This also applies to apps that make use of short-interval ``Timer``s, which is another method of creating animations. Consider giving users the option to reduce or disable animations to further conserve power, as well as removing or shortening animations that are not essential to the app's function or aesthetic. However, not all animations are bad. Efficient use of the battery can be maintained if the animations are played at more intelligent times. For example, when the user is holding their arm to view the screen (see [`pebble_glancing_demo`](https://github.com/pebble-hacks/pebble_glancing_demo)) or only when a tap or wrist shake is detected: ```c static void accel_tap_handler(AccelAxisType axis, int32_t direction) { // Animate when the user flicks their wrist play_animation(); } ``` ```c accel_tap_service_subscribe(tap_handler); ``` ### Tick Updates Many watchfaces unecessarily tick once a second by using the ``SECOND_UNIT`` constant value with the ``TickTimerService``, when they only update the display once a minute. By using the ``MINUTE_UNIT`` instead, the amount of times the watch is woken up per minute is reduced. ```c // Only tick once a minute, much more time asleep tick_timer_service_subscribe(MINUTE_UNIT, tick_handler); ``` If possible, give users the choice to disable the second hand tick and/or animation to further save power. Extremely minimal watchfaces may also use the ``HOUR_UNIT`` value to only be updated once per hour. This factor is especially important for Pebble Time Round users. On this platform the reduced battery capacity means that a watchface with animations that play every second could reduce this to one day or less. Consider offering configuration options to reducing tick updates on this platform to save power where it at a premium. ### Sensor Usage Apps that make frequent usage of Pebble's onboard accelerometer and compass sensors will also prevent the watch from going to sleep and consume more battery power. The ``AccelerometerService`` API features the ability to configure the sampling rate and number of samples received per update, allowing batching of data into less frequent updates. By receiving updates less frequently, the battery will last longer. ```c // Batch samples into sets of 10 per callback const uint32_t num_samples = 10; // Sample at 10 Hz accel_service_set_sampling_rate(ACCEL_SAMPLING_10HZ); // With this combination, only wake up the app once per second! accel_data_service_subscribe(num_samples, accel_data_handler); ``` Similarly, the ``CompassService`` API allows a filter to be set on the heading updates, allowing an app to only be notified per every 45 degree angle change, for example. ```c // Only update if the heading changes significantly compass_service_set_heading_filter(TRIG_MAX_ANGLE / 36); ``` In addition, making frequent use of the ``Dictation`` API will also keep the watch awake, and also incur a penalty for keeping the Bluetooth connection alive. Consider using the ``Storage`` API to remember previous user input and instead present a list of previous inputs if appropriate to reduce usage of this API. ```c static void dictation_session_callback(DictationSession *session, DictationSessionStatus status, char *transcription, void *context) { if(status == DictationSessionStatusSuccess) { // Display the dictated text snprintf(s_last_text, sizeof(s_last_text), "Transcription:\n\n%s", transcription); text_layer_set_text(s_output_layer, s_last_text); // Save for later! const int last_text_key = 0; persist_write_string(last_text_key, s_last_text); } } ``` ### Bluetooth Usage Hinted at above, frequent use of the ``AppMessage`` API to send and recieve data will cause the Bluetooth connection to enter a more responsive state, which consumes much more power. A small time after a message is sent, the connection will return back to a low-power state. The 'sniff interval' determines how often the API checks for new messages from the phone, and should be let in the default ``SNIFF_INTERVAL_NORMAL`` state as much as possible. Consider how infrequent communication activities can be to save power and maintain functionality, and how data obtained over the Bluetooth connection can be cached using the ``Storage`` API to reduce the frequency of updates (for example, weather information in watchface). If the reduced sniff state must be used to transfer large amounts of data quickly, be sure to return to the low-power state as soon as the transfer is complete: ```c // Return to low power Bluetooth state app_comm_set_sniff_interval(SNIFF_INTERVAL_NORMAL); ``` ## Backlight Usage The backlight LED is another large consumer of battery power. System-level backlight settings may see the backlight turn on for a few seconds every time a button is pressed. While this setting is out of the hands of developers, apps can work to reduce the backlight on-time by minimizing the number of button presses required to operate them. For example, use an ``ActionBarLayer`` to execute common actions with one button press instead of a long scrolling ``MenuLayer``. While the ``Light`` API is available to manually turn the backlight on, it should not be used for more than very short periods, if at all. Apps that keep the backlight on all the time will not last more than a few hours. If the backlight must be kept on for an extended period, make sure to return to the automatic mode as soon as possible: ```c // Return to automatic backlight control light_enable(false); ``` ## Vibration Motor Usage As a physical converter of electrical to mechanical energy, the vibration motor also consumes a lot of power. Users can elect to use Quiet Time or turn off vibration for notifications to save power, but apps can also contribute to this effort. Try and keep the use of the ``Vibes`` API to a minimum and giving user the option to disable any vibrations the app emits. Another method to reduce vibrator power consumtion is to shorten the length of any custom sequences used. ## Learn More To learn more about power consumtion on Pebble and how battery life can be extended through app design choices, watch the presentation below given at the 2014 Developer Retreat. [EMBED](//www.youtube.com/watch?v=TS0FPfgxAso)
{ "source": "google/pebble", "title": "devsite/source/_guides/best-practices/conserving-battery-life.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/best-practices/conserving-battery-life.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 9253 }
--- # Copyright 2025 Google LLC # # 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. title: Best Practices description: | Information to help optimize apps and ensure a good user experience. guide_group: best-practices menu: false permalink: /guides/best-practices/ generate_toc: false hide_comments: true --- In order to get the most out of the Pebble SDK, there are numerous opportunities for optimization that can allow apps to use power more efficiently, display correctly on all display shapes and sizes, and help keep large projects maintainable. Information on these topics is contained in this collection of guides. Pebble recommends that developers try and incorporate as many of these practices into their apps as possible, to give themselves and users the best experience of their app. ## Contents {% include guides/contents-group.md group=page.group_data %}
{ "source": "google/pebble", "title": "devsite/source/_guides/best-practices/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/best-practices/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 1371 }
--- # Copyright 2025 Google LLC # # 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. title: Modular App Architecture description: | How to break up a complex app into smaller pieces for managablilty, modularity and reusability. guide_group: best-practices order: 3 related_examples: - title: Modular App Example url: https://github.com/pebble-examples/modular-app-example/ --- Most Pebble projects (such as a simple watchface) work fine as a single-file project. This means that all the code is located in one `.c` file. However, as the size of a single-file Pebble project increases, it can become harder to keep track of where all the different components are located, and to track down how they interact with each other. For example, a hypothetical app may have many ``Window``s, perform communication over ``AppMessage`` with many types of data items, store and persist a large number of data items, or include components that may be valuable in other projects. As a first example, the Pebble SDK is already composed of separate modules such as ``Window``, ``Layer``, ``AppMessage`` etc. The implementation of each is separate from the rest and the interface for developers to use in each module is clearly defined and will rarely change. This guide aims to provide techniques that can be used to break up such an app. The advantages of a modular approach include: * App ``Window``s can be kept separate and are easier to work on. * A clearly defined interface between components ensures internal changes do not affect other modules. * Modules can be re-used in other projects, or even made into sharable libraries. * Inter-component variable dependencies do not occur, which can otherwise cause problems if their type or size changes. * Sub-component complexity is hidden in each module. * Simpler individual files promote maintainability. * Modules can be more easily tested. ## A Basic Project A basic Pebble project starts life with the `new-project` command: ```bash $ pebble new-project modular-project ``` This new project will contain the following default file structure. The `modular-project.c` file will contain the entire app, including `main()`, `init()` and `deinit()`, as well as a ``Window`` and a child ``TextLayer``. ```text modular-project/ resources/ src/ modular-project.c package.json wscript ``` For most projects, this structure is perfectly adequate. When the `.c` file grows to several hundred lines long and incorporates several sub-components with many points of interaction with each other through shared variables, the complexity reaches a point where some new techniques are needed. ## Creating a Module In this context, a 'module' can be thought of as a C header and source file 'pair', a `.h` file describing the module's interface and a `.c` file containing the actual logic and code. The header contains standard statements to prevent redefinition from being `#include`d multiple times, as well as all the function prototypes the module makes available for other modules to use. By making a sub-component of the app into a module, the need for messy global variables is removed and a clear interface between them is defined. The files themselves are located in a `modules` directory inside the project's main `src` directory, keeping them in a separate location to other components of the app. Thus the structure of the project with a `data` module added (and explained below) is now this: ```text modular-project/ resources/ src/ modules/ data.h data.c modular-project.c package.json wscript ``` The example module's pair of files is shown below. It manages a dynamically allocated array of integers, and includes an interface to setting and getting values from the array. The array itself is private to the module thanks for the [`static`](https://en.wikipedia.org/wiki/Static_(keyword)) keyword. This technique allows other components of the app to call the 'getters' and 'setters' with the correct parameters as per the module's interface, without worrying about the implementation details. `src/modules/data.h` ```c #pragma once // Prevent errors by being included multiple times #include <pebble.h> // Pebble SDK symbols void data_init(int array_length); void data_deinit(); void data_set_array_value(int index, int new_value); int data_get_array_value(int index); ``` `src/modules/data.c` ```c #include "data.h" static int* s_array; void data_init(int array_length) { if(!s_array) { s_array = (int*)malloc(array_length * sizeof(int)); } } void data_deinit() { if(s_array) { free(s_array); s_array = NULL; } } void data_set_array_value(int index, int new_value) { s_array[index] = new_value; } int data_get_array_value(int index) { return s_array[index]; } ``` ## Keep Multiple Windows Separate The ``Window Stack`` lifecycle makes the task of keeping each ``Window`` separate quite easy. Each one has a `.load` and `.unload` handler which should be used to create and destroy its UI components and other data. The first step to modularizing the new app is to keep each ``Window`` in its own module. The first ``Window``'s code can be moved out of `src/modular-project.c` into a new module in `src/windows/` called 'main_window': `src/windows/main_window.h` ```c #pragma once #include <pebble.h> void main_window_push(); ``` `src/windows/main_window.c` ```c #include "main_window.h" static Window *s_window; static void window_load(Window *window) { Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_bounds(window_layer); } static void window_unload(Window *window) { window_destroy(s_window); } void main_window_push() { if(!s_window) { s_window = window_create(); window_set_window_handlers(s_window, (WindowHandlers) { .load = window_load, .unload = window_unload, }); } window_stack_push(s_window, true); } ``` ## Keeping Main Clear After moving the ``Window`` code out of the main `.c` file, it can be safely renamed `main.c` to reflect its contents. This allows the main `.c` file to show a high-level overview of the app as a whole. Simply `#include` the required modules and windows to initialize and deinitialize the rest of the app as necessary: `src/main.c` ```c #include <pebble.h> #include "modules/data.h" #include "windows/main_window.h" static void init() { const int array_size = 16; data_init(array_size); main_window_push(); } static void deinit() { data_deinit(); } int main() { init(); app_event_loop(); deinit(); } ``` Thus the structure of the project is now: ```text modular-project/ resources/ src/ modules/ data.h data.c windows/ main_window.h main_window.c main.c package.json wscript ``` With this structured approach to organizing the different functional components of an app, the maintainability of the project will not suffer as it grows in size and complexity. A useful module can even be shared and reused as a library, which is preferrable to pasting chunks of code that may have other messy dependencies elsewhere in the project.
{ "source": "google/pebble", "title": "devsite/source/_guides/best-practices/modular-app-architecture.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/best-practices/modular-app-architecture.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 7682 }
--- # Copyright 2025 Google LLC # # 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. title: Advanced Communication description: | Details of communication tips and best practices for more advanced scenarios. guide_group: communication order: 0 related_docs: - AppMessage related_examples: - title: JS Ready Example url: https://github.com/pebble-examples/js-ready-example - title: List Items Example url: https://github.com/pebble-examples/list-items-example - title: Accel Data Stream url: https://github.com/pebble-examples/accel-data-stream - title: PNG Download Example url: https://github.com/pebble-examples/png-download-example - title: Pebble Faces url: https://github.com/pebble-examples/pebble-faces platform_choice: true --- Many types of connected Pebble watchapps and watchfaces perform common tasks such as the ones discussed here. Following these best practices can increase the quality of the implementation of each one, and avoid common bugs. ## Waiting for PebbleKit JS Any app that wishes to send data from the watch to the phone via {% guide_link communication/using-pebblekit-js "PebbleKit JS" %} **must** wait until the JavaScript `ready` event has occured, indicating that the phone has loaded the JavaScript component of the launching app. If this JavaScript code implements the `appmessage` event listsner, it is ready to receive data. > An watchapp that only *receives* data from PebbleKit JS does not have to wait > for the `ready` event. In addition, Android companion apps do not have to wait > for such an event thanks to the `Intent` system. iOS companion apps must wait > for `-watchDidConnect:`. <div class="platform-specific" data-sdk-platform="local"> {% markdown %} A simple method is to define a key in `package.json` that will be interpreted by the watchapp to mean that the JS environment is ready for exchange data: ```js "messageKeys": [ "JSReady" ] ``` {% endmarkdown %} </div> <div class="platform-specific" data-sdk-platform="cloudpebble"> {% markdown %} A simple method is to define a key in Settings that will be interpreted by the watchapp to mean that the JS environment is ready for exchange data: * JSReady {% endmarkdown %} </div> The watchapp should implement a variable that describes if the `ready` event has occured. An example is shown below: ```c static bool s_js_ready; ``` This can be exported in a header file for other parts of the app to check. Any parts of the app that are waiting should call this as part of a [retry](#timeouts-and-retries) mechanism. ```c bool comm_is_js_ready() { return s_js_ready; } ``` The state of this variable will be `false` until set to `true` when the `ready` event causes the key to be transmitted: ```js Pebble.addEventListener('ready', function() { console.log('PebbleKit JS ready.'); // Update s_js_ready on watch Pebble.sendAppMessage({'JSReady': 1}); }); ``` This key should be interpreted in the app's ``AppMessageInboxReceived`` implementation: ```c static void inbox_received_handler(DictionaryIterator *iter, void *context) { Tuple *ready_tuple = dict_find(iter, MESSAGE_KEY_JSReady); if(ready_tuple) { // PebbleKit JS is ready! Safe to send messages s_js_ready = true; } } ``` ## Timeouts and Retries Due to the wireless and stateful nature of the Bluetooth connection, some messages sent between the watch and phone may fail. A tried-and-tested method for dealing with these failures is to implement a 'timeout and retry' mechanism. Under such a scheme: * A message is sent and a timer started. * If the message is sent successfully (and optionally a reply received), the timer is cancelled. * If the timer elapses before the message can be sent successfully, the message is reattempted. Depending on the nature of the failure, a suitable retry interval (such as a few seconds) is used to avoid saturating the connection. The interval chosen before a timeout occurs and the message is resent may vary depending on the circumstances. The first failure should be reattempted fairly quickly (one second), with the interval increasing as successive failures occurs. If the connection is not available the timer interval should be [even longer](https://en.wikipedia.org/wiki/Exponential_backoff), or wait until the connection is restored. ### Using a Timeout Timer The example below shows the sending of a message and scheduling a timeout timer. The first step is to declare a handle for the timeout timer: ```c static AppTimer *s_timeout_timer; ``` When the message is sent, the timer should be scheduled: ```c static void send_with_timeout(int key, int value) { // Construct and send the message DitionaryIterator *iter; if(app_message_outbox_begin(&iter) == APP_MSG_OK) { dict_write_int(iter, key, &value, sizeof(int), true); app_message_outbox_send(); } // Schedule the timeout timer const int interval_ms = 1000; s_timout_timer = app_timer_register(interval_ms, timout_timer_handler, NULL); } ``` If the ``AppMessageOutboxSent`` is called, the message was a success, and the timer should be cancelled: ```c static void outbox_sent_handler(DictionaryIterator *iter, void *context) { // Successful message, the timeout is not needed anymore for this message app_timer_cancel(s_timout_timer); } ``` ### Retry a Failed Message However, if the timeout timer elapses before the message's success can be determined or an expected reply is not received, the callback to `timout_timer_handler()` should be used to inform the user of the failure, and schedule another attempt and retry the message: ```c static void timout_timer_handler(void *context) { // The timer elapsed because no success was reported text_layer_set_text(s_status_layer, "Failed. Retrying..."); // Retry the message send_with_timeout(some_key, some_value); } ``` Alternatively, if the ``AppMessageOutboxFailed`` is called the message failed to send, sometimes immediately. The timeout timer should be cancelled and the message reattempted after an additional delay (the 'retry interval') to avoid saturating the channel: ```c static void outbox_failed_handler(DictionaryIterator *iter, AppMessageResult reason, void *context) { // Message failed before timer elapsed, reschedule for later if(s_timout_timer) { app_timer_cancel(s_timout_timer); } // Inform the user of the failure text_layer_set_text(s_status_layer, "Failed. Retrying..."); // Use the timeout handler to perform the same action - resend the message const int retry_interval_ms = 500; app_timer_register(retry_interval_ms, timout_timer_handler, NULL); } ``` > Note: All eventualities where a message fails must invoke a resend of the > message, or the purpose of an automated 'timeout and retry' mechanism is > defeated. However, the number of attempts made and the interval between them > is for the developer to decide. ## Sending Lists Until SDK 3.8, the size of ``AppMessage`` buffers did not facilitate sending large amounts of data in one message. With the current buffer sizes of up to 8k for each an outbox the need for efficient transmission of multiple sequential items of data is lessened, but the technique is still important. For instance, to transmit sensor data as fast as possible requires careful scheduling of successive messages. Because there is no guarantee of how long a message will take to transmit, simply using timers to schedule multiple messages after one another is not reliable. A much better method is to make good use of the callbacks provided by the ``AppMessage`` API. ### Sending a List to the Phone For instance, the ``AppMessageOutboxSent`` callback can be used to safely schedule the next message to the phone, since the previous one has been acknowledged by the other side at that time. Here is an example array of items: ```c static int s_data[] = { 2, 4, 8, 16, 32, 64 }; #define NUM_ITEMS sizeof(s_data); ``` A variable can be used to keep track of the current list item index that should be transmitted next: ```c static int s_index = 0; ``` When a message has been sent, this index is used to construct the next message: <div class="platform-specific" data-sdk-platform="local"> {% markdown %} > Note: A useful key scheme is to use the item's array index as the key. For > PebbleKit JS that number of keys will have to be declared in `package.json`, > like so: `someArray[6]` {% endmarkdown %} </div> <div class="platform-specific" data-sdk-platform="cloudpebble"> {% markdown %} > Note: A useful key scheme is to use the item's array index as the key. For > PebbleKit JS that number of keys will have to be declared in the project's > 'Settings' page, like so: `someArray[6]` {% endmarkdown %} </div> ```c static void outbox_sent_handler(DictionaryIterator *iter, void *context) { // Increment the index s_index++; if(s_index < NUM_ITEMS) { // Send the next item DictionaryIterator *iter; if(app_message_outbox_begin(&iter) == APP_MSG_OK) { dict_write_int(iter, MESSAGE_KEY_someArray + s_index, &s_data[s_index], sizeof(int), true); app_message_outbox_send(); } } else { // We have reached the end of the sequence APP_LOG(APP_LOG_LEVEL_INFO, "All transmission complete!"); } } ``` This results in a callback loop that repeats until the last data item has been transmitted, and the index becomes equal to the total number of items. This technique can be combined with a timeout and retry mechanism to reattempt a particular item if transmission fails. This is a good way to avoid gaps in the received data items. On the phone side, the data items are received in the same order. An analogous `index` variable is used to keep track of which item has been received. This process will look similar to the example shown below: ```js var NUM_ITEMS = 6; var keys = require('message_keys'); var data = []; var index = 0; Pebble.addEventListener('appmessage', function(e) { // Store this data item data[index] = e.payload[keys.someArray + index]; // Increment index for next message index++; if(index == NUM_ITEMS) { console.log('Received all data items!'); } }); ``` ### Sending a List to Pebble Conversely, the `success` callback of `Pebble.sendAppMessage()` in PebbleKit JS is the equivalent safe time to send the next message to the watch. An example implementation that achieves this is shown below. After the message is sent with `Pebble.sendAppMessage()`, the `success` callback calls the `sendNextItem()` function repeatedly until the index is larger than that of the last list item to be sent, and transmission will be complete. Again, an index variable is maintained to keep track of which item is being transmitted: ```js var keys = require('message_keys'); function sendNextItem(items, index) { // Build message var key = keys.someArray + index; var dict = {}; dict[key] = items[index]; // Send the message Pebble.sendAppMessage(dict, function() { // Use success callback to increment index index++; if(index < items.length) { // Send next item sendNextItem(items, index); } else { console.log('Last item sent!'); } }, function() { console.log('Item transmission failed at index: ' + index); }); } function sendList(items) { var index = 0; sendNextItem(items, index); } function onDownloadComplete(responseText) { // Some web response containing a JSON object array var json = JSON.parse(responseText); // Begin transmission loop sendList(json.items); } ``` On the watchapp side, the items are received in the same order in the ``AppMessageInboxReceived`` handler: ```c #define NUM_ITEMS 6 static int s_index; static int s_data[NUM_ITEMS]; ``` ```c static void inbox_received_handler(DictionaryIterator *iter, void *context) { Tuple *data_t = dict_find(iter, MESSAGE_KEY_someArray + s_index); if(data_t) { // Store this item s_data[index] = (int)data_t->value->int32; // Increment index for next item s_index++; } if(s_index == NUM_ITEMS) { // We have reached the end of the sequence APP_LOG(APP_LOG_LEVEL_INFO, "All transmission complete!"); } } ``` This sequence of events is demonstrated for PebbleKit JS, but the same technique can be applied exactly to either and Android or iOS companion app wishing to transmit many data items to Pebble. Get the complete source code for this example from the [`list-items-example`](https://github.com/pebble-examples/list-items-example) repository on GitHub. ## Sending Image Data A common task developers want to accomplish is display a dynamically loaded image resource (for example, showing an MMS photo or a news item thumbnail pulled from a webservice). Because some images could be larger than the largest buffer size available to the app, the techniques shown above for sending lists also prove useful here, as the image is essentially a list of color byte values. ### Image Data Format There are two methods available for displaying image data downloaded from the web: 1. Download a `png` image, transmit the compressed data, and decompress using ``gbitmap_create_from_png_data()``. This involves sending less data, but can be prone to failure depending on the exact format of the image. The image must be in a compatible palette (1, 2, 4, or 8-bit) and small enough such that there is enough memory for a compessed copy, an uncompressed copy, and ~2k overhead when it is being processed. 2. Download a `png` image, decompress in the cloud or in PebbleKit JS into an array of image pixel bytes, transmit the pixel data into a blank ``GBitmap``'s `data` member. Each byte must be in the compatible Pebble color format (2 bits per ARGB). This process can be simplified by pre-formatting the image to be dowloaded, as resizing or palette-reduction is difficult to do locally. ### Sending Compressed PNG Data As the fastest and least complex of the two methods described above, an example of how to display a compressed PNG image will be discussed here. The image that will be displayed is [the HTML 5 logo](https://www.w3.org/html/logo/): ![](http://developer.getpebble.com.s3.amazonaws.com/assets/other/html5-logo-small.png) > Note: The above image has been resized and palettized for compatibility. To download this image in PebbleKit JS, use an `XmlHttpRequest` object. It is important to specify the `responseType` as 'arraybuffer' to obtain the image data in the correct format: ```js function downloadImage() { var url = 'http://developer.getpebble.com.s3.amazonaws.com/assets/other/html5-logo-small.png'; var request = new XMLHttpRequest(); request.onload = function() { processImage(this.response); }; request.responseType = "arraybuffer"; request.open("GET", url); request.send(); } ``` When the response has been received, `processImage()` will be called. The received data must be converted into an array of unsigned bytes, which is achieved through the use of a `Uint8Array`. This process is shown below (see the [`png-download-example`](https://github.com/pebble-examples/png-download-example) repository for the full example): ```js function processImage(responseData) { // Convert to a array var byteArray = new Uint8Array(responseData); var array = []; for(var i = 0; i < byteArray.byteLength; i++) { array.push(byteArray[i]); } // Send chunks to Pebble transmitImage(array); } ``` Now that the image data has been converted, the transmission to Pebble can begin. At a high level, the JS side transmits the image data in chunks, using an incremental array index to coordinate saving of data on the C side in a mirror array. In downloading the image data, the following keys are used for the specified purposes: | Key | Purpose | |-----|---------| | `Index` | The array index that the current chunk should be stored at. This gets larger as each chunk is transmitted. | | `DataLength` | This length of the entire data array to be downloaded. As the image is compressed, this is _not_ the product of the width and height of the image. | | `DataChunk` | The chunk's image data. | | `ChunkSize` | The size of this chunk. | | `Complete` | Used to signify that the image transfer is complete. | The first message in the sequence should tell the C side how much memory to allocate to store the compressed image data: ```js function transmitImage(array) { var index = 0; var arrayLength = array.length; // Transmit the length for array allocation Pebble.sendAppMessage({'DataLength': arrayLength}, function(e) { // Success, begin sending chunks sendChunk(array, index, arrayLength); }, function(e) { console.log('Failed to initiate image transfer!'); }) } ``` If this message is successful, the transmission of actual image data commences with the first call to `sendChunk()`. This function calculates the size of the next chunk (the smallest of either the size of the `AppMessage` inbox buffer, or the remainder of the data) and assembles the dictionary containing the index in the array it is sliced from, the length of the chunk, and the actual data itself: ```js function sendChunk(array, index, arrayLength) { // Determine the next chunk size var chunkSize = BUFFER_SIZE; if(arrayLength - index < BUFFER_SIZE) { // Resize to fit just the remaining data items chunkSize = arrayLength - index; } // Prepare the dictionary var dict = { 'DataChunk': array.slice(index, index + chunkSize), 'ChunkSize': chunkSize, 'Index': index }; // Send the chunk Pebble.sendAppMessage(dict, function() { // Success index += chunkSize; if(index < arrayLength) { // Send the next chunk sendChunk(array, index, arrayLength); } else { // Complete! Pebble.sendAppMessage({'Complete': 0}); } }, function(e) { console.log('Failed to send chunk with index ' + index); }); } ``` After each chunk is sent, the index is incremented with the size of the chunk that was just sent, and compared to the total length of the array. If the index exceeds the size of the array, the loop has sent all the data (this could be just a single chunk if the array is smaller than the maximum message size). The `AppKeyComplete` key is sent to inform the C side that the image is complete and ready for display. ### Receiving Compressed PNG Data In the previous section, the process for using PebbleKit JS to download and transmit an image to the C side was discussed. The process for storing and displaying this data is discussed here. Only when both parts work in harmony can an image be successfully shown from the web. The majority of the process takes place within the watchapp's ``AppMessageInboxReceived`` handler, with the presence of each key being detected and the appropriate actions taken to reconstruct the image. The first item expected is the total size of the data to be transferred. This is recorded (for later use with ``gbitmap_create_from_png_data()``) and the buffer used to store the chunks is allocated to this exact size: ```c static uint8_t *s_img_data; static int s_img_size; ``` ```c // Get the received image chunk Tuple *img_size_t = dict_find(iter, MESSAGE_KEY_DataLength); if(img_size_t) { s_img_size = img_size_t->value->int32; // Allocate buffer for image data img_data = (uint8_t*)malloc(s_img_size * sizeof(uint8_t)); } ``` When the message containing the data size is acknowledged, the JS side begins sending chunks with `sendChunk()`. When one of these subsequent messages is received, the three keys (`DataChunk`, `ChunkSize`, and `Index`) are used to store that chunk of data at the correct offset in the array: ```c // An image chunk Tuple *chunk_t = dict_find(iter, MESSAGE_KEY_DataChunk); if(chunk_t) { uint8_t *chunk_data = chunk_t->value->data; Tuple *chunk_size_t = dict_find(iter, MESSAGE_KEY_ChunkSize); int chunk_size = chunk_size_t->value->int32; Tuple *index_t = dict_find(iter, MESSAGE_KEY_Index); int index = index_t->value->int32; // Save the chunk memcpy(&s_img_data[index], chunk_data, chunk_size); } ``` Finally, once the array index exceeds the size of the data array on the JS side, the `AppKeyComplete` key is transmitted, triggering the data to be transformed into a ``GBitmap``: ```c static BitmapLayer *s_bitmap_layer; static GBitmap *s_bitmap; ``` ```c // Complete? Tuple *complete_t = dict_find(iter, MESSAGE_KEY_Complete); if(complete_t) { // Create new GBitmap from downloaded PNG data s_bitmap = gbitmap_create_from_png_data(s_img_data, s_img_size); // Show the image if(s_bitmap) { bitmap_layer_set_bitmap(s_bitmap_layer, s_bitmap); } else { APP_LOG(APP_LOG_LEVEL_ERROR, "Error creating GBitmap from PNG data!"); } } ``` The final result is a compressed PNG image downloaded from the web displayed in a Pebble watchapp. Get the complete source code for this example from the [`png-download-example`](https://github.com/pebble-examples/png-download-example) repository on GitHub.
{ "source": "google/pebble", "title": "devsite/source/_guides/communication/advanced-communication.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/communication/advanced-communication.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 21622 }
--- # Copyright 2025 Google LLC # # 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. title: Datalogging description: | Information on how to collect data batches using the Datalogging API. guide_group: communication order: 1 related_examples: - title: Tricorder - url: https://github.com/pebble-examples/tricorder --- In addition to the more realtime ``AppMessage`` API, the Pebble SDK also includes the ``Datalogging`` API. This is useful for applications where data can be sent in batches at time intervals that make the most sense (for example, to save battery power by allowing the watch to spend more time sleeping). Datalogging also allows upto 640 kB of data to be buffered on the watch until a connection is available, instead of requiring a connection be present at all times. If data is logged while the watch is disconnected, it will be transferred to the Pebble mobile app in batches for processing at the next opportunity. The data is then passed on to any {% guide_link communication/using-pebblekit-android %} or {% guide_link communication/using-pebblekit-ios %} companion app that wishes to process it. ## Collecting Data Datalogging can capture any values that are compatible with one of the ``DataLoggingItemType`` `enum` (byte array, unsigned integer, and integer) values, with common sources including accelerometer data or compass data. ### Creating a Session Data is logged to a 'session' with a unique identifier or tag, which allows a single app to have multiple data logs for different types of data. First, define the identifier(s) that should be used where appropriate: ```c // The log's ID. Only one required in this example #define TIMESTAMP_LOG 1 ``` Next, a session must first be created before any data can be logged to it. This should be done during app initialization, or just before the first time an app needs to log some data: ```c // The session reference variable static DataLoggingSessionRef s_session_ref; ``` ```c static void init() { // Begin the session s_session_ref = data_logging_create(TIMESTAMP_LOG, DATA_LOGGING_INT, sizeof(int), true); /* ... */ } ``` > Note: The final parameter of ``data_logging_create()`` allows a previous log > session to be continued, instead of starting from screatch on each app launch. ### Logging Data Once the log has been created or resumed, data collection can proceed. Each call to ``data_logging_log()`` will add a new entry to the log indicated by the ``DataLoggingSessionRef`` variable provided. The success of each logging operation can be checked using the ``DataLoggingResult`` returned: ```c const int value = 16; const uint32_t num_values = 1; // Log a single value DataLoggingResult result = data_logging_log(s_session_ref, &value, num_values); // Was the value successfully stored? If it failed, print the reason if(result != DATA_LOGGING_SUCCESS) { APP_LOG(APP_LOG_LEVEL_ERROR, "Error logging data: %d", (int)result); } ``` ### Finishing a Session Once all data has been logged or the app is exiting, the session must be finished to signify that the data is to be either transferred to the connected phone (if available), or stored for later transmission. ```c // Finish the session and sync data if appropriate data_logging_finish(s_session_ref); ``` > Note: Once a session has been finished, data cannot be logged to its > ``DataLoggingSessionRef`` until it is resumed or began anew. ## Receiving Data > Note: Datalogging data cannot be received via PebbleKit JS. Data collected with the ``Datalogging`` API can be received and processed in a mobile companion app using PebbleKit Android or PebbleKit iOS. This enables it to be used in a wide range of general applications, such as detailed analysis of accelerometer data for health research, or transmission to a third-party web service. ### With PebbleKit Android PebbleKit Android allows collection of data by registering a `PebbleDataLogReceiver` within your `Activity` or `Service`. When creating a receiver, be careful to provide the correct UUID to match that of the watchapp that is doing that data collection. For example: ```java // The UUID of the watchapp private UUID APP_UUID = UUID.fromString("64fcb54f-76f0-418a-bd7d-1fc1c07c9fc1"); ``` Use the following overridden methods to collect data and determine when the session has been finished by the watchapp. In the example below, each new integer received represents the uptime of the watchapp, and is displayed in an Android `TextView`: ```java // Create a receiver to collect logged data PebbleKit.PebbleDataLogReceiver dataLogReceiver = new PebbleKit.PebbleDataLogReceiver(APP_UUID) { @Override public void receiveData(Context context, UUID logUuid, Long timestamp, Long tag, int data) { // super() (removed from IDE-generated stub to avoid exception) Log.i(TAG, "New data for session " + tag + "!"); // Cumulatively add the new data item to a TextView's current text String current = dataView.getText().toString(); current += timestamp.toString() + ": " + data + "s since watchapp launch.\n"; dataView.setText(current); } @Override public void onFinishSession(Context context, UUID logUuid, Long timestamp, Long tag) { Log.i(TAG, "Session " + tag + " finished!"); } }; // Register the receiver PebbleKit.registerDataLogReceiver(getApplicationContext(), dataLogReceiver); ``` <div class="alert alert--fg-white alert--bg-dark-red"> {% markdown %} **Important** If your Java IDE automatically adds a line of code to call super() when you create the method, the code will result in an UnsupportedOperationException. Ensure you remove this line to avoid the exception. {% endmarkdown %} </div> Once the `Activity` or `Service` is closing, you should attempt to unregister the receiver. However, this is not always required (and will cause an exception to be thrown if invoked when not required), so use a `try, catch` statement: ```java @Override protected void onPause() { super.onPause(); try { unregisterReceiver(dataLogReceiver); } catch(Exception e) { Log.w(TAG, "Receiver did not need to be unregistered"); } } ``` ### With PebbleKit iOS The process of collecing data via a PebbleKit iOS companion mobile app is similar to that of using PebbleKit Android. Once your app is a delegate of ``PBDataLoggingServiceDelegate`` (see {% guide_link communication/using-pebblekit-ios %} for details), simply register the class as a datalogging delegate: ```objective-c // Get datalogging data by becoming the delegate [[PBPebbleCentral defaultCentral] dataLoggingServiceForAppUUID:myAppUUID].delegate = self; ``` Being a datalogging delegate allows the class to receive two additional [callbacks](/docs/pebblekit-ios/Protocols/PBDataLoggingServiceDelegate/) for when new data is available, and when the session has been finished by the watch. Implement these callbacks to read the new data: ```objective-c - (BOOL)dataLoggingService:(PBDataLoggingService *)service hasSInt32s:(const SInt32 [])data numberOfItems:(UInt16)numberOfItems forDataLog:(PBDataLoggingSessionMetadata *)log { NSLog(@"New data received!"); // Append newest data to displayed string NSString *current = self.dataView.text; NSString *newString = [NSString stringWithFormat:@"New item: %d", data[0]]; current = [current stringByAppendingString:newString]; self.dataView.text = current; return YES; } - (void)dataLoggingService:(PBDataLoggingService *)service logDidFinish:(PBDataLoggingSessionMetadata *)log { NSLog(@"Finished data log: %@", log); } ``` ### Special Considerations for iOS Apps * The logic to deal with logs with the same type of data (i.e., the same tag/type) but from different sessions (different timestamps) must be created by the developer using the delegate callbacks. * To check whether the data belongs to the same log or not, use `-isEqual:` on `PBDataLoggingSessionMetadata`. For convenience, `PBDataLoggingSessionMetadata` can be serialized using `NSCoding`. * Using multiple logs in parallel (for example to transfer different kinds of information) will require extra logic to re-associate the data from these different logs, which must also be implemented by the developer.
{ "source": "google/pebble", "title": "devsite/source/_guides/communication/datalogging.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/communication/datalogging.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 8966 }
--- # Copyright 2025 Google LLC # # 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. title: Communication description: | How to talk to the phone via PebbleKit with JavaScript and on Android or iOS. guide_group: communication menu: false permalink: /guides/communication/ generate_toc: false hide_comments: true platform_choice: true --- All Pebble watchapps and watchfaces have the ability to communicate with the outside world through its connection to the user's phone. The PebbleKit collection of libraries (see below) is available to facilitate this communication between watchapps and phone apps. Examples of additional functionality made possible through PebbleKit include, but are not limited to apps that can: * Display weather, news, stocks, etc. * Communicate with other web services. * Read and control platform APIs and features of the connected phone. ## Contents {% include guides/contents-group.md group=page.group_data %} ## Communication Model Pebble communicates with the connected phone via the Bluetooth connection, which is the same connection that delivers notifications and other alerts in normal use. Developers can leverage this connection to send and receive arbitrary data using the ``AppMessage`` API. Depending on the requirements of the app, there are three possible ways to receive data sent from Pebble on the connected phone: * {% guide_link communication/using-pebblekit-js %} - A JavaScript environment running within the official Pebble mobile app with web, geolocation, and extended storage access. * {% guide_link communication/using-pebblekit-android %} - A library available to use in Android companion apps that allows them to interact with standard Android platform APIs. * {% guide_link communication/using-pebblekit-ios %} - As above, but for iOS companion apps. <div class="alert alert--fg-white alert--bg-dark-red"> {% markdown %} **Important** PebbleKit JS cannot be used in conjunction with PebbleKit Android or PebbleKit iOS. {% endmarkdown %} </div> All messages sent from a Pebble watchapp or watchface will be delivered to the appropriate phone app depending on the layout of the developer's project: <div class="platform-specific" data-sdk-platform="local"> {% markdown %} * If at least an `index.js` file is present in `src/pkjs/`, the message will be handled by PebbleKit JS. {% endmarkdown %} </div> <div class="platform-specific" data-sdk-platform="cloudpebble"> {% markdown %} * If the project contains at least one JavaScript file, the message will be handled by PebbleKit JS. {% endmarkdown %} </div> * If there is no valid JS file present (at least an `index.js`) in the project, the message will be delivered to the official Pebble mobile app. If there is a companion app installed that has registered a listener with the same UUID as the watchapp, the message will be forwarded to that app via PebbleKit Android/iOS.
{ "source": "google/pebble", "title": "devsite/source/_guides/communication/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/communication/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 3417 }
--- # Copyright 2025 Google LLC # # 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. title: Sending and Receiving Data description: | How to send and receive data between your watchapp and phone. guide_group: communication order: 5 --- Before using ``AppMessage``, a Pebble C app must set up the buffers used for the inbox and outbox. These are used to store received messages that have not yet been processed, and sent messages that have not yet been transmitted. In addition, callbacks may be registered to allow an app to respond to any success or failure events that occur when dealing with messages. Doing all of this is discussed in this guide. ## Message Structure Every message sent or received using the ``AppMessage`` API is stored in a ``DictionaryIterator`` structure, which is essentially a list of ``Tuple`` objects. Each ``Tuple`` contains a key used to 'label' the value associated with that key. When a message is sent, a ``DictionaryIterator`` is filled with a ``Tuple`` for each item of outgoing data. Conversely, when a message is received the ``DictionaryIterator`` provided by the callback is examined for the presence of each key. If a key is present, the value associated with it can be read. ## Data Types The [`Tuple.value`](``Tuple``) union allows multiple data types to be stored in and read from each received message. These are detailed below: | Name | Type | Size in Bytes | Signed? | |------|------|---------------|---------| | uint8 | `uint8_t` | 1 | No | | uint16 | `uint16_t` | 2 | No | | uint32 | `uint32_t` | 4 | No | | int8 | `int8_t` | 1 | Yes | | int16 | `int16_t` | 2 | Yes | | int32 | `int32_t` | 4 | Yes | | cstring | `char[]` | Variable length array | N/A | | data | `uint8_t[]` | Variable length array | N/A | ## Buffer Sizes The size of each of the outbox and inbox buffers must be set chosen such that the largest message that the app will ever send or receive will fit. Incoming messages that exceed the size of the inbox buffer, and outgoing messages that exceed that size of the outbox buffer will be dropped. These sizes are specified when the ``AppMessage`` system is 'opened', allowing communication to occur: ```c // Largest expected inbox and outbox message sizes const uint32_t inbox_size = 64; const uint32_t outbox_size = 256; // Open AppMessage app_message_open(inbox_size, outbox_size); ``` Each of these buffers is allocated at this moment, and comes out of the app's memory budget, so the sizes of the inbox and outbox should be conservative. Calculate the size of the buffer you require by summing the sizes of all the keys and values in the larges message the app will handle. For example, a message containing three integer keys and values will work with a 32 byte buffer size. ## Choosing Keys For each message sent and received, the contents are accessible using keys-value pairs in a ``Tuple``. This allows each piece of data in the message to be uniquely identifiable using its key, and also allows many different data types to be stored inside a single message. Each possible piece of data that may be transmitted should be assigned a unique key value, used to read the associated value when it is found in a received message. An example for a weather app is shown below:: * Temperature * WindSpeed * WindDirection * RequestData * LocationName These values will be made available in any file that includes `pebble.h` prefixed with `MESSAGE_KEY_`, such as `MESSAGE_KEY_Temperature` and `MESSAGE_KEY_WindSpeed`. Examples of how these key values would be used in the phone-side app are shown in {% guide_link communication/using-pebblekit-js %}, {% guide_link communication/using-pebblekit-ios %}, and {% guide_link communication/using-pebblekit-android %}. ## Using Callbacks Like many other aspects of the Pebble C API, the ``AppMessage`` system makes use of developer-defined callbacks to allow an app to gracefully handle all events that may occur, such as successfully sent or received messages as well as any errors that may occur. These callback types are discussed below. Each is used by first creating a function that matches the signature of the callback type, and then registering it with the ``AppMessage`` system to be called when that event type occurs. Good use of callbacks to drive the app's UI will result in an improved user experience, especially when errors occur that the user can be guided in fixing. ### Inbox Received The ``AppMessageInboxReceived`` callback is called when a new message has been received from the connected phone. This is the moment when the contents can be read and used to drive what the app does next, using the provided ``DictionaryIterator`` to read the message. An example is shown below under [*Reading an Incoming Message*](#reading-an-incoming-message): ```c static void inbox_received_callback(DictionaryIterator *iter, void *context) { // A new message has been successfully received } ``` Register this callback so that it is called at the appropriate time: ```c // Register to be notified about inbox received events app_message_register_inbox_received(inbox_received_callback); ``` ### Inbox Dropped The ``AppMessageInboxDropped`` callback is called when a message was received, but it was dropped. A common cause of this is that the message was too big for the inbox. The reason for failure can be determined using the ``AppMessageResult`` provided by the callback: ```c static void inbox_dropped_callback(AppMessageResult reason, void *context) { // A message was received, but had to be dropped APP_LOG(APP_LOG_LEVEL_ERROR, "Message dropped. Reason: %d", (int)reason); } ``` Register this callback so that it is called at the appropriate time: ```c // Register to be notified about inbox dropped events app_message_register_inbox_dropped(inbox_dropped_callback); ``` ### Outbox Sent The ``AppMessageOutboxSent`` callback is called when a message sent from Pebble has been successfully delivered to the connected phone. The provided ``DictionaryIterator`` can be optionally used to inspect the contents of the message just sent. > When sending multiple messages in a short space of time, it is **strongly** > recommended to make use of this callback to wait until the previous message > has been sent before sending the next. ```c static void outbox_sent_callback(DictionaryIterator *iter, void *context) { // The message just sent has been successfully delivered } ``` Register this callback so that it is called at the appropriate time: ```c // Register to be notified about outbox sent events app_message_register_outbox_sent(outbox_sent_callback); ``` ### Outbox Failed The ``AppMessageOutboxFailed`` callback is called when a message just sent failed to be successfully delivered to the connected phone. The reason can be determined by reading the value of the provided ``AppMessageResult``, and the contents of the failed message inspected with the provided ``DictionaryIterator``. Use of this callback is strongly encouraged, since it allows an app to detect a failed message and either retry its transmission, or inform the user of the failure so that they can attempt their action again. ```c static void outbox_failed_callback(DictionaryIterator *iter, AppMessageResult reason, void *context) { // The message just sent failed to be delivered APP_LOG(APP_LOG_LEVEL_ERROR, "Message send failed. Reason: %d", (int)reason); } ``` Register this callback so that it is called at the appropriate time: ```c // Register to be notified about outbox failed events app_message_register_outbox_failed(outbox_failed_callback); ``` ## Constructing an Outgoing Message A message is constructed and sent from the C app via ``AppMessage`` using a ``DictionaryIterator`` object and the ``Dictionary`` APIs. Ensure that ``app_message_open()`` has been called before sending or receiving any messages. The first step is to begin an outgoing message by preparing a ``DictionaryIterator`` pointer, used to keep track of the state of the dictionary being constructed: ```c // Declare the dictionary's iterator DictionaryIterator *out_iter; // Prepare the outbox buffer for this message AppMessageResult result = app_message_outbox_begin(&out_iter); ``` The ``AppMessageResult`` should be checked to make sure the outbox was successfully prepared: ```c if(result == APP_MSG_OK) { // Construct the message } else { // The outbox cannot be used right now APP_LOG(APP_LOG_LEVEL_ERROR, "Error preparing the outbox: %d", (int)result); } ``` If the result is ``APP_MSG_OK``, the message construction can continue. Data is now written to the dictionary according to data type using the ``Dictionary`` APIs. An example from the hypothetical weather app is shown below: ```c if(result == APP_MSG_OK) { // A dummy value int value = 0; // Add an item to ask for weather data dict_write_int(out_iter, MESSAGE_KEY_RequestData, &value, sizeof(int), true); } ``` After all desired data has been written to the dictionary, the message may be sent: ```c // Send this message result = app_message_outbox_send(); // Check the result if(result != APP_MSG_OK) { APP_LOG(APP_LOG_LEVEL_ERROR, "Error sending the outbox: %d", (int)result); } ``` <div class="alert alert--fg-white alert--bg-dark-red"> {% markdown %} **Important** Any app that wishes to send data from the watch to the phone via PebbleKit JS must wait until the `ready` event has occured, indicating that the phone has loaded the JavaScript for the app and it is ready to receive data. See [*Advanced Communication*](/guides/communication/advanced-communication#waiting-for-pebblekit-js) for more information. {% endmarkdown %} </div> Once the message send operation has been completed, either the ``AppMessageOutboxSent`` or ``AppMessageOutboxFailed`` callbacks will be called (if they have been registered), depending on either a success or failure outcome. ### Example Outgoing Message Construction A complete example of assembling an outgoing message is shown below: ```c // Declare the dictionary's iterator DictionaryIterator *out_iter; // Prepare the outbox buffer for this message AppMessageResult result = app_message_outbox_begin(&out_iter); if(result == APP_MSG_OK) { // Add an item to ask for weather data int value = 0; dict_write_int(out_iter, MESSAGE_KEY_RequestData, &value, sizeof(int), true); // Send this message result = app_message_outbox_send(); if(result != APP_MSG_OK) { APP_LOG(APP_LOG_LEVEL_ERROR, "Error sending the outbox: %d", (int)result); } } else { // The outbox cannot be used right now APP_LOG(APP_LOG_LEVEL_ERROR, "Error preparing the outbox: %d", (int)result); } ``` ## Reading an Incoming Message When a message is received from the connected phone the ``AppMessageInboxReceived`` callback is called, and the message's contents can be read using the provided ``DictionaryIterator``. This should be done by looking for the presence of each expectd `Tuple` key value, and using the associated value as required. Most apps will deal with integer values or strings to pass signals or some human-readable information respectively. These common use cases are discussed below. ### Reading an Integer **From JS** ```js var dict = { 'Temperature': 29 }; ``` **In C** ```c static void inbox_received_callback(DictionaryIterator *iter, void *context) { // A new message has been successfully received // Does this message contain a temperature value? Tuple *temperature_tuple = dict_find(iter, MESSAGE_KEY_Temperature); if(temperature_tuple) { // This value was stored as JS Number, which is stored here as int32_t int32_t temperature = temperature_tuple->value->int32; } } ``` ### Reading a String A common use of transmitted strings is to display them in a ``TextLayer``. Since the displayed text is required to be long-lived, a `static` `char` buffer can be used when the data is received: **From JS** ```js var dict = { 'LocationName': 'London, UK' }; ``` **In C** ```c static void inbox_received_callback(DictionaryIterator *iter, void *context) { // Is the location name inside this message? Tuple *location_tuple = dict_find(iter, MESSAGE_KEY_LocationName); if(location_tuple) { // This value was stored as JS String, which is stored here as a char string char *location_name = location_tuple->value->cstring; // Use a static buffer to store the string for display static char s_buffer[MAX_LENGTH]; snprintf(s_buffer, sizeof(s_buffer), "Location: %s", location_name); // Display in the TextLayer text_layer_set_text(s_text_layer, s_buffer); } } ``` ### Reading Binary Data Apps that deal in packed binary data can send this data and pack/unpack as required on either side: **From JS** ```js var dict = { 'Data': [1, 2, 4, 8, 16, 32, 64] }; ``` **In C** ```c static void inbox_received_callback(DictionaryIterator *iter, void *context) { // Expected length of the binary data const int length = 32; // Does this message contain the data tuple? Tuple *data_tuple = dict_find(iter, MESSAGE_KEY_Data); if(data_tuple) { // Read the binary data value uint8_t *data = data_tuple->value->data; // Inspect the first byte, for example uint8_t byte_zero = data[0]; // Store into an app-defined buffer memcpy(s_buffer, data, length); } ```
{ "source": "google/pebble", "title": "devsite/source/_guides/communication/sending-and-receiving-data.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/communication/sending-and-receiving-data.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 13908 }
--- # Copyright 2025 Google LLC # # 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. title: PebbleKit Android description: How to use PebbleKit to communicate with a watchapp on Android. guide_group: communication order: 2 --- [PebbleKit Android](https://github.com/pebble/pebble-android-sdk/) is a Java library that works with the Pebble SDK and can be embedded in any Android application. Using the classes and methods in this library, an Android companion app can find and exchange data with a Pebble watch. This section assumes that the reader is familiar with basic Android development and Android Studio as an integrated development environment. Refer to the [Android Documentation](http://developer.android.com/sdk/index.html) for more information on installing the Android SDK. Most PebbleKit Android methods require a `Context` parameter. An app can use `getApplicationContext()`, which is available from any `Activity` implementation. ### Setting Up PebbleKit Android Add PebbleKit Android to an Android Studio project in the `app/build.gradle` file: ``` dependencies { compile 'com.getpebble:pebblekit:{{ site.data.sdk.pebblekit-android.version }}' } ``` ### Sending Messages from Android Since Android apps are built separately from their companion Pebble apps, there is no way for the build system to automatically create matching appmessage keys. You must therefore manually specify them in `package.json`, like so: ```js { "ContactName": 0, "Age": 1 } ``` These numeric values can then be used as appmessage keys in your Android app. Messages are constructed with the `PebbleDictionary` class and sent to a C watchapp or watchface using the `PebbleKit` class. The first step is to create a `PebbleDictionary` object: ```java // Create a new dictionary PebbleDictionary dict = new PebbleDictionary(); ``` Data items are added to the [`PebbleDictionary`](/docs/pebblekit-android/com/getpebble/android/kit/util/PebbleDictionary) using key-value pairs with the methods made available by the object, such as `addString()` and `addInt32()`. An example is shown below: ```java // The key representing a contact name is being transmitted final int AppKeyContactName = 0; final int AppKeyAge = 1; // Get data from the app final String contactName = getContact(); final int age = getAge(); // Add data to the dictionary dict.addString(AppKeyContactName, contactName); dict.addInt32(AppKeyAge, age); ``` Finally, the dictionary is sent to the C app by calling `sendDataToPebble()` with a UUID matching that of the C app that will receive the data: ```java final UUID appUuid = UUID.fromString("EC7EE5C6-8DDF-4089-AA84-C3396A11CC95"); // Send the dictionary PebbleKit.sendDataToPebble(getApplicationContext(), appUuid, dict); ``` Once delivered, this dictionary will be available in the C app via the ``AppMessageInboxReceived`` callback, as detailed in {% guide_link communication/sending-and-receiving-data#inbox-received %}. ### Receiving Messages on Android Receiving messages from Pebble in a PebbleKit Android app requires a listener to be registered in the form of a `PebbleDataReceiver` object, which extends `BroadcastReceiver`: ```java // Create a new receiver to get AppMessages from the C app PebbleDataReceiver dataReceiver = new PebbleDataReceiver(appUuid) { @Override public void receiveData(Context context, int transaction_id, PebbleDictionary dict) { // A new AppMessage was received, tell Pebble PebbleKit.sendAckToPebble(context, transaction_id); } }; ``` <div class="alert alert--fg-white alert--bg-dark-red"> {% markdown %} **Important** PebbleKit apps **must** manually send an acknowledgement (Ack) to Pebble to inform it that the message was received successfully. Failure to do this will cause timeouts. {% endmarkdown %} </div> Once created, this receiver should be registered in `onResume()`, overridden from `Activity`: ```java @Override public void onResume() { super.onResume(); // Register the receiver PebbleKit.registerReceivedDataHandler(getApplicationContext(), dataReceiver); } ``` > Note: To avoid getting callbacks after the `Activity` or `Service` has exited, > apps should attempt to unregister the receiver in `onPause()` with > `unregisterReceiver()`. With a receiver in place, data can be read from the provided [`PebbleDictionary`](/docs/pebblekit-android/com/getpebble/android/kit/util/PebbleDictionary) using analogous methods such as `getString()` and `getInteger()`. Before reading the value of a key, the app should first check that it exists using a `!= null` check. The example shown below shows how to read an integer from the message, in the scenario that the watch is sending an age value to the Android companion app: ```java @Override public void receiveData(Context context, int transaction_id, PebbleDictionary dict) { // If the tuple is present... Long ageValue = dict.getInteger(AppKeyAge); if(ageValue != null) { // Read the integer value int age = ageValue.intValue(); } } ``` ### Other Capabilities In addition to sending and receiving messages, PebbleKit Android also allows more intricate interactions with Pebble. See the [PebbleKit Android Documentation](/docs/pebblekit-android/com/getpebble/android/kit/PebbleKit/) for a complete list of available methods. Some examples are shown below of what is possible: * Checking if the watch is connected: ```java boolean connected = PebbleKit.isWatchConnected(getApplicationContext()); ``` * Registering for connection events with `registerPebbleConnectedReceiver()` and `registerPebbleDisconnectedReceiver()`, and a suitable `BroadcastReceiver`. ```java PebbleKit.registerPebbleConnectedReceiver(getApplicationContext(), new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { } }); ``` * Registering for Ack/Nack events with `registerReceivedAckHandler()` and `registerReceivedNackHandler()`. ```java PebbleKit.registerReceivedAckHandler(getApplicationContext(), new PebbleKit.PebbleAckReceiver(appUuid) { @Override public void receiveAck(Context context, int i) { } }); ``` * Launching and killing the watchapp with `startAppOnPebble()` and `closeAppOnPebble()`. ```java PebbleKit.startAppOnPebble(getApplicationContext(), appUuid); ```
{ "source": "google/pebble", "title": "devsite/source/_guides/communication/using-pebblekit-android.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/communication/using-pebblekit-android.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 7061 }
--- # Copyright 2025 Google LLC # # 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. title: PebbleKit iOS description: How to use PebbleKit to communicate with a watchapp on iOS. guide_group: communication order: 3 --- [PebbleKit iOS](https://github.com/pebble/pebble-ios-sdk/) is an Objective-C framework that works with the Pebble SDK and can be embedded in any iOS application for **iOS 7.1** and above. Using the classes and methods in this framework, an iOS app can find and exchange data with a Pebble watch. This section assumes that the reader has a basic knowledge of Objective-C, Xcode as an IDE, and the delegate and block patterns. > PebbleKit iOS should be compatible if your app uses Swift. The framework > itself is written in Objective-C to avoid the requirement of the Swift runtime > in pure Objective-C apps, and to improve the backwards and forwards > compatibility. ### Setting Up PebbleKit iOS If the project is using [CocoaPods](http://cocoapods.org/) (which is the recommended approach), just add `pod 'PebbleKit'` to the `Podfile` and execute `pod install`. After installing PebbleKit iOS in the project, perform these final steps: * If the iOS app needs to run in the background, you should update your target’s “Capabilities” in Xcode. Enable “Background Modes” and select both “Uses Bluetooth LE accessories” and “Acts as a Bluetooth LE accessory”. This should add the keys `bluetooth-peripheral` (“App shares data using CoreBluetooth”) and `bluetooth-central` (“App communicates using CoreBluetooth”) to your target’s `Info.plist` file. * If you are using Xcode 8 or greater (and recommended for previous versions), you must also add the key `NSBluetoothPeripheralUsageDescription` (“Privacy - Bluetooth Peripheral Usage Description”) to your `Info.plist`. > To add PebbleKit iOS manually, or some other alternatives follow the steps in > the [repository](https://github.com/pebble/pebble-ios-sdk/). The documentation > might also include more information that might be useful. Read it carefully. ### Targeting a Companion App Before an iOS companion app can start communicating or exchange messages with a watchapp on Pebble, it needs to give PebbleKit a way to identify the watchapp. The UUID of your watchapp is used for this purpose. Set the app UUID associated with the PBPebbleCentral instance. A simple way to create a UUID in standard representation to `NSUUID` is shown here: ```objective-c // Set UUID of watchapp NSUUID *myAppUUID = [[NSUUID alloc] initWithUUIDString:@"226834ae-786e-4302-a52f-6e7efc9f990b"]; [PBPebbleCentral defaultCentral].appUUID = myAppUUID; ``` If you are trying to communicate with the built-in Sports or Golf apps, their UUID are available as part of PebbleKit with ``PBSportsUUID`` and ``PBGolfUUID``. You must register those UUID if you intend to communicate with those apps. ### Becoming a Delegate To communicate with a Pebble watch, the class must implement `PBPebbleCentralDelegate`: ```objective-c @interface ViewController () <PBPebbleCentralDelegate> ``` The `PBPebbleCentral` class should not be instantiated directly. Instead, always use the singleton provided by `[PBPebbleCentral defaultCentral]`. An example is shown below, with the Golf app UUID: ```objective-c central = [PBPebbleCentral defaultCentral]; central.appUUID = myAppUUID; [central run]; ``` Once this is done, set the class to be the delegate: ```objective-c [PBPebbleCentral defaultCentral].delegate = self; ``` This delegate will get two callbacks: `pebbleCentral:watchDidConnect:isNew:` and `pebbleCentral:watchDidDisconnect:` every time a Pebble connects or disconnects. The app won't get connection callbacks if the Pebble is already connected when the delegate is set. Implement these to receive the associated connection/disconnection events: ```objective-c - (void)pebbleCentral:(PBPebbleCentral *)central watchDidConnect:(PBWatch *)watch isNew:(BOOL)isNew { NSLog(@"Pebble connected: %@", watch.name); // Keep a reference to this watch self.connectedWatch = watch; } - (void)pebbleCentral:(PBPebbleCentral *)central watchDidDisconnect:(PBWatch *)watch { NSLog(@"Pebble disconnected: %@", watch.name); // If this was the recently connected watch, forget it if ([watch isEqual:self.connectedWatch]) { self.connectedWatch = nil; } } ``` ### Initiating Bluetooth Communication Once the iOS app is correctly set up to communicate with Pebble, the final step is to actually begin communication. No communication can take place until the following is called: ```objective-c [[PBPebbleCentral defaultCentral] run]; ``` > Once this occurs, the user _may_ be shown a dialog asking for confirmation > that they want the app to communicate. This means the app should not call > `run:` until the appropriate moment in the UI. ### Sending Messages from iOS Since iOS apps are built separately from their companion Pebble apps, there is no way for the build system to automatically create matching app message keys. You must therefore manually specify them in `package.json`, like so: ```js { "Temperature": 0, "WindSpeed": 1, "WindDirection": 2, "RequestData": 3, "LocationName": 4 } ``` These numeric values can then be used as app message keys in your iOS app. Messages are constructed with the `NSDictionary` class and sent to the C watchapp or watchface by the `PBPebbleCentralDelegate` when the `appMessagesPushUpdate:` function is invoked. To send a message, prepare an `NSDictionary` object with the data to be sent to the C watchapp. Data items are added to the [`NSDictionary`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/) using key-value pairs of standard data types. An example containing a string and an integer is shown below: ```objective-c NSDictionary *update = @{ @(0):[NSNumber pb_numberWithUint8:42], @(1):@"a string" }; ``` Send this dictionary to the watchapp using `appMessagesPushUpdate:`. The first argument is the update dictionary to send and the second argument is a callback block that will be invoked when the data has been acknowledged by the watch (or if an error occurs). ```objective-c [self.connectedWatch appMessagesPushUpdate:update onSent:^(PBWatch *watch, NSDictionary *update, NSError *error) { if (!error) { NSLog(@"Successfully sent message."); } else { NSLog(@"Error sending message: %@", error); } }]; ``` Once delivered, this dictionary will be available in the C app via the ``AppMessageInboxReceived`` callback, as detailed in {% guide_link communication/sending-and-receiving-data#inbox-received %}. ### Receiving Messages on iOS To receive messages from a watchapp, register a receive handler (a block) with `appMessagesAddReceiveUpdateHandler:`. This block will be invoked with two parameters - a pointer to a `PBWatch` object describing the Pebble that sent the message and an `NSDictionary` with the message received. ```objective-c [self.connectedWatch appMessagesAddReceiveUpdateHandler:^BOOL(PBWatch *watch, NSDictionary *update) { NSLog(@"Received message: %@", update); // Send Ack to Pebble return YES; }]; ``` > Always return `YES` in the handler. This instructs PebbleKit to automatically > send an ACK to Pebble, to avoid the message timing out. Data can be read from the `NSDictionary` by first testing for each key's presence using a `!= nil` check, and reading the value if it is present: ```objective-c NSNumber *key = @1; // If the key is present in the received dictionary if (update[key]) { // Read the integer value int value = [update[key] intValue]; } ``` ### Other Capabilities In addition to sending and receiving messages, PebbleKit iOS also allows more intricate interactions with Pebble. See the [PebbleKit iOS Documentation](/docs/pebblekit-ios/) for more information. Some examples are shown below of what is possible: * Checking if the watch is connected using the `connected` property of a `PBWatch`. ```objective-c BOOL isConnected = self.watch.connected; ``` * Receiving `watchDidConnect` and `watchDidDisconnect` events through being a `PBDataloggingServiceDelegate`. ### Limitations of PebbleKit on iOS The iOS platform imposes some restrictions on what apps can do with accessories. It also limits the capabilities of apps that are in the background. It is critical to understand these limitations when developing an app that relies on PebbleKit iOS. On iOS, all communication between a mobile app and Pebble is managed through a communication session. This communication session is a protocol specific to iOS, with notable limitations that the reader should know and understand when developing an iOS companion app for Pebble. #### Bluetooth Low Energy (BLE) Connections For Pebble apps that communicate with Pebble in BLE mode, a session can be created for each app that requires one. This removes the 'one session only' restriction, but only for these BLE apps. Currently, there are several BLE only devices, such as Pebble Time Round, and Pebble 2, but all the devices using a firmware 3.8 or greater can use BLE to communicate with PebbleKit. For BLE apps, the 'phone must launch' restriction is removed. The iOS companion app can be restarted by the watchapp if it stops working if user force-quits iOS app, or it crashes. Note that the app will not work after rebooting iOS device, which requires it be launched by the iPhone user once after boot. #### Communication with firmware older than 3.0 PebbleKit iOS 3.1.1 is the last PebbleKit that supports communication with firmwares older than 3.0. PebbleKit iOS 4.0.0 can only communicate with Pebble devices with firmware newer than 3.0. For newer devices like Pebble Time, Pebble Time Steel, Pebble Time Round, and Pebble 2 there should be no problem. For previous generation devices like Pebble and Pebble Steel it means that their users should upgrade their firmware to the latest firmware available for their devices using the new apps. This change allows better compatibility and new features to be developed by 3rd parties.
{ "source": "google/pebble", "title": "devsite/source/_guides/communication/using-pebblekit-ios.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/communication/using-pebblekit-ios.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 10653 }
--- # Copyright 2025 Google LLC # # 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. title: PebbleKit JS description: | How to use PebbleKit JS to communicate with the connected phone's JS environment. guide_group: communication order: 4 platform_choice: true --- PebbleKit JS allows a JavaScript component (run in a sandbox inside the official Pebble mobile app) to be added to any watchapp or watchface in order to extend the functionality of the app beyond what can be accomplished on the watch itself. Extra features available to an app using PebbleKit JS include: * Access to extended storage with [`localStorage`](#using-localstorage). * Internet access using [`XMLHttpRequest`](#using-xmlhttprequest). * Location data using [`geolocation`](#using-geolocation). * The ability to show a configuration page to allow users to customize how the app behaves. This is discussed in detail in {% guide_link user-interfaces/app-configuration %}. ## Setting Up ^LC^ PebbleKit JS can be set up by creating the `index.js` file in the project's `src/pkjs/` directory. Code in this file will be executed when the associated watchapp is launched, and will stop once that app exits. ^CP^ PebbleKit JS can be set up by clicking 'Add New' in the Source Files section of the sidebar. Choose the 'JavaScript file' type and choose a file name before clicking 'Create'. Code in this file will be executed when the associated watchapp is launched, and will stop once that app exits. The basic JS code required to begin using PebbleKit JS is shown below. An event listener is created to listen for the `ready` event - fired when the watchapp has been launched and the JS environment is ready to receive messages. This callback must return within a short space of time (a few seconds) or else it will timeout and be killed by the phone. ```js Pebble.addEventListener('ready', function() { // PebbleKit JS is ready! console.log('PebbleKit JS ready!'); }); ``` <div class="alert alert--fg-white alert--bg-dark-red"> {% markdown %} **Important** A watchapp or watchface **must** wait for the `ready` event before attempting to send messages to the connected phone. See [*Advanced Communication*](/guides/communication/advanced-communication#waiting-for-pebblekit-js) to learn how to do this. {% endmarkdown %} </div> ## Defining Keys ^LC^ Before any messages can be sent or received, the keys to be used to store the data items in the dictionary must be declared. The watchapp side uses exclusively integer keys, whereas the JavaScript side may use the same integers or named string keys declared in `package.json`. Any string key not declared beforehand will not be transmitted to/from Pebble. ^CP^ Before any messages can be sent or received, the keys to be used to store the data items in the dictionary must be declared. The watchapp side uses exclusively integer keys, whereas the JavaScript side may use the same integers or named string keys declared in the 'PebbleKit JS Message Keys' section of 'Settings'. Any string key not declared beforehand will not be transmitted to/from Pebble. > Note: This requirement is true of PebbleKit JS **only**, and not PebbleKit > Android or iOS. ^LC^ Keys are declared in the project's `package.json` file in the `messageKeys` object, which is inside the `pebble` object. Example keys are shown as equivalents to the ones used in the hypothetical weather app example in {% guide_link communication/sending-and-receiving-data#choosing-key-values %}. <div class="platform-specific" data-sdk-platform="local"> {% highlight {} %} "messageKeys": [ "Temperature", "WindSpeed", "WindDirection", "RequestData", "LocationName" ] {% endhighlight %} </div> ^CP^ Keys are declared individually in the 'PebbleKit JS Message Keys' section of the 'Settings' page. Enter the 'Key Name' of each key that will be used by the app. The names chosen here will be injected into your C code prefixed with `MESSAGE_KEY_`, like `MESSAGE_KEY_Temperature`. As such, they must be legal C identifiers. If you want to emulate an array by attaching multiple "keys" to a name, you can specify the size of the array by adding it in square brackets: for instance, `"LapTimes[10]`" would create a key called `LapTimes` and leave nine empty keys after it which can be accessed by arithmetic, e.g. `MESSAGE_KEY_LapTimes + 3`. ## Sending Messages from JS Messages are sent to the C watchapp or watchface using `Pebble.sendAppMessage()`, which accepts a standard JavaScript object containing the keys and values to be transmitted. The keys used **must** be identical to the ones declared earlier. An example is shown below: ```js // Assemble data object var dict = { 'Temperature': 29, 'LocationName': 'London, UK' }; // Send the object Pebble.sendAppMessage(dict, function() { console.log('Message sent successfully: ' + JSON.stringify(dict)); }, function(e) { console.log('Message failed: ' + JSON.stringify(e)); }); ``` It is also possible to read the numeric values of the keys by `require`ing `message_keys`, which is necessary to use the array feature. For instance: ```js // Require the keys' numeric values. var keys = require('message_keys'); // Build a dictionary. var dict = {} dict[keys.LapTimes] = 42 dict[keys.LapTimes+1] = 51 // Send the object Pebble.sendAppMessage(dict, function() { console.log('Message sent successfully: ' + JSON.stringify(dict)); }, function(e) { console.log('Message failed: ' + JSON.stringify(e)); }); ``` ### Type Conversion Depending on the type of the item in the object to be sent, the C app will be able to read the value (from the [`Tuple.value` union](/guides/communication/sending-and-receiving-data#data-types)) according to the table below: | JS Type | Union member | |---------|--------------| | String | cstring | | Number | int32 | | Array | data | | Boolean | int16 | ## Receiving Messages in JS When a message is received from the C watchapp or watchface, the `appmessage` event is fired in the PebbleKit JS app. To receive these messages, register the appropriate event listener: ```js // Get AppMessage events Pebble.addEventListener('appmessage', function(e) { // Get the dictionary from the message var dict = e.payload; console.log('Got message: ' + JSON.stringify(dict)); }); ``` Data can be read from the dictionary by reading the value if it is present. A suggested best practice involves first checking for the presence of each key within the callback using an `if()` statement. ```js if(dict['RequestData']) { // The RequestData key is present, read the value var value = dict['RequestData']; } ``` ## Using LocalStorage In addition to the storage available on the watch itself through the ``Storage`` API, apps can take advantage of the larger storage on the connected phone through the use of the HTML 5 [`localStorage`](http://www.w3.org/TR/webstorage/) API. Data stored here will persist across app launches, and so can be used to persist latest data, app settings, and other data. PebbleKit JS `localStorage` is: * Associated with the application UUID and cannot be shared between apps. * Persisted when the user uninstalls and then reinstalls an app. * Persisted when the user upgrades an app. To store a value: ```js var color = '#FF0066'; // Store some data localStorage.setItem('backgroundColor', color); ``` To read the data back: ```js var color = localStorage.getItem('backgroundColor'); ``` > Note: Keys used with `localStorage` should be Strings. ## Using XMLHttpRequest A PebbleKit JS-equipped app can access the internet and communicate with web services or download data using the standard [`XMLHttpRequest`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) object. To communicate with the web, create an `XMLHttpRequest` object and send it, specifying the HTTP method and URL to be used, as well as a callback for when it is successfully completed: ```js var method = 'GET'; var url = 'http://example.com'; // Create the request var request = new XMLHttpRequest(); // Specify the callback for when the request is completed request.onload = function() { // The request was successfully completed! console.log('Got response: ' + this.responseText); }; // Send the request request.open(method, url); request.send(); ``` If the response is expected to be in the JSON format, data items can be easily read after the `responseText` is converted into a JSON object: ```js request.onload = function() { try { // Transform in to JSON var json = JSON.parse(this.responseText); // Read data var temperature = json.main.temp; } catch(err) { console.log('Error parsing JSON response!'); } }; ``` ## Using Geolocation PebbleKit JS provides access to the location services provided by the phone through the [`navigator.geolocation`](http://dev.w3.org/geo/api/spec-source.html) object. ^CP^ Declare that the app will be using the `geolocation` API by checking the 'Uses Location' checkbox in the 'Settings' screen. ^LC^ Declare that the app will be using the `geolocation` API by adding the string `location` in the `capabilities` array in `package.json`: <div class="platform-specific" data-sdk-platform="local"> {% highlight {} %} "capabilities": [ "location" ] {% endhighlight %} </div> Below is an example showing how to get a single position value from the `geolocation` API using the [`getCurrentPosition()`](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) method: ```js function success(pos) { console.log('lat= ' + pos.coords.latitude + ' lon= ' + pos.coords.longitude); } function error(err) { console.log('location error (' + err.code + '): ' + err.message); } /* ... */ // Choose options about the data returned var options = { enableHighAccuracy: true, maximumAge: 10000, timeout: 10000 }; // Request current position navigator.geolocation.getCurrentPosition(success, error, options); ``` Location permission is given by the user to the Pebble application for all Pebble apps. The app should gracefully handle the `PERMISSION DENIED` error and fallback to a default value or manual configuration when the user has denied location access to Pebble apps. ```js function error(err) { if(err.code == err.PERMISSION_DENIED) { console.log('Location access was denied by the user.'); } else { console.log('location error (' + err.code + '): ' + err.message); } } ``` The `geolocation` API also provides a mechanism to receive callbacks when the user's position changes to avoid the need to manually poll at regular intervals. This is achieved by using [`watchPosition()`](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition) in a manner similar to the example below: ```js // An ID to store to later clear the watch var watchId; function success(pos) { console.log('Location changed!'); console.log('lat= ' + pos.coords.latitude + ' lon= ' + pos.coords.longitude); } function error(err) { console.log('location error (' + err.code + '): ' + err.message); } /* ... */ var options = { enableHighAccuracy: true, maximumAge: 0, timeout: 5000 }; // Get location updates watchId = navigator.geolocation.watchPosition(success, error, options); ``` To cancel the update callbacks, use the `watchId` variable received when the watch was registered with the [`clearWatch()`](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/clearWatch) method: ```js // Clear the watch and stop receiving updates navigator.geolocation.clearWatch(watchId); ``` ## Account Token PebbleKit JS provides a unique account token that is associated with the Pebble account of the current user, accessible using `Pebble.getAccountToken()`: ```js // Get the account token console.log('Pebble Account Token: ' + Pebble.getAccountToken()); ``` The token is a string with the following properties: * From the developer's perspective, the account token of a user is identical across platforms and across all the developer's watchapps. * If the user is not logged in, the token will be an empty string (''). ## Watch Token PebbleKit JS also provides a unique token that can be used to identify a Pebble device. It works in a similar way to `Pebble.getAccountToken()`: ```js // Get the watch token console.log('Pebble Watch Token: ' + Pebble.getWatchToken()); ``` The token is a string that is unique to the app and cannot be used to track Pebble devices across applications. <div class="alert alert--fg-white alert--bg-dark-red"> {% markdown %} **Important** The watch token is dependent on the watch's serial number, and therefore **should not** be used to store sensitive user information in case the watch changes ownership. If the app wishes to track a specific user _and_ watch, use a combination of the watch and account token. {% endmarkdown %} </div> ## Showing a Notification A PebbleKit JS app can send a notification to the watch. This uses the standard system notification layout with customizable `title` and `body` fields: ```js var title = 'Update Available'; var body = 'Version 1.5 of this app is now available from the appstore!'; // Show the notification Pebble.showSimpleNotificationOnPebble(title, body); ``` > Note: PebbleKit Android/iOS applications cannot directly invoke a > notification, and should instead leverage the respective platform notification > APIs. These will be passed on to Pebble unless the user has turned them off in > the mobile app. ## Getting Watch Information Use `Pebble.getActiveWatchInfo()` to return an object of data about the connected Pebble. <div class="alert alert--fg-white alert--bg-purple"> {% markdown %} This API is currently only available for SDK 3.0 and above. Do not assume that this function exists, so test that it is available before attempting to use it using the code shown below. {% endmarkdown %} </div> ```js var watch = Pebble.getActiveWatchInfo ? Pebble.getActiveWatchInfo() : null; if(watch) { // Information is available! } else { // Not available, handle gracefully } ``` > Note: If there is no active watch available, `null` will be returned. The table below details the fields of the returned object and the information available. | Field | Type | Description | Values | |-------|------|-------------|--------| | `platform` | String | Hardware platform name. | `aplite`, `basalt`, `chalk`. | | `model` | String | Watch model name including color. | `pebble_black`, `pebble_grey`, `pebble_white`, `pebble_red`, `pebble_orange`, `pebble_blue`, `pebble_green`, `pebble_pink`, `pebble_steel_silver`, `pebble_steel_black`, `pebble_time_red`, `pebble_time_white`, `pebble_time_black`, `pebble_time_steel_black`, `pebble_time_steel_silver`, `pebble_time_steel_gold`, `pebble_time_round_silver_14mm`, `pebble_time_round_black_14mm`, `pebble_time_round_rose_gold_14mm`, `pebble_time_round_silver_20mm`, `pebble_time_round_black_20mm`, `qemu_platform_aplite`, `qemu_platform_basalt`, `qemu_platform_chalk`. | | `language` | String | Language currently selected on the watch. | E.g.: `en_GB`. See the {% guide_link tools-and-resources/internationalization#locales-supported-by-pebble %} for more information. | | `firmware` | Object | The firmware version running on the watch. | See below for sub-fields. | | `firmware.major` | Number | Major firmware version. | E.g.: `2` | | `firmware.minor` | Number | Minor firmware version. | E.g.: `8` | | `firmware.patch` | Number | Patch firmware version. | E.g.: `1` | | `firmware.suffix` | String | Any additional firmware versioning. | E.g.: `beta3` |
{ "source": "google/pebble", "title": "devsite/source/_guides/communication/using-pebblekit-js.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/communication/using-pebblekit-js.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 16109 }
--- # Copyright 2025 Google LLC # # 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. title: Sports API description: | How to use the PebbleKit Sports API to integrate your mobile sports app with Pebble. guide_group: communication order: 6 related_examples: - title: PebbleKit Sports API Demos - url: https://github.com/pebble-examples/pebblekit-sports-api-demo --- Every Pebble watch has two built-in system watchapps called the Sports app, and the Golf app. These apps are hidden from the launcher until launched via PebbleKit Android or PebbleKit iOS. Both are designed to be generic apps that display sports-related data in common formats. The goal is to allow fitness and golf mobile apps to integrate with Pebble to show the wearer data about their activity without needing to create and maintain an additional app for Pebble. An example of a popular app that uses this approach is the [Runkeeper](http://apps.getpebble.com/en_US/application/52e05bd5d8561de307000039) app. The Sports and Golf apps are launched, closed, and controlled by PebbleKit in an Android or iOS app, shown by example in each section below. In both cases, the data fields that are available to be populated are different, but data is pushed in the same way. ## Available Data Fields ### Sports {% screenshot_viewer %} { "image": "/images/guides/design-and-interaction/sports.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} The sports app displays activity duration and distance which can apply to a wide range of sports, such as cycling or running. A configurable third field is also available that displays pace or speed, depending on the app's preference. The Sports API also allows the app to be configured to display the labels of each field in metric (the default) or imperial units. The action bar is used to prompt the user to use the Select button to pause and resume their activity session. The companion app is responsible for listening for these events and implementing the pause/resume operation as appropriate. ### Golf {% screenshot_viewer %} { "image": "/images/guides/design-and-interaction/golf.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} The Golf app is specialized to displaying data relevant to golf games, including par and hole numbers, as well as front, mid, and rear yardage. Similar to the Sports app, the action bar is used to allow appropriate feedback to the companion app. In this case the actions are an 'up', 'ball' and 'down' events which the companion should handle as appropriate. ## With PebbleKit Android Once an Android app has set up {% guide_link communication/using-pebblekit-android %}, the Sports and Golf apps can be launched and customized as appropriate. ### Launching Sports and Golf To launch one of the Sports API apps, simply call `startAppOnPebble()` and supply the UUID from the `Constants` class: ```java // Launch the Sports app PebbleKit.startAppOnPebble(getApplicationContext(), Constants.SPORTS_UUID); ``` ### Customizing Sports To choose which unit type is used, construct and send a `PebbleDictionary` containing the desired value from the `Constants` class. Either `SPORTS_UNITS_IMPERIAL` or `SPORTS_UNITS_METRIC` can be used: ```java PebbleDictionary dict = new PebbleDictionary(); // Display imperial units dict.addUint8(Constants.SPORTS_UNITS_KEY, Constants.SPORTS_UNITS_IMPERIAL); PebbleKit.sendDataToPebble(getApplicationContext(), Constants.SPORTS_UUID, dict); ``` To select between 'pace' or 'speed' as the label for the third field, construct and send a `PebbleDictionary` similar to the example above. This can be done in the same message as unit selection: ```java PebbleDictionary dict = new PebbleDictionary(); // Display speed instead of pace dict.addUint8(Constants.SPORTS_LABEL_KEY, Constants.SPORTS_DATA_SPEED); PebbleKit.sendDataToPebble(getApplicationContext(), Constants.SPORTS_UUID, dict); ``` > Note: The Golf app does not feature any customizable fields. ### Displaying Data Data about the current activity can be sent to either of the Sports API apps using a `PebbleDictionary`. For example, to show a value for duration and distance in the Sports app: ```java PebbleDictionary dict = new PebbleDictionary(); // Show a value for duration and distance dict.addString(Constants.SPORTS_TIME_KEY, "12:52"); dict.addString(Constants.SPORTS_DISTANCE_KEY, "23.8"); PebbleKit.sendDataToPebble(getApplicationContext(), Constants.SPORTS_UUID, dict); ``` Read the [`Constants`](/docs/pebblekit-android/com/getpebble/android/kit/Constants) documentation to learn about all the available parameters that can be used for customization. ### Handling Button Events When a button event is generated from one of the Sports API apps, a message is sent to the Android companion app, which can be processed using a `PebbleDataReceiver`. For example, to listen for a change in the state of the Sports app, search for `Constants.SPORTS_STATE_KEY` in the received `PebbleDictionary`. The user is notified in the example below through the use of an Android [`Toast`](http://developer.android.com/guide/topics/ui/notifiers/toasts.html): ```java // Create a receiver for when the Sports app state changes PebbleDataReceiver reciever = new PebbleKit.PebbleDataReceiver( Constants.SPORTS_UUID) { @Override public void receiveData(Context context, int id, PebbleDictionary data) { // Always ACKnowledge the last message to prevent timeouts PebbleKit.sendAckToPebble(getApplicationContext(), id); // Get action and display as Toast Long value = data.getUnsignedIntegerAsLong(Constants.SPORTS_STATE_KEY); if(value != null) { int state = value.intValue(); String text = (state == Constants.SPORTS_STATE_PAUSED) ? "Resumed!" : "Paused!"; Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); } } }; // Register the receiver PebbleKit.registerReceivedDataHandler(getApplicationContext(), receiver); ``` ## With PebbleKit iOS Once an iOS app has set up {% guide_link communication/using-pebblekit-ios %}, the Sports and Golf apps can be launched and customized as appropriate. The companion app should set itself as a delegate of `PBPebbleCentralDelegate`, and assign a `PBWatch` property once `watchDidConnect:` has fired. This `PBWatch` object will then be used to manipulate the Sports API apps. Read *Becoming a Delegate* in the {% guide_link communication/using-pebblekit-ios %} guide to see how this is done. ### Launching Sports and Golf To launch one of the Sports API apps, simply call `sportsAppLaunch:` or `golfAppLaunch:` as appropriate: ```objective-c [self.watch sportsAppLaunch:^(PBWatch * _Nonnull watch, NSError * _Nullable error) { NSLog(@"Sports app was launched"); }]; ``` ### Customizing Sports To choose which unit type is used, call `sportsAppSetMetric:` with the desired `isMetric` `BOOL`: ```objective-c BOOL isMetric = YES; [self.watch sportsAppSetMetric:isMetric onSent:^(PBWatch * _Nonnull watch, NSError * _Nonnull error) { if (!error) { NSLog(@"Successfully sent message."); } else { NSLog(@"Error sending message: %@", error); } }]; ``` To select between 'pace' or 'speed' as the label for the third field, call `sportsAppSetLabel:` with the desired `isPace` `BOOL`: ```objective-c BOOL isPace = YES; [self.watch sportsAppSetLabel:isPace onSent:^(PBWatch * _Nonnull watch, NSError * _Nullable error) { if (!error) { NSLog(@"Successfully sent message."); } else { NSLog(@"Error sending message: %@", error); } }]; ``` > Note: The Golf app does not feature any customizable fields. ### Displaying Data Data about the current activity can be sent to either the Sports or Golf app using `sportsAppUpdate:` or `golfAppUpdate:`. For example, to show a value for duration and distance in the Sports app: ```objective-c // Construct a dictionary of data NSDictionary *update = @{ PBSportsTimeKey: @"12:34", PBSportsDistanceKey: @"6.23" }; // Send the data to the Sports app [self.watch sportsAppUpdate:update onSent:^(PBWatch * _Nonnull watch, NSError * _Nullable error) { if (!error) { NSLog(@"Successfully sent message."); } else { NSLog(@"Error sending message: %@", error); } }]; ``` Read the [`PBWatch`](/docs/pebblekit-ios/Classes/PBWatch/) documentation to learn about all the available methods and values for customization. ### Handling Button Events When a button event is generated from one of the Sports API apps, a message is sent to the Android companion app, which can be processed using `sportsAppAddReceiveUpdateHandler` and supplying a block to be run when a message is received. For example, to listen for change in state of the Sports app, check the value of the provided `SportsAppActivityState`: ```objective-c // Register to get state updates from the Sports app [self.watch sportsAppAddReceiveUpdateHandler:^BOOL(PBWatch *watch, SportsAppActivityState state) { // Display the new state of the watchapp switch (state) { case SportsAppActivityStateRunning: NSLog(@"Watchapp now running."); break; case SportsAppActivityStatePaused: NSLog(@"Watchapp now paused."); break; default: break; } // Finally return YES; }]; ```
{ "source": "google/pebble", "title": "devsite/source/_guides/communication/using-the-sports-api.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/communication/using-the-sports-api.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 10430 }
--- # Copyright 2025 Google LLC # # 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. title: Common Runtime Errors description: | Examples of commonly encountered runtime problems that cannot be detected at compile time and can usually be fixed by logical thought and experimentation. guide_group: debugging order: 3 --- Whether just beginning to create apps for the Pebble platform or are creating a more complex app, the output from app logs can be very useful in tracking down problems with an app's code. Some examples of common problems are explored here, including some examples to help gain familiarity with compiler output. In contrast with syntactical errors in written code (See {% guide_link debugging/common-syntax-errors %}), there can also be problems that only occur when the app is actually run on a Pebble. The reason for this is that perfectly valid C code can sometimes cause improper behavior that is incompatible with the hardware. These problems can manifest themselves as an app crashing and very little other information available as to what the cause was, which means that they can take an abnormally long time to diagnose and fix. One option to help track down the offending lines is to begin at the start of app initialization and use a call to ``APP_LOG()`` to establish where execution stops. If the message in the log call appears, then execution has at least reached that point. Move the call further through logical execution until it ceases to appear, as it will then be after the point where the app crashes. ## Null Pointers The Pebble SDK uses a dynamic memory allocation model, meaning that all the SDK objects and structures available for use by developers are allocated as and when needed. This model has the advantage that only the immediately needed data and objects can be kept in memory and unloaded when they are not needed, increasing the scale and capability of apps that can be created. In this paradigm a structure is first declared as a pointer (which may be given an initial value of `NULL`) before being fully allocated a structure later in the app's initialization. Therefore one of the most common problems that can arise is that of the developer attempting to use an unallocated structure or data item. For example, the following code segment will cause a crash: ```c Window *main_window; static void init() { // Attempting to push an uninitialized Window! window_stack_push(main_window, true); } ``` The compiler will not report this, but when run the app will crash before the ``Window`` can be displayed, with an error message sent to the console output along the following lines: ```nc|text [INFO ] E ault_handling.c:77 App fault! {f23aecb8-bdb5-4d6b-b270-602a1940575e} PC: 0x8016716 LR: 0x8016713 [WARNING ] Program Counter (PC): 0x8016716 ??? [WARNING ] Link Register (LR): 0x8016713 ??? ``` When possible, the pebble tool will tell the developer the PC (Program Counter, or which statement is currently being executed) and LR (Link Register, address to return to when the current function scope ends) addresses and line numbers at the time of the crash, which may help indicate the source of the problem. This problem can be fixed by ensuring that any data structures declared as pointers are properly allocated using the appropriate `_create()` SDK functions before they are used as arguments: ```c Window *main_window; static void init(void) { main_window = window_create(); window_stack_push(main_window, true); } ``` In situations where available heap space is limited, `_create()` functions may return `NULL`, and the object will not be allocated. Apps can detect this situation as follows: ```c Window *main_window; static void init(void) { main_window = window_create(); if(main_window != NULL) { // Allocation was successful! window_stack_push(main_window, true); } else { // The Window could not be allocated! // Tell the user that the operation could not be completed text_layer_set_text(s_output_layer, "Unable to use this feature at the moment."); } } ``` This `NULL` pointer error can also occur to any dynamically allocated structure or variable of the developer's own creation outside the SDK. For example, a typical dynamically allocated array will cause a crash if it is used before it is allocated: ```c char *array; // Array is still NULL! array[0] = 'a'; ``` This problem can be fixed in a similar manner as before by making sure the array is properly allocated before it is used: ```c char *array = (char*)malloc(8 * sizeof(char)); array[0] = 'a'; ``` As mentioned above for ``window_create()``, be sure also check the [return value](http://pubs.opengroup.org/onlinepubs/009695399/functions/malloc.html) of `malloc()` to determine whether the memory allocation requested was completed successfully: ```c array = (char*)malloc(8 * sizeof(char)); // Check the malloc() was successful if(array != NULL) { array[0] = 'a'; } else { // Gracefully handle the failed situation } ``` ## Outside Array Bounds Another problem that can look OK to the compiler, but cause an error at runtime is improper use of arrays, such as attempting to access an array index outside the array's bounds. This can occur when a loop is set up to iterate through an array, but the size of the array is reduced or the loop conditions change. For example, the array iteration below will not cause a crash, but includes the use of 'magic numbers' that can make a program brittle and prone to errors when these numbers change: ```c int *array; static void init(void) { array = (int*)malloc(8 * sizeof(int)); for(int i = 0; i < 8; i++) { array[i] = i * i; } } ``` If the size of the allocated array is reduced, the app will crash when the iterative loop goes outside the array bounds: ```c int *array; static void init(void) { array = (int*)malloc(4 * sizeof(int)); for(int i = 0; i < 8; i++) { array[i] = i * i; // Crash when i == 4! } } ``` Since the number of loop iterations is linked to the size of the array, this problem can be avoided by defining the size of the array in advance in one place, and then using that value everywhere the size of the array is needed: ```c #define ARRAY_SIZE 4 int *array; static void init(void) { array = (int*)malloc(ARRAY_SIZE * sizeof(int)); for(int i = 0; i < ARRAY_SIZE; i++) { array[i] = i * i; } } ``` An alternative solution to the above is to use either the `ARRAY_LENGTH()` macro or the `sizeof()` function to programmatically determine the size of the array to be looped over.
{ "source": "google/pebble", "title": "devsite/source/_guides/debugging/common-runtime-errors.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/debugging/common-runtime-errors.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 7157 }
--- # Copyright 2025 Google LLC # # 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. title: Common Syntax Errors description: | Details of common problems encountered when writing C apps for Pebble, and how to resolve them. guide_group: debugging order: 2 --- If a developer is relatively new to writing Pebble apps (or new to the C language in general), there may be times when problems with an app's code will cause compilation errors. Some types of errors with the code itself can be detected by the compiler and this helps reduce the number that cause problems when the code is run on Pebble. These are problems with how app code is written, as opposed to runtime errors (discussed in {% guide_link debugging/common-runtime-errors %}), which may include breaking the rules of the C language or bad practices that the compiler is able to detect and show as an error. The following are some examples. ### Undeclared Variables This error means that a variable that has been referenced is not available in the current scope. ```nc|text ../src/main.c: In function 'toggle_logging': ../src/main.c:33:6: error: 'is_now_logging' undeclared (first use in this function) if(is_now_logging == true) { ^ ``` In the above example, the symbol `is_now_logging` has been used in the `toggle_logging` function, but it was not first declared there. This could be because the declaring line has been deleted, or it was expected to be available globally, but isn't. To fix this, consider where else the symbol is required. If it is needed in other functions, move the declaration to a global scope (outside any function). If it is needed only for this function, declare it before the offending line (here line `33`). ### Undeclared Functions Another variant of the above problem can occur when declaring new functions in a code file. Due to the nature of C compilation, any function a developer attempts to call must have been previously encountered by the compiler in order to be visible. This can be done through [forward declaration](http://en.wikipedia.org/wiki/Forward_declaration). For example, the code segment below will not compile: ```c static void window_load(Window *window) { my_function(); } void my_function() { // Some code here } ``` The compiler will report this with an 'implicit declaration' error, as the app has implied the function's existence by calling it, even though the compiler has not seen it previously: ```nc|text ../src/function-visibility.c: In function 'window_load': ../src/function-visibility.c:6:3: error: implicit declaration of function 'my_function' [-Werror=implicit-function-declaration] my_function(); ^ ``` This is because the *declaration* of `my_function()` occurs after it is called in `window_load()`. There are two options to fix this. * Move the function declaration above any calls to it, so it has been encountered by the compiler: ```c void my_function() { // Some code here } static void window_load(Window *window) { my_function(); } ``` * Declare the function by prototype before it is called, and provide the implementation later: ```c void my_function(); static void window_load(Window *window) { my_function(); } void my_function() { // Some code here } ``` ### Too Few Arguments When creating functions with argument lists, sometimes the requirements of the function change and the developer forgets to update the places where it is called. ```nc|text ../src/main.c: In function 'select_click_handler': ../src/main.c:57:3: error: too few arguments to function 'toggle_logging' toggle_logging(); ^ ../src/main.c:32:13: note: declared here static void toggle_logging(bool will_log) { ^ ``` The example above reports that the app tried to call the `toggle_logging()` function in `select_click_handler()` on line 57, but did not supply enough arguments. The argument list expected in the function definition is shown in the second part of the output message, which here exists on line 32 and expects an extra value of type `bool`. To fix this, establish which version of the function is required, and update either the calls or the declaration to match. ### Incorrect Callback Implementations In the Pebble SDK there are many instances where the developer must implement a function signature required for callbacks, such as for a ``WindowHandlers`` object. This means that when implementing the handler the developer-defined callback must match the return type and argument list specified in the API documentation. For example, the ``WindowHandler`` callback (used for the `load` and `unload` events in a ``Window``'s lifecycle) has the following signature: ```c typedef void(* WindowHandler)(struct Window *window) ``` This specifies a return type of `void` and a single argument: a pointer of type ``Window``. Therefore the implemented callback should look like this: ```c void window_load(Window *window) { } ``` If the developer does not specify the correct return type and argument list in their callback implementation, the compiler will let them know with an error like the following, stating that the type of function passed by the developer does not match that which is expected: ```nc|text ../src/main.c: In function 'init': ../src/main.c:82:5: error: initialization from incompatible pointer type [-Werror] .load = main_window_load, ^ ../src/main.c:82:5: error: (near initialization for '(anonymous).load') [-Werror] ``` To fix this, double check that the implementation provided has the same return type and argument list as specified in the API documentation.
{ "source": "google/pebble", "title": "devsite/source/_guides/debugging/common-syntax-errors.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/debugging/common-syntax-errors.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 6121 }
--- # Copyright 2025 Google LLC # # 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. title: Debugging with App Logs description: | How to use the app logs to debug problems with an app, as well as tips on interpreting common run time errors. guide_group: debugging order: 1 related_docs: - Logging platform_choice: true --- When apps in development do not behave as expected the developer can use app logs to find out what is going wrong. The C SDK and PebbleKit JS can both output messages and values to the console to allow developers to get realtime information on the state of their app. This guide describes how to log information from both the C and JS parts of a watchapp or watchface and also how to read that information for debugging purposes. ## Logging in C The C SDK includes the ``APP_LOG()`` macro function which allows an app to log a string containing information to the console: ```c static int s_buffer[5]; for(int i = 0; i < 10; i++) { // Store loop value in array s_buffer[i] = i; APP_LOG(APP_LOG_LEVEL_DEBUG, "Loop index now %d", i); } ``` This will result in the following output before crashing: ```nc|text [INFO ] D main.c:20 Loop index now 0 [INFO ] D main.c:20 Loop index now 1 [INFO ] D main.c:20 Loop index now 2 [INFO ] D main.c:20 Loop index now 3 [INFO ] D main.c:20 Loop index now 4 ``` In this way it will be possible to tell the state of the loop index value if the app encounters a problem and crashes (such as going out of array bounds in the above example). ## Logging in JS Information can be logged in PebbleKit JS and Pebble.js using the standard JavaScript console, which will then be passed on to the log output view. An example of this is to use the optional callbacks when using `Pebble.sendAppMessage()` to know if a message was sent successfully to the watch: ```js console.log('Sending data to Pebble...'); Pebble.sendAppMessage({'KEY': value}, function(e) { console.log('Send successful!'); }, function(e) { console.log('Send FAILED!'); } ); ``` ## Viewing Log Data When viewing app logs, both the C and JS files' output are shown in the same view. ^CP^ To view app logs in CloudPebble, open a project and navigate to the 'Compilation' screen. Click 'View App Logs' and run an app that includes log output calls to see the output appear in this view. ^LC^ The `pebble` {% guide_link tools-and-resources/pebble-tool %} will output any logs from C and JS files after executing the `pebble logs` command and supplying the phone's IP address: <div class="platform-specific" data-sdk-platform="local"> {% markdown %} ```text pebble logs --phone=192.168.1.25 ``` > Note: You can also use `pebble install --logs' to combine both of these > operations into one command. {% endmarkdown %} </div> ## Memory Usage Information In addition to the log output from developer apps, statistics about memory usage are also included in the C app logs when an app exits: ```nc|text [INFO] process_manager.c:289: Heap Usage for App compass-ex: Total Size <22980B> Used <164B> Still allocated <0B> ``` This piece of information reports the total heap size of the app, the amount of memory allocated as a result of execution, and the amount of memory still allocated when it exited. This last number can alert any forgotten deallocations (for example, forgetting ``window_destroy()`` after ``window_create()``). A small number such as `28B` is acceptable, provided it remains the same after subsequent executions. If it increases after each app exit it may indicate a memory leak. For more information on system memory usage, checkout the [Size presentation from the 2014 Developer Retreat](https://www.youtube.com/watch?v=8tOhdUXcSkw). ## Avoid Excessive Logging As noted in the [API documentation](``Logging``), logging over Bluetooth can be a power-hungry operation if an end user has the Developer Connection enabled and is currently viewing app logs. In addition, frequent (multiple times per second) logging can interfere with frequent use of ``AppMessage``, as the two mechanisms share the same channel for communication. If an app is logging sent/received AppMessage events or values while doing this sending, it could experience slow or dropped messages. Be sure to disable this logging when frequently sending messages.
{ "source": "google/pebble", "title": "devsite/source/_guides/debugging/debugging-with-app-logs.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/debugging/debugging-with-app-logs.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 4822 }
--- # Copyright 2025 Google LLC # # 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. title: Debugging with GDB description: | How to use GDB to debug a Pebble app in the emulator. guide_group: debugging order: 0 --- As of SDK 3.10 (and [Pebble Tool](/guides/tools-and-resources/pebble-tool) 4.2), developers can use the powerful [GDB](https://www.gnu.org/software/gdb/) debugging tool to find and fix errors in Pebble apps while they are running in an emulator. GDB allows the user to observe the state of the app at any point in time, including the value of global and local variables, as well as current function parameters and a backtrace. Strategically placing breakpoints and observing these values can quickly reveal the source of a bug. {% alert notice %} GDB cannot be used to debug an app running on a real watch. {% endalert %} ## Starting GDB To begin using GDB, start an emulator and install an app: ```text $ pebble install --emulator basalt ``` Once the app is installed, begin using GDB: ```text $ pebble gdb --emulator basalt ``` Once the `(gdb)` prompt appears, the app is paused by GDB for observation. To resume execution, use the `continue` (or `c`) command. Similarly, the app can be paused for debugging by pressing `control + c`. ```text (gdb) c Continuing. ``` A short list of useful commands (many more are available) can be also be obtained from the `pebble` tool. Read the [*Emulator Interaction*](/guides/tools-and-resources/pebble-tool/#gdb) section of the {% guide_link tools-and-resources/pebble-tool %} guide for more details on this list. ```text $ pebble gdb --help ``` ## Observing App State To see the value of variables and parameters at any point, set a breakpoint by using the `break` (or `b`) command and specifying either a function name, or file name with a line number. For example, the snippet below shows a typical ``TickHandler`` implementation with line numbers in comments: ```c /* 58 */ static void tick_handler(struct tm *tick_time, TimeUnits changed) { /* 59 */ int hours = tick_time->tm_hour; /* 60 */ int mins = tick_time->tm_min; /* 61 */ /* 62 */ if(hours < 10) { /* 63 */ /* other code */ /* 64 */ } /* 65 */ } ``` To observe the values of `hours` and `mins`, a breakpoint is set in this file at line 61: ```text (gdb) b main.c:61 Breakpoint 2 at 0x200204d6: file ../src/main.c, line 61. ``` > Use `info break` to see a list of all breakpoints currently registered. Each > can be deleted with `delete n`, where `n` is the breakpoint number. With this breakpoint set, use the `c` command to let the app continue until it encounters the breakpoint: ```text $ c Continuing. ``` When execution arrives at the breakpoint, the next line will be displayed along with the state of the function's parameters: ```text Breakpoint 2, tick_handler (tick_time=0x20018770, units_changed=(SECOND_UNIT | MINUTE_UNIT)) at ../src/main.c:62 62 if(hours < 10) { ``` The value of `hours` and `mins` can be found using the `info locals` command: ```text (gdb) info locals hours = 13 mins = 23 ``` GDB can be further used here to view the state of variables using the `p` command, such as other parts of the `tm` object beyond those being used to assign values to `hours` and `mins`. For example, the day of the month: ```text (gdb) p tick_time->tm_mday $2 = 14 ``` A backtrace can be generated that describes the series of function calls that got the app to the breakpoint using the `bt` command: ```text (gdb) bt #0 segment_logic (this=0x200218a0) at ../src/drawable/segment.c:18 #1 0x2002033c in digit_logic (this=0x20021858) at ../src/drawable/digit.c:141 #2 0x200204c4 in pge_logic () at ../src/main.c:29 #3 0x2002101a in draw_frame_update_proc (layer=<optimized out>, ctx=<optimized out>) at ../src/pge/pge.c:190 #4 0x0802627c in ?? () #5 0x0805ecaa in ?? () #6 0x0801e1a6 in ?? () #7 0x0801e24c in app_event_loop () #8 0x2002108a in main () at ../src/pge/pge.c:34 #9 0x080079de in ?? () #10 0x00000000 in ?? () ``` > Lines that include '??' denote a function call in the firmware. Building the > app with `pebble build --debug` will disable some optimizations and can > produce more readable output from GDB. However, this can increase code size > which may break apps that are pushing the heap space limit. ## Fixing a Crash When an app is paused for debugging, the developer can manually advance each statement and precisely follow the path taken through the code and observe how the state of each variable changes over time. This is very useful for tracking down bugs caused by unusual input to functions that do not adequately check them. For example, a `NULL` pointer. The app code below demonstrates a common cause of an app crash, caused by a misunderstanding of how the ``Window`` stack works. The ``TextLayer`` is created in the `.load` handler, but this is not called until the ``Window`` is pushed onto the stack. The attempt to set the time to the ``TextLayer`` by calling `update_time()` before it is displayed will cause the app to crash. ```c #include <pebble.h> static Window *s_window; static TextLayer *s_time_layer; static void window_load(Window *window) { Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_bounds(window_layer); s_time_layer = text_layer_create(bounds); text_layer_set_text(s_time_layer, "00:00"); text_layer_set_text_alignment(s_time_layer, GTextAlignmentCenter); layer_add_child(window_layer, text_layer_get_layer(s_time_layer)); } static void update_time() { time_t now = time(NULL); struct tm *tick_time = localtime(&now); static char s_buffer[8]; strftime(s_buffer, sizeof(s_buffer), "%H:%M", tick_time); text_layer_set_text(s_time_layer, s_buffer); } static void init() { s_window = window_create(); window_set_window_handlers(s_window, (WindowHandlers) { .load = window_load }); update_time(); window_stack_push(s_window, true); } static void deinit() { window_destroy(s_window); } int main() { init(); app_event_loop(); deinit(); } ``` Supposing the cause of this crash was not obvious from the order of execution, GDB can be used to identify the cause of the crash with ease. It is known that the app crashes on launch, so the first breakpoint is placed at the beginning of `init()`. After continuing execution, the app will pause at this location: ```text (gdb) b init Breakpoint 2 at 0x2002010c: file ../src/main.c, line 26. (gdb) c Continuing. Breakpoint 2, main () at ../src/main.c:41 41 init(); ``` Using the `step` command (or Enter key), the developer can step through all the statements that occur during app initialization until the crash is found (and the `app_crashed` breakpoint is encountered. Alternatively, `bt full` can be used after the crash occurs to inspect the local variables at the time of the crash: ```text (gdb) c Continuing. Breakpoint 1, 0x0804af6c in app_crashed () (gdb) bt full #0 0x0804af6c in app_crashed () No symbol table info available. #1 0x0800bfe2 in ?? () No symbol table info available. #2 0x0800c078 in ?? () No symbol table info available. #3 0x0804c306 in ?? () No symbol table info available. #4 0x080104f0 in ?? () No symbol table info available. #5 0x0804c5c0 in ?? () No symbol table info available. #6 0x0805e6ea in text_layer_set_text () No symbol table info available. #7 0x20020168 in update_time () at ../src/main.c:22 now = 2076 tick_time = <optimized out> s_buffer = "10:38\000\000" #8 init () at ../src/main.c:31 No locals. #9 main () at ../src/main.c:41 No locals. #10 0x080079de in ?? () No symbol table info available. #11 0x00000000 in ?? () No symbol table info available. ``` The last statement to be executed before the crash is a call to `text_layer_set_text()`, which implies that one of its input variables was bad. It is easy to determine which by printing local variable values with the `p` command: ```text Breakpoint 4, update_time () at ../src/main.c:22 22 text_layer_set_text(s_time_layer, s_buffer); (gdb) p s_time_layer $1 = (TextLayer *) 0x0 <__pbl_app_info> ``` In this case, GDB displays `0x0` (`NULL`) for the value of `s_time_layer`, which shows it has not yet been allocated, and so will cause `text_layer_set_text()` to crash. And thus, the source of the crash has been methodically identified. A simple fix here is to swap `update_time()` and ``window_stack_push()`` around so that `init()` now becomes: ```c static void init() { // Create a Window s_window = window_create(); window_set_window_handlers(s_window, (WindowHandlers) { .load = window_load }); // Display the Window window_stack_push(s_window, true); // Set the time update_time(); } ``` In this new version of the code the ``Window`` will be pushed onto the stack, calling its `.load` handler in the process, and the ``TextLayer`` will be allocated and available for use once execution subsequently reaches `update_time()`.
{ "source": "google/pebble", "title": "devsite/source/_guides/debugging/debugging-with-gdb.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/debugging/debugging-with-gdb.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 9482 }
--- # Copyright 2025 Google LLC # # 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. title: Debugging description: | How to find and fix common compilation and runtime problems in apps. guide_group: debugging permalink: /guides/debugging/ menu: false generate_toc: false related_docs: - Logging hide_comments: true --- When writing apps, everyone makes mistakes. Sometimes a simple typo or omission can lead to all kinds of mysterious behavior or crashes. The guides in this section are aimed at trying to help developers identify and fix a variety of issues that can arise when writing C code (compile-time) or running the compiled app on Pebble (runtime). There are also a few strategies outlined here, such as app logging and other features of the `pebble` {% guide_link tools-and-resources/pebble-tool %} that can indicate the source of a problem in the vast majority of cases. ## Contents {% include guides/contents-group.md group=page.group_data %}
{ "source": "google/pebble", "title": "devsite/source/_guides/debugging/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/debugging/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 1457 }
--- # Copyright 2025 Google LLC # # 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. title: Benefits of Design Guidelines description: | Learn the main concepts of design guidelines, why they are needed, and how they can help developers. guide_group: design-and-interaction menu: true permalink: /guides/design-and-interaction/benefits/ generate_toc: true order: 0 --- ## What are Design Guidelines? Design guidelines are a set of concepts and rules used to create an app's user interface. These define how the layout on-screen at any one time should be used to maximize the efficiency of presenting data to the user, as well as quickly informing them how to choose their next action. An app creator may look to other popular apps to determine how they have helped their users understand their app's purpose, either through the use of iconography or text highlighting. They may then want to use that inspiration to enable users of the inspiring app to easily use their own app. If many apps use the same visual cues, then future users will already be trained in their use when they discover them. ## What are Interaction Patterns? Similar to design guidelines, interaction patterns define how to implement app interactivity to maximize its efficiency. If a user can predict how the app will behave when they take a certain action, or be able to determine which action fits that which they want to achieve without experimentation, then an intuitive and rewarding experience will result. In addition to purely physical actions such as button presses and accelerometer gestures, the virtual navigation flow should also be considered at the design stage. It should be intuitive for the user to move around the app screens to access the information or execute the commands as they would expect on a first guess. An easy way to achieve this is to use a menu with the items clearly labelling their associated actions. An alternative is to use explicit icons to inform the user implicitly of their purpose without needing to label them all. ## Why are They Needed? Design guidelines and interaction patterns exist to help the developer help the user by ensuring user interface consistency across applications on the platform. It is often the case that the developer will have no problem operating their own watchapp because they have been intimately familiar with how it is supposed to work since its inception. When such an app is given to users, they may receive large amounts of feedback from confused users who feel they do not know if an app supports the functionality they though it did, or even how to find it. By considering a novice user from the beginning of the UI design and implementation, this problem can be avoided. A Pebble watchapp experience is at its best when it can be launched, used for its purpose in the smallest amount of time, and then closed back to the watchface. If the user must spend a long time navigating the app's UI to get to the information they want, or the information takes a while to arrive on every launch, the app efficiency suffers. To avoid this problem, techniques such as implementing a list of the most commonly used options in an app (according to the user or the whole user base) to aid fast navigation, or caching remotely fetched data which may still be relevant from the last update will improve the user experience. From an interaction pattern point of view, a complex layout filled with abstract icons may confuse a first-time user as to what each of them represents. Apps can mitigate this problem by using icons that have pre-established meanings across languages, such as the 'Play/Pause' icon or the 'Power' icon, seen on many forms of devices. ## What Are the Benefits? The main benefits of creating and following design guidelines and common interaction patterns are summarized as follows: * User interface consistency, which breeds familiarity and predictability. * Clarity towards which data is most important and hence visible and usable. * Reduced user confusion and frustration, leading to improved perception of apps. * No need to include explicit usage instructions in every app to explain how it must be used. * Apps that derive design from the system apps can benefit from any learned behavior all Pebble users may develop in using their watches out the box. * Clearer, more efficient and better looking apps! ## Using Existing Affordances Developers can use concepts and interaction patterns already employed in system apps and popular 3rd party apps to lend those affordances to your own apps. An example of this in mobile apps is the common 'swipe down to refresh' action. By using this action in their app, many mobile app makers can benefit from users who have already been trained to perform this action, and can free up their app's UI for a cleaner look, or use the space that would have been used by a 'refresh' button to add an additional feature. In a similar vein, knowing that the Back button always exits the current ``Window`` in a Pebble app, a user does not have to worry about knowing how to navigate out of it. Similarly, developers do not have to repeatedly implement exiting an app, as this action is a single, commonly understood pattern - just press the Back button! On the other hand, if a developer overrides this action a user may be confused or frustrated when the app fails to exit as they would expect, and this could mean a negative opinion that could have been avoided. ## What's Next? Read {% guide_link design-and-interaction/core-experience %} to learn how design guidelines helped shape the core Pebble system experience.
{ "source": "google/pebble", "title": "devsite/source/_guides/design-and-interaction/benefits.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/design-and-interaction/benefits.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 6148 }
--- # Copyright 2025 Google LLC # # 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. title: Core Experience Design description: | How design guidelines shape the core Pebble app experience. guide_group: design-and-interaction menu: true permalink: /guides/design-and-interaction/core-experience/ generate_toc: true order: 1 --- The core Pebble experience includes several built-in system apps that use repeatable design and interaction concepts in their implementation. These are: * Apps are designed with a single purpose in mind, and they do it well. * Fast animations are used to draw attention to changing or updating information. * Larger, bolder fonts to highlight important data. * A preference for displaying multiple data items in a paginated format rather than many 'menus within menus'. This is called the 'card' pattern and is detail in {% guide_link design-and-interaction/recommended#display-data-sets-using-cards "Display Data Sets Using Cards" %}. * Colors are used to enhance the app's look and feel, and are small in number. Colors are also sometimes used to indicate state, such as the temperature in a weather app, or to differentiate between different areas of a layout. ## System Experience Design The core system design and navigation model is a simple metaphor for time on the user's wrist - a linear representation of the past, present, and future. The first two are presented using the timeline design, with a press of the Up button displaying past events (also known as pins), and a press of the Down button displaying future events. As was the case for previous versions of the system experience, pressing the Select button opens the app menu. This contains the system apps, such as Music and Notifications, as well as all the 3rd party apps the user has installed in their locker. ![system-navigation](/images/guides/design-and-interaction/system-navigation.png) Evidence of the concepts outlined above in action can be seen within the core system apps in firmware 3.x. These are described in detail in the sections below. ### Music ![music](/images/guides/design-and-interaction/music.png) The Music app is designed with a singular purpose in mind - display the current song and allow control over playback. To achieve this, the majority of the screen space is devoted to the most important data such as the song title and artist. The remainder of the space is largely used to display the most immediate controls for ease of interaction in an action bar UI element. The 'previous track' and 'next track' icons on the action bar are ones with pre-existing affordances which do not require specific instruction for new users thanks to their universal usaging other media applications. The use of the '...' icon is used as an additional commonly understood action to indicate more functionality is available. By single-pressing this action, the available actions change from preview/next to volume up/volume down, reverting on a timeout. This is preferable to a long-press, which is typically harder to discover without an additional prompt included in the UI. A press of the Back button returns the user to the appface menu, where the Music appface displays the name and artist of the currently playing track, in a scrolling 'marquee' manner. If no music is playing, no information is shown here. ### Notifications ![notifications](/images/guides/design-and-interaction/notifications.png) The system Notifications app allows a user to access all their past received notifications in one place. Due to the fact that the number of notifications received can be either small or large, the main view of the app is implemented as a menu, with each item showing each notification's icon, title and the first line of the body content. In this way it is easy for a user to quickly scroll down the list and identify the notification they are looking for based on these first hints. The first item in the menu is a 'Clear All' option, which when selected prompts the user to confirm this action using a dialog. This dialog uses the action bar component to give the user the opportunity to confirm this action with the Select button, or to cancel it with the Back button. Once the desired item has been found, a press of the Select button opens a more detailed view, where the complete notification content can be read, scrolling down if needed. The fact that there is more content available to view is hinted at using the arrow marker and overlapping region at the bottom of the layout. ### Alarms ![alarms](/images/guides/design-and-interaction/alarms.png) The Alarms app is the most complex of the system apps, with multiple screens dedicated to input collection from the user. Like the Watchfaces and Music apps, the appface in the system menu shows the time of the next upcoming scheduled alarm, if any. Also in keeping with other system apps, the main screen is presented using a menu, with each item representing a scheduled alarm. Each alarm is treated as a separate item, containing different settings and values. A press of the Select button on an existing item will open the action menu containing a list of possible actions, such as 'Delete' or 'Disable'. Pressing Select on the top item ('+') will add a new item to the list, using multiple subsequent screens to collect data about the alarm the user wishes to schedule. Using multiple screens avoids the need for one screen to contain a lot of input components and clutter up the display. In the time selection screen, the current selection is marked using a green highlight. The Up and Down buttons are used to increase and decrease the currently selected field respectively. Once a time and recurring frequency has been chosen by the user, the new alarm is added to the main menu list. The default state is enabled, marked by the word 'ON' to the right hand side, but can be disabled in which case 'OFF' is displayed instead. ### Watchfaces ![watchfaces](/images/guides/design-and-interaction/watchfaces.png) The Watchfaces system app is similar to the Notifications app, in that it uses a menu as its primary means of navigation. Each watchface available in the user's locker is shown as a menu item, with a menu icon if one has been included by the watchface developer. The currently active watchface is indicated by the presence of 'Active' as that item's subtitle. Once the user has selected a new watchface, they are shown a confirmation dialog to let them know their choice was successful. If the watchface is not currently loaded on the watch, a progress bar is shown briefly while the data is loaded. Once this is done the newly chosen watchface is displayed. ### Settings ![settings](/images/guides/design-and-interaction/settings.png) The Settings app uses the system appface to display the date, the battery charge level, and the Bluetooth connection without the need to open the app proper. If the user does open the app, they are greeted with a menu allowing a choice of settings category. This approach saves the need for a single long list of settings that would require a lot of scrolling. Once a category has been chosen, the app displays another menu filled with interactive menu rows that change various settings. Each item shows the name of the setting in bold as the item title, with the current state of the setting shown as the subtitle. When the user presses Select, the state of the currently selected setting is changed, usually in a binary rotation of On -> Off states. If the setting does not operate with a binary state (two states), or has more than two options, an action menu window is displayed with the available actions, allowing the user to select one with the Select button. A press of the Back button from a category screen returns the user to the category list, where they can make another selection, or press Back again to return to the app menu. ### Sports API {% screenshot_viewer %} { "image": "/images/guides/design-and-interaction/sports.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} The Sports API app is designed around displaying the most immediate relevant data of a particular sporting activity, such as running or cycling. A suitable Android or iOS companion app pushes data to this app using the {% guide_link communication/using-the-sports-api "PebbleKit Sports API" %} at regular intervals. This API enables third-party sports app developers to easily add support for Pebble without needing to create and maintain their own watchapp. The high contrast choice of colors makes the information easy to read at a glance in a wide variety of lighting conditions, ideal for use in outdoor activities. The action bar is also used to present the main action available to the user - the easily recognizable 'pause' action to suspend the current activity for a break. This is replaced by the equally recognizable 'play' icon, the action now used to resume the activity. This API also contains a separate Golf app for PebbleKit-compatible apps to utilize in tracking the user's golf game. {% screenshot_viewer %} { "image": "/images/guides/design-and-interaction/golf.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} The Golf app uses a similar design style with larger fonts for important numbers in the center of the layout, with the action bar reserved for additional input, such as moving between holes. Being an app that is intended to be in use for long periods of time, the status bar is used to display the current time for quick reference without needing to exit back to the watchface. ## Timeline Experience Design Evidence of guided design can also be found in other aspects of the system, most noticeably the timeline view. With pins containing possibly a large variety of types of information, it is important to display a view which caters for as many types as possible. As detailed in {% guide_link pebble-timeline/pin-structure "Creating Pins" %}, pins can be shown in two different ways; the event time, icon and title on two lines or a single line, depending on how the user is currently navigating the timeline. When a pin is highlighted, as much information is shown to the user as possible. ![timeline](/images/guides/design-and-interaction/timeline.png) Users access the timeline view using Up and Down buttons from the watchface to go into the past and future respectively. The navigation of the timeline also uses animations for moving elements that gives life to the user interface, and elements such as moving the pin icon between windows add cohesion between the different screens. A press of the Select button opens the pin to display all the information it contains, and is only one click away. A further press of the Select button opens the pin's action menu, containing a list of all the actions a user may take. These actions are directly related to the pin, and can be specified when it is created. The system provides two default actions: 'Remove' to remove the pin from the user's timeline, and 'Mute [Name]' to mute all future pins from that source. This gives the user control over which pins they see in their personal timeline. Mute actions can be reversed later in the mobile app's 'Apps/Timeline' screen. ## What's Next? Read {% guide_link design-and-interaction/recommended %} for tips on creating an intuitive app experience.
{ "source": "google/pebble", "title": "devsite/source/_guides/design-and-interaction/core-experience.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/design-and-interaction/core-experience.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 12181 }
--- # Copyright 2025 Google LLC # # 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. title: Example Implementations description: | Resources and code samples to implement common design and UI patterns. guide_group: design-and-interaction menu: true permalink: /guides/design-and-interaction/implementation/ generate_toc: true order: 4 --- This guide contains resources and links to code examples that may help developers implement UI designs and interaction patterns recommended in the other guides in this section. ## UI Components and Patterns Developers can make use of the many UI components available in SDK 3.x in combination with the {% guide_link design-and-interaction/recommended#common-design-styles "Common Design Styles" %} to ensure the user experience is consistent and intuitive. The following components and patterns are used in the Pebble experience, and listed in the table below. Some are components available for developers to use in the SDK, or are example implementations designed for adaptation and re-use. | Pattern | Screenshot | Description | |---------|------------|-------------| | [`Menu Layer`](``MenuLayer``) | ![](/images/guides/design-and-interaction/menulayer.png) | Show many items in a list, allow scrolling between them, and choose an option. | | [`Status Bar`](``StatusBarLayer``) | ![](/images/guides/design-and-interaction/alarm-list~basalt.png) | Display the time at the top of the Window, optionally extended with additional data. | | [`Radio Button List`]({{site.links.examples_org}}/ui-patterns/blob/master/src/windows/radio_button_window.c) | ![](/images/guides/design-and-interaction/radio-button.png) | Allow the user to specify one choice out of a list. | | [`Checkbox List`]({{site.links.examples_org}}/ui-patterns/blob/master/src/windows/checkbox_window.c) | ![](/images/guides/design-and-interaction/checkbox-list.png) | Allow the user to choose multiple different options from a list. | | [`List Message`]({{site.links.examples_org}}/ui-patterns/blob/master/src/windows/list_message_window.c) | ![](/images/guides/design-and-interaction/list-message.png) | Provide a hint to help the user choose from a list of options. | | [`Message Dialog`]({{site.links.examples_org}}/ui-patterns/blob/master/src/windows/dialog_message_window.c) | ![](/images/guides/design-and-interaction/dialog-message.gif) | Show an important message using a bold fullscreen alert. | | [`Choice Dialog`]({{site.links.examples_org}}/ui-patterns/blob/master/src/windows/dialog_choice_window.c) | ![](/images/guides/design-and-interaction/dialog-choice-patterns.png) | Present the user with an important choice, using the action bar and icons to speed up decision making. | | [`PIN Entry`]({{site.links.examples_org}}/ui-patterns/blob/master/src/windows/pin_window.c) | ![](/images/guides/design-and-interaction/pin.png) | Enable the user to input integer data. | | [`Text Animation`]({{site.links.examples_org}}/ui-patterns/blob/master/src/windows/text_animation_window.c) | ![](/images/guides/design-and-interaction/text-change-anim.gif) | Example animation to highlight a change in a text field. | | [`Progress Bar`]({{site.links.examples_org}}/ui-patterns/blob/master/src/windows/progress_bar_window.c) | ![](/images/guides/design-and-interaction/progress-bar.gif) | Example progress bar implementation on top of a ``StatusBarLayer``. | | [`Progress Layer`]({{site.links.examples_org}}/ui-patterns/blob/master/src/windows/progress_layer_window.c) | ![](/images/guides/design-and-interaction/progresslayer.gif) | Example implementation of the system progress bar layer. | ## Example Apps Developers can look at existing apps to begin to design (or improve) their user interface and interaction design. Many of these apps can be found on the appstore with links to their source code, and can be used as inspiration. ### Cards Example (Weather) The weather [`cards-example`]({{site.links.examples_org}}/cards-example) embodies the 'card' design pattern. Consisting of a single layout, it displays all the crucial weather-related data in summary without the need for further layers of navigation. Instead, the buttons are reserved for scrolling between whole sets of data pertaining to different cities. The number of 'cards' is shown in the top-right hand corner to let the user know that there is more data present to be scrolled through, using the pre-existing Up and Down button action affordances the user has already learned. This helps avoid implementing a novel navigation pattern, which saves time for both the user and the developer. ![weather >{pebble-screenshot,pebble-screenshot--time-red}](/images/guides/design-and-interaction/weather.gif) When the user presses the appropriate buttons to scroll through sets of data, the changing information is animated with fast, snappy, and highly visible animations to reinforce the idea of old data moving out of the layout and being physically replaced by new data.
{ "source": "google/pebble", "title": "devsite/source/_guides/design-and-interaction/implementation.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/design-and-interaction/implementation.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 5453 }
--- # Copyright 2025 Google LLC # # 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. title: Round App Design description: | Tips and advice for designing apps that take advantage of the Pebble Time Round display guide_group: design-and-interaction menu: true permalink: /guides/design-and-interaction/in-the-round/ generate_toc: true order: 3 --- > This guide is about designing round apps. For advice on implementing a round > design in code, read {% guide_link user-interfaces/round-app-ui %}. With the release of the Chalk [platform](/faqs#pebble-sdk), developers must take new features and limitations into account when designing their apps. New and existing apps that successfully adapt their layout and colors for both Aplite and Basalt should also endeavor to do so for the Chalk platform. ## Minor Margins The Pebble Time Round display requires a small two pixel border on each edge, to compensate for the bezel design. To this end, it is highly encouraged to allow for this in an app's design. This may involve stretching a background color to all outer edges, or making sure that readable information cannot be displayed in this margin, or else it may not be visible. Avoid thin rings around the edge of the display, even after accounting for the two pixel margin as manufacturing variations may cause them to be visibly off-center. Instead use thick rings, or inset them significantly from the edge of the screen. ## Center of Attention With the round Chalk display, apps no longer have the traditional constant amount of horizontal space available. This particularly affects the use of the ``MenuLayer``. To compensate for this, menus are now always centered on the highlighted item. Use this to display additional information in the cell with the most space available, while showing reduced content previews in the unhighlighted cells. ![centered >{pebble-screenshot,pebble-screenshot--time-round-silver-20}](/images/guides/design-and-interaction/center-layout~chalk.png) Menus built using the standard cell drawing functions will automatically adopt this behavior. If performing custom cell drawing, new APIs are available to help implement this behavior. For more information, look at the ``Graphics`` documentation, as well as the ``menu_layer_set_center_focused()`` and ``menu_layer_is_index_selected()`` to help with conditional drawing. ## Pagination Another key concept to bear in mind when designing for a round display is text flow. In traditional Pebble apps, text in ``ScrollLayer`` or ``TextLayer`` elements could be freely moved and scrolled with per-pixel increments without issue. However, with a round display each row of text can have a different width, depending on its vertical position. If such text was reflowed while moving smoothly down the window, the layout would reflow so often the text would be very difficult to read. ![center-layout >{pebble-screenshot,pebble-screenshot--time-round-silver-20}](/images/guides/design-and-interaction/scrolling-with-text-flow.gif) The solution to this problem is to scroll through text in pages, a technique known as pagination. By moving through the text in discrete sections, the text is only reflowed once per 'page', and remains easily readable as the user is navigating through it. The ``ScrollLayer`` has been updated to implement this on Chalk. To inform the user that more content is available, the Chalk platform allows use of the ``ContentIndicator`` UI component. This facilitates the display of two arrows at the top and bottom of the display, similar to those seen in the system UI. ![content-indicator >{pebble-screenshot,pebble-screenshot--time-round-silver-20}](/images/guides/design-and-interaction/content-indicator.png) A ``ContentIndicator`` can be created from scratch and manually managed to determine when the arrows should be shown, or a built-in instance can be obtained from a ``ScrollLayer``. ## Platform-Specific Designs Sometimes a design that made sense on a rectangular display does not make sense on a circular one, or could be improved. Be open to creating a new UI for the Chalk platform, and selecting which to use based on the display shape. For example, in the screenshot below the linear track display was incompatible with the round display and center-focused menus, leading to a completely different design on Chalk that shows the same information. {% screenshot_viewer %} { "image": "/images/guides/design-and-interaction/caltrain-stops.png", "platforms": [ {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} ## What's Next? Read {% guide_link design-and-interaction/implementation %} to learn how to use and implement the UI components and patterns encouraged in SDK 3.x apps.
{ "source": "google/pebble", "title": "devsite/source/_guides/design-and-interaction/in-the-round.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/design-and-interaction/in-the-round.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 5308 }
--- # Copyright 2025 Google LLC # # 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. title: Design and Interaction description: | How to design apps to maximise engagement, satisfaction, efficiency and overall user experience. guide_group: design-and-interaction menu: false permalink: /guides/design-and-interaction/ generate_toc: false hide_comments: true --- Interaction guides are intended to help developers design their apps to maximize user experience through effective, consistent visual design and user interactions on the Pebble platform. Readers can be non-programmers and programmers alike: All material is explained conceptually and no code must be understood. For code examples, see {% guide_link design-and-interaction/implementation %}. By designing apps using a commonly understood and easy to understand visual language users can get the best experience with the minimum amount of effort expended - learning how they work, how to operate them or what other behavior is required. This can help boost how efficiently any given app is used as well as help reinforce the underlying patterns for similar apps. For example, the layout design should make it immediately obvious which part of the UI contains the vital information the user should glance at first. In addition to consistent visual design, implementing a common interaction pattern helps an app respond to users as they would expect. This allows them to correctly predict how an app will respond to their input without having to experiment to find out. To get a feel for how to approach good UI design for smaller devices, read other examples of developer design guidelines such as Google's [Material Design](http://www.google.com/design/spec/material-design/introduction.html) page or Apple's [iOS Human Interface Guidelines](https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/). ## Contents {% include guides/contents-group.md group=page.group_data %}
{ "source": "google/pebble", "title": "devsite/source/_guides/design-and-interaction/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/design-and-interaction/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 2476 }
--- # Copyright 2025 Google LLC # # 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. title: One Click Actions description: | Details about how to create One Click Action watchapps guide_group: design-and-interaction menu: true order: 2 related_docs: - AppExitReason - AppGlanceSlice - AppMessage related_examples: - title: One Click Action Example url: https://github.com/pebble-examples/one-click-action-example --- One click actions are set to revolutionize the way users interact with their Pebble by providing instant access to their favorite one click watchapps, directly from the new system launcher. Want to unlock your front door? Call an Uber? Or perhaps take an instant voice note? With one click actions, the user is able to instantly perform a single action by launching an app, and taking no further action. ![Lockitron >{pebble-screenshot,pebble-screenshot--time-black}](/images/guides/design-and-interaction/lockitron.png) ### The One Click Flow It’s important to develop your one click application with a simple and elegant flow. You need to simplify the process of your application by essentially creating an application which serves a single purpose. The typical flow for a one click application would be as follows: 1. Application is launched 2. Application performs action 3. Application displays status to user 4. Application automatically exits to watchface if the action was successful, or displays status message and does not exit if the action failed If we were creating an instant voice note watchapp, the flow could be as follows: 1. Application launched 2. Application performs action (take a voice note) 1. Start listening for dictation 2. Accept dictation response 3. Application displays a success message 4. Exit to watchface In the case of a one click application for something like Uber, we would need to track the state of any existing booking to prevent ordering a second car. We would also want to update the ``App Glance`` as the status of the booking changes. 1. Application launched 2. If a booking exists: 1. Refresh booking status 2. Update ``App Glance`` with new status 3. Exit to watchface 3. Application performs action (create a booking) 1. Update AppGlance: “Your Uber is on it’s way” 2. Application displays a success message 3. Exit to watchface ### Building a One Click Application For this example, we’re going to build a one click watchapp which will lock or unlock the front door of our virtual house. We’re going to use a virtual [Lockitron](https://lockitron.com/), or a real one if you’re lucky enough to have one. Our flow will be incredibly simple: 1. Launch the application 2. Take an action (toggle the state of the lock) 3. Update the ``App Glance`` to indicate the new lock state 4. Display a success message 5. Exit to watchface For the sake of simplicity in our example, we will not know if someone else has locked or unlocked the door using a different application. You can investigate the [Lockitron API](http://api.lockitron.com) if you want to develop this idea further. In order to control our Lockitron, we need the UUID of the lock and an access key. You can generate your own virtual lockitron UUID and access code on the [Lockitron website](https://api.lockitron.com/v1/getting_started/virtual_locks). ```c #define LOCKITRON_LOCK_UUID "95c22a11-4c9e-4420-adf0-11f1b36575f2" #define LOCKITRON_ACCESS_TOKEN "99e75a775fe737bb716caf88f161460bb623d283c3561c833480f0834335668b" ``` > Never publish your actual Lockitron access token in the appstore, unless you want strangers unlocking your door! Ideally you would make these fields configurable using [Clay for Pebble](https://github.com/pebble/clay). We’re going to need a simple enum for the state of our lock, where 0 is unlocked, 1 is locked and anything else is unknown. ```c typedef enum { LOCKITRON_UNLOCKED, LOCKITRON_LOCKED, LOCKITRON_UNKNOWN } LockitronLockState; ``` We’re also going to use a static variable to keep track of the state of our lock. ```c static LockitronLockState s_lockitron_state; ``` When our application launches, we’re going to initialize ``AppMessage`` and then wait for PebbleKit JS to tell us it’s ready. ```c static void prv_init(void) { app_message_register_inbox_received(prv_inbox_received_handler); app_message_open(256, 256); s_window = window_create(); window_stack_push(s_window, false); } static void prv_inbox_received_handler(DictionaryIterator *iter, void *context) { Tuple *ready_tuple = dict_find(iter, MESSAGE_KEY_APP_READY); if (ready_tuple) { // PebbleKit JS is ready, toggle the Lockitron! prv_lockitron_toggle_state(); return; } // ... } ``` In order to toggle the state of the Lockitron, we’re going to send an ``AppMessage`` to PebbleKit JS, containing our UUID and our access key. ```c static void prv_lockitron_toggle_state() { DictionaryIterator *out; AppMessageResult result = app_message_outbox_begin(&out); dict_write_cstring(out, MESSAGE_KEY_LOCK_UUID, LOCKITRON_LOCK_UUID); dict_write_cstring(out, MESSAGE_KEY_ACCESS_TOKEN, LOCKITRON_ACCESS_TOKEN); result = app_message_outbox_send(); } ``` PebbleKit JS will handle this request and make the relevant ajax request to the Lockitron API. It will then return the current state of the lock and tell our application to exit back to the default watchface using ``AppExitReason``. See the [full example](https://github.com/pebble-examples/one-click-action-example) for the actual Javascript implementation. ```c static void prv_inbox_received_handler(DictionaryIterator *iter, void *context) { // ... Tuple *lock_state_tuple = dict_find(iter, MESSAGE_KEY_LOCK_STATE); if (lock_state_tuple) { // Lockitron state has changed s_lockitron_state = (LockitronLockState)lock_state_tuple->value->int32; // App will exit to default watchface app_exit_reason_set(APP_EXIT_ACTION_PERFORMED_SUCCESSFULLY); // Exit the application by unloading the only window window_stack_remove(s_window, false); } } ``` Before our application terminates, we need to update the ``App Glance`` with the current state of our lock. We do this by passing our current lock state into the ``app_glance_reload`` method. ```c static void prv_deinit(void) { window_destroy(s_window); // Before the application terminates, setup the AppGlance app_glance_reload(prv_update_app_glance, &s_lockitron_state); } ``` We only need a single ``AppGlanceSlice`` for our ``App Glance``, but it’s worth noting you can have multiple slices with varying expiration times. ```c static void prv_update_app_glance(AppGlanceReloadSession *session, size_t limit, void *context) { // Check we haven't exceeded system limit of AppGlances if (limit < 1) return; // Retrieve the current Lockitron state from context LockitronLockState *lockitron_state = context; // Generate a friendly message for the current Lockitron state char *str = prv_lockitron_status_message(lockitron_state); APP_LOG(APP_LOG_LEVEL_INFO, "STATE: %s", str); // Create the AppGlanceSlice (no icon, no expiry) const AppGlanceSlice entry = (AppGlanceSlice) { .layout = { .template_string = str }, .expiration_time = time(NULL)+3600 }; // Add the slice, and check the result const AppGlanceResult result = app_glance_add_slice(session, entry); if (result != APP_GLANCE_RESULT_SUCCESS) { APP_LOG(APP_LOG_LEVEL_ERROR, "AppGlance Error: %d", result); } } ``` ### Handling Launch Reasons In the example above, we successfully created an application that will automatically execute our One Click Action when the application is launched. But we also need to be aware of some additional launch reasons where it would not be appropriate to perform the action. By using the ``launch_reason()`` method, we can detect why our application was started and prevent the One Click Action from firing unnecessarily. A common example, would be to detect if the application was actually started by the user, from either the launcher, or quick launch. ```c if(launch_reason() == APP_LAUNCH_USER || launch_reason() == APP_LAUNCH_QUICK_LAUNCH) { // Perform One Click } else { // Display a message } ``` ### Conclusion As you can see, it’s a relatively small amount of code to create one click watchapps and we hope this inspires you to build your own! We recommend that you check out the complete [Lockitron sample](https://github.com/pebble-examples/one-click-action-example) application and also the ``App Glance`` and ``AppExitReason`` guides for further information.
{ "source": "google/pebble", "title": "devsite/source/_guides/design-and-interaction/one-click-actions.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/design-and-interaction/one-click-actions.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 9098 }
--- # Copyright 2025 Google LLC # # 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. title: Recommended Guidelines and Patterns description: | Pebble's recommended guidelines for creating awesome app experiences. guide_group: design-and-interaction menu: true permalink: /guides/design-and-interaction/recommended/ generate_toc: true order: 2 --- This page contains recommendations for things to consider when designing an app's visual styles and interaction patterns. The aim here is to encourage efficiency through optional conformity to common ideas and concepts, and to breed a consistent experience for users across apps. Developers can also find suggested interface styles to use when building the navigation of apps to best display the information contained within. ## Tips for UI Design To achieve an effective, clear, and intuitive design developers should: * Keep layouts **simple**, with only as much information displayed as is **immediately required**. This encourages quick usage of the app, distracting the user for the minimal amount of time necessary for the app to achieve its goals. * Give priority to the **most commonly used/main purpose** functionality of the app in the UI. Make it easy to use the biggest features, but still easy to find additional functionality that would otherwise be hidden. * Use **larger fonts** to highlight the **most important data** to be read at a glance. Consider font size 28 for larger items, and a minimum of 18 for smaller ones. * Take advantage of colors to convey additional **information without any text** if they are already associated as such, such as green for a task complete. * Try to avoid any colors used in places they may have a **pre-conceived meaning** which does not apply, such as red text when there are no errors. * Use animations to embody the layout with **character** and flourish, as well as to **draw the eye** to updated or changing information. * Ensure the UI gives **direct feedback** to the user's input, or else they may think their button presses are having no effect. ## Tips for UI Interaction * Avoid using the Pebble buttons for actions **not** already associated with them, unless clearly marked in the UI using an ``ActionBarLayer`` or similar method. When using the Up and Down buttons for 'previous item' and 'next item' respectively, there may be no need for a visual cue. * Use iconography with **pre-existing visual associations** (such as a 'stop' icon) to take advantage of the inherent behavior the user will have when seeing it. This can avoid the need for explicit instructions to train the user for an app's special case. * Ensure the navigation between app ``Window``s is **logical** with the input given and the information displayed. For example, an app showing bus timetables should use higher level screens for quickly navigating to a particular area/station, with lower level views reserved for scrolling through the actual timetable data. * If possible, **preserve the state of the app** and/or previous navigation if the app is commonly used for a repetitive task. In the bus timetable example, the user may only look up two stations for a to-from work journey. Learn this behavior and store it with the [Persistent Storage API](``Storage``) to intelligently adapt the UI on subsequent launches to show the relevant information. This helps the user avoid navigating through multiple menus every time they launch the app. ## Common Design Styles The following are common design styles that have been successfully used in system and 3rd party apps, and are recommended for use in the correct manner. ### Display Data Sets Using Cards ![card >{pebble-screenshot,pebble-screenshot--time-red}](/images/guides/design-and-interaction/card.gif) The 'card' style aims to reduce the number of menu levels needed to access as much relevant information as possible. Instead of a menu to select a data set leading to a menu to explore each item in that set, a single ``Window`` is designed that displays an entire data set. This view then uses the Pebble Up and Down buttons to scroll through complete data sets in an array of many sets. An example of this is the {% guide_link design-and-interaction/implementation#cards-example-weather "cards-example" %} example app, which displays all weather data in a single view and pages through sets of data for separate locations with the Up and Down buttons. This style of UI design allows access to lots of information without navigating through several menus to view it. ### List Options with a Menu {% screenshot_viewer %} { "image": "/images/guides/design-and-interaction/list.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} The style is one of the most basic, tried and true styles. Using the ``MenuLayer`` UI component, the user may choose between multiple app functions by scrolling with the Up and Down buttons, an interaction pattern afforded to the developer by the core system experience. Using a menu, a user can navigate straight to the part of the app or specific action they want. ### Execute Actions with an ActionBarLayer {% screenshot_viewer %} { "image": "/images/guides/design-and-interaction/actionbar.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} The ``ActionBarLayer`` allows easy association of app functionality with the Pebble buttons. By setting icons to each of the three positions, a user can see which actions they can perform at a glance and execture them with a single button press. When pressed, the icon is animated to provide immediate visual feedback. An example of this is the system Music app, that uses the ``ActionBarLayer`` to inform the user that the Up and Down buttons skip tracks. In this case, the Select button is displayed with elipses, indicating further actions are available. A press of this button changes the set of actions on the Up and Down buttons, enabling them to modify the playback volume instead. A collection of icons for common actions is available for use by developers, and can be found in the {% guide_link app-resources/app-assets %} guide. ### Allow Extended Options with an Action Menu ![actionmenu](/images/guides/design-and-interaction/actionmenu.png) If an app screen demands a larger range of available actions than the ``ActionBarLayer`` will allow, present these as a list that slides into view with a press of the Select button using an action menu. This menu contains all the available options, and can contain multiple sub-menus, providing levels. The user can keep track of which level they are currently looking at using the breadcrumb dots on the left-hand side of the screen when the action menu is displayed. Once an action has been chosen, the user should be informed of the success or failure of their choice using a new alert dialog window. In the system action menus, these screens use an eye-catching animation and bold label to convey the result of the action. This feedback is important to prevent the user from getting frustrated if they perceive their input has no result, as well as to reassure them that their action has succeeded without a problem. ### Get User Input with a Form ![list](/images/guides/design-and-interaction/alarm-list-config.png) Apps such as the system Alarm app make use of a list of configurable items, with each active alarm treated as a menu item with properties. The status of each item is displayed in a menu, with the Select button initiating configuration of that item. When an item is being configured, the data requried to create the item should be obtained from the user through the use of a form, with manipulable elements. In the Alarms example, each integer required to schedule an alarm is obtained with a number field that can have its value incrememted or decremented using the intuitive Up and Down buttons. The current form element is highlighted with color, and advancing to the next element is done with the Select button, doubling as a 'Confirm' action when the end of the form is reached. ### Prompting User Action on the Phone In some applications, user input is required in the app's configuration page (as detailed in {% guide_link user-interfaces/app-configuration %}) before the app can perform its task. An example of this is a feed reader app, that will need the user to input the URL of their preferred news feed before it can fetch the feed content. In this case, the watchapp should display a prominent (full- screen if possible) dialog telling the user that input to the phone app for configuration is required. ![action-required >{pebble-screenshot,pebble-screenshot--time-red}](/images/guides/design-and-interaction/action-required.png) Once the user has performed the required action on the phone, the [`webviewclosed`](/guides/communication/using-pebblekit-js/) event should signify that the app can proceed, and that the required data is now available. It should not be the case that this action is required every time the app is started. In most cases, the input data from the user can be stored with [Peristent Storage](``Storage``) on the watch, or [`localStorage`](/guides/communication/using-pebblekit-js/) on the phone. If the app must get input on every launch (such as a mode selection), this should be done through a form or menu on the watch, so as to avoid needing to use the phone. ### Show Time and Other Data with the Status Bar {% screenshot_viewer %} { "image": "/images/guides/design-and-interaction/alarm-list.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} Under SDK 2.x, the status bar was displayed to users in all menus and watchapps except watchfaces, or where the developer had explicitly disabled it. This was useful for showing the time and battery level, but arguably not essential all the time. In SDK 3.x, only apps that are designed to be running for extended periods of time (such as Music and the Sports API app) show the time, using the ``StatusBarLayer`` UI component. The battery level can easily be seen from the Settings appface, and so it not necessary to be always visible. Another instance where the status bar is neccessary is in the Alarms app (shown above), where the user may need to compare with the current time when setting an alarm. If a constant, minimalistic display of app data is required, the ``StatusBarLayer`` can be used to perform this task. It provides a choice of separator mode and foreground/background colors, and can also be made transparent. Since is it just another ``Layer``, it can be easily extended with additional text, icons, or other data. For example, the [`cards-example`]({{site.links.examples_org}}/cards-example) app uses an extention of the status bar to display the currently selected 'card' (a set of displayed data). Another example is the progress bar component example from the [`ui-patterns`]({{site.links.examples_org}}/ui-patterns) app, which builds upon the dotted separator mode to become a thin progress bar. When used in conjunction with the ``ActionBarLayer`` (for example, in the Music system app), the width of the underlying layer should be adjusted such that the time displayed is shown in the new center of the app area (excluding that taken up by the action bar itself). ### Show Alerts and Get Decisions with Modal Windows ![dialog-message >{pebble-screenshot,pebble-screenshot--time-red}](/images/guides/design-and-interaction/dialog-message.gif) When a significant event occurs while using an app, it should be made visible to the user through the use of a full-screen model dialog. In a similar way that notifications and reminders alert the user to events, these layouts consist of only the important information and an associated icon telling the user the source of the alert, or the reason for its occurrence. This pattern should also be used to quickly and efficently tell the user that an app-related error has occured, including steps on how to fix any potential problems. These alerts can also take the form of requests for important decisions to be made by the user, such as to remember a choice as the default preference: {% screenshot_viewer %} { "image": "/images/guides/design-and-interaction/dialog-choice-window.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} In this way the decision can be passed to the user with an immediately obvious and actionable set of choices. One the choice has been made, the modal window is dismissed, and a confirmation of the choice displayed. The user should then be returned to the previous window to resume their use of the app where they left off. ### Using Vibrations and Haptic Feedback The Pebble SDK allows the use of the vibration motor to deliver haptic feedback to the user. This can take the form of short, long, double pulses or more detailed vibration sequences, allowing a lot of customization as well as variation between apps. To encourage a consistent experience for users, the ``Vibes`` API should be used with the following points in mind: * A short pulse should be used to alert the user to the end of a long-running in-app event, such as a download completing, preferably when they are not looking at the watch. * A long pulse should be used to alert the user to a failure or error that requires attention and some interaction. * Custom vibration patterns should be used to allow the user to customize haptic feedback for different events inside the app. When the app is open and being actively interacted with no vibration or haptic feedback should be neccessary on top of the existing visual feedback. However, some exceptions may occur, such as for visually-impaired users. In these cases haptic feedback may be very useful in boosting app accessibility. ### Handling Connection Problems When a watchapp is running, there is no guarantee that the phone connection will be available at any one time. Most apps will function without this connection, but if PebbleKit JS, Android, or iOS is required, the user must be informed of the reason for failure so that they can correct the problem. This check can be performed at any time using ``connection_service_peek_pebble_app_connection()``. An example alert layout is shown below. {% screenshot_viewer %} { "image": "/images/guides/design-and-interaction/no-bt-connection.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} A similar situation arises if an app that requires information or responses from a remote web service attempts to do so, but the phone has no Internet connection. This may be because the user has opted to disable their data connections, or they may be out of range. Another example alert layout is shown below for this situation. {% screenshot_viewer %} { "image": "/images/guides/design-and-interaction/no-inet-connection.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} If these kinds of situations can cause problems for the operation of the app, consider using the [`Persistent Storage`](``Storage``) API to cache the most recently loaded data (such as weather, sports scores or news items) from the last successful launch, and display this to the user (while making them aware of the data's age) until new data can be obtained. ### Hiding Timeline-only Apps Watchapps that consist only of a {% guide_link pebble-timeline "Pebble timeline" %} experience will only need to be launched when configured by the user to select topic subscriptions. In these cases, developers should hide their app from the launcher menu to prevent the user needlessly launching it. To find out how to do this using the `hiddenApp` property, see {% guide_link tools-and-resources/app-metadata %}. ## Consistent App Configuration Watchapps and watchfaces that include user configuration normally include a web page hosted by the app developer, allowing the user to choose from a set of options and apply them to the app. Such options include aesthetic options such as color schemes, larger font sizes, replacement images, data source choices, and others. Traditionally the design of these pages has been left entirely to the developer on a per-app basis, and this is reflected in the resulting design consistency. Read {% guide_link user-interfaces/app-configuration %} to learn more about configuration page design and implementation. ## What's Next? Read {% guide_link design-and-interaction/in-the-round %} to read tips and guidance on designing apps that work well on a round display.
{ "source": "google/pebble", "title": "devsite/source/_guides/design-and-interaction/recommended.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/design-and-interaction/recommended.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 17918 }
--- # Copyright 2025 Google LLC # # 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. title: Accelerometer description: | How to use data and simple tap gestures from the onboard accelerometer. guide_group: events-and-services order: 0 related_docs: - AccelerometerService related_examples: - title: Feature Accel Discs url: https://github.com/pebble-examples/feature-accel-discs --- The acceleromter sensor is included in every Pebble watch, and allows collection of acceleration and orientation data in watchapps and watchfaces. Data is available in two ways, each suitable to different types of watchapp: * Taps events - Fires an event whenever a significant tap or shake of the watch occurs. Useful to 'shake to view' features. * Data batches - Allows collection of data in batches at specific intervals. Useful for general accelerometer data colleciton. As a significant source of regular callbacks, the accelerometer should be used as sparingly as possible to allow the watch to sleep and conserve power. For example, receiving data in batches once per second is more power efficient than receiving a single sample 25 times per second. ## About the Pebble Accelerometer The Pebble accelerometer is oriented according to the diagram below, showing the direction of each of the x, y, and z axes. ![accel-axes](/images/guides/pebble-apps/sensors/accel.png) In the API, each axis value contained in an ``AccelData`` sample is measured in milli-Gs. The accelerometer is calibrated to measure a maximum acceleration of ±4G. Therefore, the range of possible values for each axis is -4000 to +4000. The ``AccelData`` sample object also contains a `did_vibrate` field, set to `true` if the vibration motor was active during the sample collection. This could possibly contaminate those samples due to onboard vibration, so they should be discarded. Lastly, the `timestamp` field allows tracking of obtained accelerometer data over time. ## Using Taps Adding a subscription to tap events allows a developer to react to any time the watch is tapped or experiences a shake along one of three axes. Tap events are received by registering an ``AccelTapHandler`` function, such as the one below: ```c static void accel_tap_handler(AccelAxisType axis, int32_t direction) { // A tap event occured } ``` The `axis` parameter describes which axis the tap was detected along. The `direction` parameter is set to `1` for the positive direction, and `-1` for the negative direction. A subscription can be added or removed at any time. While subscribed, `accel_tap_handler` will be called whenever a tap event is fired by the accelerometer. Adding a subscription is simple: ```c // Subscribe to tap events accel_tap_service_subscribe(accel_tap_handler); ``` ```c // Unsubscribe from tap events accel_tap_service_unsubscribe(); ``` ## Using Data Batches Accelerometer data can be received in batches at a chosen sampling rate by subscribing to the Accelerometer Data Service at any time: ```c uint32_t num_samples = 3; // Number of samples per batch/callback // Subscribe to batched data events accel_data_service_subscribe(num_samples, accel_data_handler); ``` The ``AccelDataHandler`` function (called `accel_data_handler` in the example above) is called when a new batch of data is ready for consumption by the watchapp. The rate at which these occur is dictated by two things: * The sampling rate - The number of samples the accelerometer device measures per second. One value chosen from the ``AccelSamplingRate`` `enum`. * The number of samples per batch. Some simple math will determine how often the callback will occur. For example, at the ``ACCEL_SAMPLING_50HZ`` sampling rate, and specifying 10 samples per batch will result in five calls per second. When an event occurs, the acceleromater data can be read from the ``AccelData`` pointer provided in the callback. An example reading the first set of values is shown below: ```c static void accel_data_handler(AccelData *data, uint32_t num_samples) { // Read sample 0's x, y, and z values int16_t x = data[0].x; int16_t y = data[0].y; int16_t z = data[0].z; // Determine if the sample occured during vibration, and when it occured bool did_vibrate = data[0].did_vibrate; uint64_t timestamp = data[0].timestamp; if(!did_vibrate) { // Print it out APP_LOG(APP_LOG_LEVEL_INFO, "t: %llu, x: %d, y: %d, z: %d", timestamp, x, y, z); } else { // Discard with a warning APP_LOG(APP_LOG_LEVEL_WARNING, "Vibration occured during collection"); } } ``` The code above will output the first sample in each batch to app logs, which will look similar to the following: ```nc|text [15:33:18] -data-service.c:21> t: 1449012797098, x: -111, y: -280, z: -1153 [15:33:18] -data-service.c:21> t: 1449012797305, x: -77, y: 40, z: -1014 [15:33:18] -data-service.c:21> t: 1449012797507, x: -60, y: 4, z: -1080 [15:33:19] -data-service.c:21> t: 1449012797710, x: -119, y: -55, z: -921 [15:33:19] -data-service.c:21> t: 1449012797914, x: 628, y: 64, z: -506 ```
{ "source": "google/pebble", "title": "devsite/source/_guides/events-and-services/accelerometer.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/events-and-services/accelerometer.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 5617 }
--- # Copyright 2025 Google LLC # # 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. title: Background Worker description: | Using the Background Worker to do work in the background, such as activity tracking. guide_group: events-and-services order: 1 related_docs: - Worker related_examples: - title: Background Counter url: https://github.com/pebble-examples/feature-background-counter - title: Background Worker Communication url: https://github.com/pebble-examples/feature-worker-message platform_choice: true --- In addition to the main foreground task that every Pebble app implements, a second background worker task can also be created. This worker is capable of running even when the foreground task is closed, and is useful for tasks that must continue for long periods of time. For example, apps that log sensor data. There are several important points to note about the capabilities of this worker when compared to those of the foreground task: * The worker is constrained to 10.5 kB of memory. * Some APIs are not available to the worker. See the [*Available APIs*](#available-apis) section below for more information. * There can only be one background worker active at a time. In the event that a second one attempts to launch from another watchapp, the user will be asked to choose whether the new worker can replace the existing one. * The user can determine which app's worker is running by checking the 'Background App' section of the Settings menu. Workers can also be launched from there. * The worker can launch the foreground app using ``worker_launch_app()``. This means that the foreground app should be prepared to be launched at any time that the worker is running. > Note: This API should not be used to build background timers; use the > ``Wakeup`` API instead. ## Adding a Worker ^CP^ The background worker's behavior is determined by code written in a separate C file to the foreground app. Add a new source file and set the 'Target' field to 'Background Worker'. ^LC^ The background worker's behavior is determined by code written in a separate C file to the foreground app, created in the `/worker_src` project directory. <div class="platform-specific" data-sdk-platform="local"> {% markdown %} This project structure can also be generated using the [`pebble` tool](/guides/tools-and-resources/pebble-tool/) with the `--worker` flag as shown below: ```bash $ pebble new-project --worker project_name ``` {% endmarkdown %} </div> The worker C file itself has a basic structure similar to a regular Pebble app, but with a couple of minor changes, as shown below: ```c #include <pebble_worker.h> static void prv_init() { // Initialize the worker here } static void prv_deinit() { // Deinitialize the worker here } int main(void) { prv_init(); worker_event_loop(); prv_deinit(); } ``` ## Launching the Worker To launch the worker from the foreground app, use ``app_worker_launch()``: ```c // Launch the background worker AppWorkerResult result = app_worker_launch(); ``` The ``AppWorkerResult`` returned will indicate any errors encountered as a result of attempting to launch the worker. Possible result values include: | Result | Value | Description | |--------|-------|:------------| | ``APP_WORKER_RESULT_SUCCESS`` | `0` | The worker launch was successful, but may not start running immediately. Use ``app_worker_is_running()`` to determine when the worker has started running. | | ``APP_WORKER_RESULT_NO_WORKER`` | `1` | No worker found for the current app. | | ``APP_WORKER_RESULT_ALREADY_RUNNING`` | `4` | The worker is already running. | | ``APP_WORKER_RESULT_ASKING_CONFIRMATION`` | `5` | The user will be asked for confirmation. To determine whether the worker was given permission to launch, use ``app_worker_is_running()`` for a short period after receiving this result. | ## Communicating Between Tasks There are three methods of passing data between the foreground and background worker tasks: * Save the data using the ``Storage`` API, then read it in the other task. * Send the data to a companion phone app using the ``DataLogging`` API. Details on how to do this are available in {% guide_link communication/datalogging %}. * Pass the data directly while the other task is running, using an ``AppWorkerMessage``. These messages can be sent bi-directionally by creating an `AppWorkerMessageHandler` in each task. The handler will fire in both the foreground and the background tasks, so you must identify the source of the message using the `type` parameter. ```c // Used to identify the source of a message #define SOURCE_FOREGROUND 0 #define SOURCE_BACKGROUND 1 ``` **Foreground App** ```c static int s_some_value = 1; static int s_another_value = 2; static void worker_message_handler(uint16_t type, AppWorkerMessage *message) { if(type == SOURCE_BACKGROUND) { // Get the data, only if it was sent from the background s_some_value = message->data0; s_another_value = message->data1; } } // Subscribe to get AppWorkerMessages app_worker_message_subscribe(worker_message_handler); // Construct a message to send AppWorkerMessage message = { .data0 = s_some_value, .data1 = s_another_value }; // Send the data to the background app app_worker_send_message(SOURCE_FOREGROUND, &message); ``` **Worker** ```c static int s_some_value = 3; static int s_another_value = 4; // Construct a message to send AppWorkerMessage message = { .data0 = s_some_value, .data1 = s_another_value }; static void worker_message_handler(uint16_t type, AppWorkerMessage *message) { if(type == SOURCE_FOREGROUND) { // Get the data, if it was sent from the foreground s_some_value = message->data0; s_another_value = message->data1; } } // Subscribe to get AppWorkerMessages app_worker_message_subscribe(worker_message_handler); // Send the data to the foreground app app_worker_send_message(SOURCE_BACKGROUND, &message); ``` ## Managing the Worker The current running state of the background worker can be determined using the ``app_worker_is_running()`` function: ```c // Check to see if the worker is currently active bool running = app_worker_is_running(); ``` The user can tell whether the worker is running by checking the system 'Background App' settings. Any installed workers with be listed there. The worker can be stopped using ``app_worker_kill()``: ```c // Stop the background worker AppWorkerResult result = app_worker_kill(); ``` Possible `result` values when attempting to kill the worker are as follows: | Result | Value | Description | |--------|-------|:------------| | ``APP_WORKER_RESULT_SUCCESS`` | `0` | The worker launch was killed successfully. | | ``APP_WORKER_RESULT_DIFFERENT_APP`` | `2` | A worker from a different app is running, and cannot be killed by this app. | | ``APP_WORKER_RESULT_NOT_RUNNING`` | `3` | The worker is not currently running. | ## Available APIs Background workers do not have access to the UI APIs. They also cannot use the ``AppMessage`` API or load resources. Most other APIs are available including (but not limited to) ``AccelerometerService``, ``CompassService``, ``DataLogging``, ``HealthService``, ``ConnectionService``, ``BatteryStateService``, ``TickTimerService`` and ``Storage``. ^LC^ The compiler will throw an error if the developer attempts to use an API unsupported by the worker. For a definitive list of available APIs, check `pebble_worker.h` in the SDK bundle for the presence of the desired API. ^CP^ CloudPebble users will be notified by the editor and compiler if they attempt to use an unavailable API.
{ "source": "google/pebble", "title": "devsite/source/_guides/events-and-services/background-worker.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/events-and-services/background-worker.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 8420 }
--- # Copyright 2025 Google LLC # # 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. title: Buttons description: | How to react to button presses in your app. guide_group: events-and-services order: 2 related_docs: - Clicks - ClickHandler related_examples: - title: App Font Browser url: https://github.com/pebble-examples/app-font-browser/blob/master/src/app_font_browser.c#L168 --- Button [`Clicks`](``Clicks``) are the primary input method on Pebble. All Pebble watches come with the same buttons available, shown in the diagram below for Pebble Time: ![button-layout](/images/guides/sensors-and-input/button-layout.png) These buttons are used in a logical fashion throughout the system: * Back - Navigates back one ``Window`` until the watchface is reached. * Up - Navigates to the previous item in a list, or opens the past timeline when pressed from the watchface. * Select - Opens the app launcher from the watchface, accepts a selected option or list item, or launches the next ``Window``. * Down - Navigates to the next item in a list, or opens the future timeline when pressed from the watchface. Developers are highly encouraged to follow these patterns when using button clicks in their watchapps, since users will already have an idea of what each button will do to a reasonable degree, thus avoiding the need for lengthy usage instructions for each app. Watchapps that wish to use each button for a specific action should use the ``ActionBarLayer`` or ``ActionMenu`` to give hints about what each button will do. ## Listening for Button Clicks Button clicks are received via a subscription to one of the types of button click events listed below. Each ``Window`` that wishes to receive button click events must provide a ``ClickConfigProvider`` that performs these subscriptions. The first step is to create the ``ClickConfigProvider`` function: ```c static void click_config_provider(void *context) { // Subcribe to button click events here } ``` The second step is to register the ``ClickConfigProvider`` with the current ``Window``, typically after ``window_create()``: ```c // Use this provider to add button click subscriptions window_set_click_config_provider(window, click_config_provider); ``` The final step is to write a ``ClickHandler`` function for each different type of event subscription required by the watchapp. An example for a single click event is shown below: ```c static void select_click_handler(ClickRecognizerRef recognizer, void *context) { // A single click has just occured } ``` ## Types of Click Events There are five types of button click events that apps subscribe to, enabling virtually any combination of up/down/click events to be utilized in a watchapp. The usage of each of these is explained below: ### Single Clicks Most apps will use this type of click event, which occurs whenever the button specified is pressed and then immediately released. Use ``window_single_click_subscribe()`` from a ``ClickConfigProvider`` function, supplying the ``ButtonId`` value for the chosen button and the name of the ``ClickHandler`` that will receive the events: ```c static void click_config_provider(void *context) { ButtonId id = BUTTON_ID_SELECT; // The Select button window_single_click_subscribe(id, select_click_handler); } ``` ### Single Repeating Clicks Similar to the single click event, the single repeating click event allows repeating events to be received at a specific interval if the chosen button is held down for a longer period of time. This makes the task of scrolling through many list items or incrementing a value significantly easier for the user, and uses fewer button clicks. ```c static void click_config_provider(void *context) { ButtonId id = BUTTON_ID_DOWN; // The Down button uint16_t repeat_interval_ms = 200; // Fire every 200 ms while held down window_single_repeating_click_subscribe(id, repeat_interval_ms, down_repeating_click_handler); } ``` After an initial press (but not release) of the button `id` subscribed to, the callback will be called repeatedly with an interval of `repeat_interval_ms` until it is then released. Developers can determine if the button is still held down after the first callback by using ``click_recognizer_is_repeating()``, as well as get the number of callbacks counted so far with ``click_number_of_clicks_counted()``: ```c static void down_repeating_click_handler(ClickRecognizerRef recognizer, void *context) { // Is the button still held down? bool is_repeating = click_recognizer_is_repeating(recognizer); // How many callbacks have been recorded so far? uint8_t click_count = click_number_of_clicks_counted(recognizer); } ``` > Single click and single repeating click subscriptions conflict, and cannot be > registered for the same button. ### Multiple Clicks A multi click event will call the ``ClickHandler`` after a specified number of single clicks has been recorded. A good example of usage is to detect a double or triple click gesture: ```c static void click_config_provider(void *context) { ButtonId id = BUTTON_ID_SELECT; // The Select button uint8_t min_clicks = 2; // Fire after at least two clicks uint8_t max_clicks = 3; // Don't fire after three clicks uint16_t timeout = 300; // Wait 300ms before firing bool last_click_only = true; // Fire only after the last click window_multi_click_subscribe(id, min_clicks, max_clicks, timeout, last_click_only, multi_select_click_handler); } ``` Similar to the single repeating click event, the ``ClickRecognizerRef`` can be used to determine how many clicks triggered this multi click event using ``click_number_of_clicks_counted()``. ### Long Clicks A long click event is fired after a button is held down for the specified amount of time. The event also allows two ``ClickHandler``s to be registered - one for when the button is pressed, and another for when the button is released. Only one of these is required. ```c static void click_config_provider(void *context) { ButtonId id = BUTTON_ID_SELECT; // The select button uint16_t delay_ms = 500; // Minimum time pressed to fire window_long_click_subscribe(id, delay_ms, long_down_click_handler, long_up_click_handler); } ``` ### Raw Clicks The last type of button click subcsription is used to track raw button click events. Like the long click event, two ``ClickHandler``s may be supplied to receive each of the pressed and depressed events. ```c static void click_config_provider(void *context) { ButtonId id = BUTTON_ID_SELECT; // The select button window_raw_click_subscribe(id, raw_down_click_handler, raw_up_click_handler, NULL); } ``` > The last parameter is an optional pointer to a context object to be passed to > the callback, and is set to `NULL` if not used.
{ "source": "google/pebble", "title": "devsite/source/_guides/events-and-services/buttons.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/events-and-services/buttons.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 7623 }
--- # Copyright 2025 Google LLC # # 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. title: Compass description: | How to use data from the Compass API to determine direction. guide_group: events-and-services order: 3 related_docs: - CompassService related_examples: - title: Feature Compass url: https://github.com/pebble-examples/feature-compass - title: Official Compass Watchapp url: https://github.com/pebble-hacks/pebble-compass --- The ``CompassService`` combines data from Pebble's accelerometer and magnetometer to automatically calibrate the compass and produce a ``CompassHeading``, containing an angle measured relative to magnetic north. The compass service provides magnetic north and information about its status and accuracy through the ``CompassHeadingData`` structure. ## Calibration The compass service requires an initial calibration before it can return accurate results. Calibration is performed automatically by the system when first required. The [`compass_status`](``CompassHeadingData``) field indicates whether the compass service is calibrating. To help the calibration process, the app should show a message to the user asking them to move their wrists in different directions. Refer to the [compass example]({{site.links.examples_org}}/feature-compass) for an example of how to implement this screen. ## Magnetic North and True North Depending on the user's location on Earth, the measured heading towards magnetic north and true north can significantly differ. This is due to magnetic variation, also known as 'declination'. Pebble does not automatically correct the magnetic heading to return a true heading, but the API is designed so that this feature can be added in the future and the app will be able to automatically take advantage of it. For a more precise heading, use the `magnetic_heading` field of ``CompassHeadingData`` and use a webservice to retrieve the declination at the user's current location. Otherwise, use the `true_heading` field. This field will contain the `magnetic_heading` if declination is not available, or the true heading if declination is available. The field `is_declination_valid` will be true when declination is available. Use this information to tell the user whether the app is showing magnetic north or true north. ![Declination illustrated](/images/guides/pebble-apps/sensors/declination.gif) > To see the true extent of declination, see how declination has > [changed over time](http://maps.ngdc.noaa.gov/viewers/historical_declination/). ## Battery Considerations Using the compass will turn on both Pebble's magnetometer and accelerometer. Those two devices will have a slight impact on battery life. A much more significant battery impact will be caused by redrawing the screen too often or performing CPU-intensive work every time the compass heading is updated. Use ``compass_service_subscribe()`` if the app only needs to update its UI when new compass data is available, or else use ``compass_service_peek()`` if this happens much less frequently. ## Defining "Up" on Pebble Compass readings are always relative to the current orientation of Pebble. Using the accelerometer, the compass service figures out which direction the user is facing. ![Compass Orientation](/images/guides/pebble-apps/sensors/compass-orientation.png) The best orientation to encourage users to adopt while using a compass-enabled watchapp is with the top of the watch parallel to the ground. If the watch is raised so that the screen is facing the user, the plane will now be perpedicular to the screen, but still parallel to the ground. ## Angles and Degrees The magnetic heading value is presented as a number between 0 and TRIG_MAX_ANGLE (65536). This range is used to give a higher level of precision for drawing commands, which is preferable to using only 360 degrees. If you imagine an analogue clock face on your Pebble, the angle 0 is always at the 12 o'clock position, and the magnetic heading angle is calculated in a counter clockwise direction from 0. This can be confusing to grasp at first, as it’s opposite of how direction is measured on a compass, but it's simple to convert the values into a clockwise direction: ```c int clockwise_angle = TRIG_MAX_ANGLE - heading_data.magnetic_heading; ``` Once you have an angle relative to North, you can convert that to degrees using the helper function `TRIGANGLE_TO_DEG()`: ```c int degrees = TRIGANGLE_TO_DEG(TRIG_MAX_ANGLE - heading_data.magnetic_heading); ``` ## Subscribing to Compass Data Compass heading events can be received in a watchapp by subscribing to the ``CompassService``: ```c // Subscribe to compass heading updates compass_service_subscribe(compass_heading_handler); ``` The provided ``CompassHeadingHandler`` function (called `compass_heading_handler` above) can be used to read the state of the compass, and the current heading if it is available. This value is given in the range of `0` to ``TRIG_MAX_ANGLE`` to preserve precision, and so it can be converted using the ``TRIGANGLE_TO_DEG()`` macro: ```c static void compass_heading_handler(CompassHeadingData heading_data) { // Is the compass calibrated? switch(heading_data.compass_status) { case CompassStatusDataInvalid: APP_LOG(APP_LOG_LEVEL_INFO, "Not yet calibrated."); break; case CompassStatusCalibrating: APP_LOG(APP_LOG_LEVEL_INFO, "Calibration in progress. Heading is %ld", TRIGANGLE_TO_DEG(TRIG_MAX_ANGLE - heading_data.magnetic_heading)); break; case CompassStatusCalibrated: APP_LOG(APP_LOG_LEVEL_INFO, "Calibrated! Heading is %ld", TRIGANGLE_TO_DEG(TRIG_MAX_ANGLE - heading_data.magnetic_heading)); break; } } ``` By default, the callback will be triggered whenever the heading changes by one degree. To reduce the frequency of updates, change the threshold for heading changes by setting a heading filter: ```c // Only notify me when the heading has changed by more than 5 degrees. compass_service_set_heading_filter(DEG_TO_TRIGANGLE(5)); ``` ## Unsubscribing From Compass Data When the app is done using the compass, stop receiving callbacks by unsubscribing: ```c compass_service_unsubscribe(); ``` ## Peeking at Compass Data To fetch a compass heading without subscribing, simply peek to get a single sample: ```c // Peek to get data CompassHeadingData data; compass_service_peek(&data); ``` > Similar to the subscription-provided data, the app should examine the peeked > `CompassHeadingData` to determine if it is valid (i.e. the compass is > calibrated).
{ "source": "google/pebble", "title": "devsite/source/_guides/events-and-services/compass.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/events-and-services/compass.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 7115 }
--- # Copyright 2025 Google LLC # # 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. title: Dictation description: | How to use the Dictation API to get voice-to-text input in watchapps. guide_group: events-and-services order: 4 platforms: - basalt - chalk - diorite - emery related_docs: - Dictation related_examples: - title: Simple Voice Demo url: https://github.com/pebble-examples/simple-voice-demo - title: Voice Quiz url: https://github.com/pebble-examples/voice-quiz --- On hardware [platforms](/faqs/#pebble-sdk) supporting a microphone, the ``Dictation`` API can be used to gather arbitrary text input from a user. This approach is much faster than any previous button-based text input system (such as [tertiary text](https://github.com/vgmoose/tertiary_text)), and includes the ability to allow users to re-attempt dictation if there are any errors in the returned transcription. > Note: Apps running on multiple hardware platforms that may or may not include > a microphone should use the `PBL_MICROPHONE` compile-time define (as well as > checking API return values) to gracefully handle when it is not available. ## How the Dictation API Works The ``Dictation`` API invokes the same UI that is shown to the user when responding to notifications via the system menu, with events occuring in the following order: * The user initiates transcription and the dictation UI is displayed. * The user dictates the phrase they would like converted into text. * The audio is transmitted via the Pebble phone application to a 3rd party service and translated into text. * When the text is returned, the user is given the opportunity to review the result of the transcription. At this time they may elect to re-attempt the dictation by pressing the Back button and speaking clearer. * When the user is happy with the transcription, the text is provided to the app by pressing the Select button. * If an error occurs in the transcription attempt, the user is automatically allowed to re-attempt the dictation. * The user can retry their dictation by rejecting a successful transcription, but only if confirmation dialogs are enabled. ## Beginning a Dictation Session To get voice input from a user, an app must first create a ``DictationSession`` that contains data relating to the status of the dictation service, as well as an allocated buffer to store the result of any transcriptions. This should be declared in the file-global scope (as `static`), so it can be used at any time (in button click handlers, for example). ```c static DictationSession *s_dictation_session; ``` A callback of type ``DictationSessionStatusCallback`` is also required to notify the developer to the status of any dictation requests and transcription results. This is called at any time the dictation UI exits, which can be for any of the following reasons: * The user accepts a transcription result. * A transcription is successful but the confirmation dialog is disabled. * The user exits the dictation UI with the Back button. * When any error occurs and the error dialogs are disabled. * Too many transcription errors occur. ```c static void dictation_session_callback(DictationSession *session, DictationSessionStatus status, char *transcription, void *context) { // Print the results of a transcription attempt APP_LOG(APP_LOG_LEVEL_INFO, "Dictation status: %d", (int)status); } ``` At the end of this callback the `transcription` pointer becomes invalid - if the text is required later it should be copied into a separate buffer provided by the app. The size of this dictation buffer is chosen by the developer, and should be large enough to accept all expected input. Any transcribed text longer than the length of the buffer will be truncated. ```c // Declare a buffer for the DictationSession static char s_last_text[512]; ``` Finally, create the ``DictationSession`` and supply the size of the buffer and the ``DictationSessionStatusCallback``. This session may be used as many times as requires for multiple transcriptions. A context pointer may also optionally be provided. ```c // Create new dictation session s_dictation_session = dictation_session_create(sizeof(s_last_text), dictation_session_callback, NULL); ``` ## Obtaining Dictated Text After creating a ``DictationSession``, the developer can begin a dictation attempt at any time, providing that one is not already in progress. ```c // Start dictation UI dictation_session_start(s_dictation_session); ``` The dictation UI will be displayed and the user will speak their desired input. ![listening >{pebble-screenshot,pebble-screenshot--time-red}](/images/guides/pebble-apps/sensors/listening.png) It is recommended to provide visual guidance on the format of the expected input before the ``dictation_session_start()`` is called. For example, if the user is expected to speak a location that should be a city name, they should be briefed as such before being asked to provide input. When the user exits the dictation UI, the developer's ``DictationSessionStatusCallback`` will be called. The `status` parameter provided will inform the developer as to whether or not the transcription was successful using a ``DictationSessionStatus`` value. It is useful to check this value, as there are multiple reasons why a dictation request may not yield a successful result. These values are described below under [*DictationSessionStatus Values*](#dictationsessionstatus-values). If the value of `status` is equal to ``DictationSessionStatusSuccess``, the transcription was successful. The user's input can be read from the `transcription` parameter for evaluation and storage for later use if required. Note that once the callback returns, `transcription` will no longer be valid. For example, a ``TextLayer`` in the app's UI with variable name `s_output_layer` may be used to show the status of an attempted transcription: ```c if(status == DictationSessionStatusSuccess) { // Display the dictated text snprintf(s_last_text, sizeof(s_last_text), "Transcription:\n\n%s", transcription); text_layer_set_text(s_output_layer, s_last_text); } else { // Display the reason for any error static char s_failed_buff[128]; snprintf(s_failed_buff, sizeof(s_failed_buff), "Transcription failed.\n\nReason:\n%d", (int)status); text_layer_set_text(s_output_layer, s_failed_buff); } ``` The confirmation mechanism allowing review of the transcription result can be disabled if it is not needed. An example of such a scenario may be to speed up a 'yes' or 'no' decision where the two expected inputs are distinct and different. ```c // Disable the confirmation screen dictation_session_enable_confirmation(s_dictation_session, false); ``` It is also possible to disable the error dialogs, if so desired. This will disable the dialogs that appear when a transcription attempt fails, as well as disabling the ability to retry the dictation if a failure occurs. ``` // Disable error dialogs dictation_session_enable_error_dialogs(s_dictation_session, false); ``` ### DictationSessionStatus Values These are the possible values provided by a ``DictationSessionStatusCallback``, and should be used to handle transcription success or failure for any of the following reasons. | Status | Value | Description | |--------|-------|-------------| | ``DictationSessionStatusSuccess`` | `0` | Transcription successful, with a valid result. | | ``DictationSessionStatusFailureTranscriptionRejected`` | `1` | User rejected transcription and dismissed the dictation UI. | | ``DictationSessionStatusFailureTranscriptionRejectedWithError`` | `2` | User exited the dictation UI after a transcription error. | | ``DictationSessionStatusFailureSystemAborted`` | `3` | Too many errors occurred during transcription and the dictation UI exited. | | ``DictationSessionStatusFailureNoSpeechDetected`` | `4` | No speech was detected and the dictation UI exited. | | ``DictationSessionStatusFailureConnectivityError`` | `5` | No Bluetooth or Internet connection available. | | ``DictationSessionStatusFailureDisabled`` | `6` | Voice transcription disabled for this user. This can occur if the user has disabled sending 'Usage logs' in the Pebble mobile app. | | ``DictationSessionStatusFailureInternalError`` | `7` | Voice transcription failed due to an internal error. | | ``DictationSessionStatusFailureRecognizerError`` | `8` | Cloud recognizer failed to transcribe speech (only possible if error dialogs are disabled). |
{ "source": "google/pebble", "title": "devsite/source/_guides/events-and-services/dictation.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/events-and-services/dictation.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 9124 }
--- # Copyright 2025 Google LLC # # 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. title: Event Services description: | How to use the various asynchronous event services to power app features. guide_group: events-and-services order: 5 related_docs: - TickTimerService - ConnectionService - AccelerometerService - BatteryStateService - HealthService - AppFocusService - CompassService --- All Pebble apps are executed in three phases, which are summarized below: * Initialization - all code from the beginning of `main()` is run to set up all the components of the app. * Event Loop - the app waits for and responds to any event services it has subscribed to. * Deinitialization - when the app is exiting (i.e.: the user has pressed Back from the last ``Window`` in the stack) ``app_event_loop()`` returns, and all deinitialization code is run before the app exits. Once ``app_event_loop()`` is called, execution of `main()` pauses and all further activities are performed when events from various ``Event Service`` types occur. This continues until the app is exiting, and is typically handled in the following pattern: ```c static void init() { // Initialization code here } static void deinit() { // Deinitialization code here } int main(void) { init(); app_event_loop(); deinit(); } ``` ## Types of Events There are multiple types of events an app can receive from various event services. These are described in the table below, along with their handler signature and a brief description of what they do: | Event Service | Handler(s) | Description | |---------------|------------|-------------| | ``TickTimerService`` | ``TickHandler`` | Most useful for watchfaces. Allows apps to be notified when a second, minute, hour, day, month or year ticks by. | | ``ConnectionService`` | ``ConnectionHandler`` | Allows apps to know when the Bluetooth connection with the phone connects and disconnects. | | ``AccelerometerService`` | ``AccelDataHandler``<br/>``AccelTapHandler`` | Allows apps to receive raw data or tap events from the onboard accelerometer. | | ``BatteryStateService`` | ``BatteryStateHandler`` | Allows apps to read the state of the battery, as well as whether the watch is plugged in and charging. | | ``HealthService`` | ``HealthEventHandler`` | Allows apps to be notified to changes in various ``HealthMetric`` values as the user performs physical activities. | | ``AppFocusService`` | ``AppFocusHandler`` | Allows apps to know when they are obscured by another window, such as when a notification modal appears. | | ``CompassService`` | ``CompassHeadingHandler`` | Allows apps to read a compass heading, including calibration status of the sensor. | In addition, many other APIs also operate through the use of various callbacks including ``MenuLayer``, ``AppMessage``, ``Timer``, and ``Wakeup``, but these are not considered to be 'event services' in the same sense. ## Using Event Services The event services described in this guide are all used in the same manner - the app subscribes an implementation of one or more handlers, and is notified by the system when an event of that type occurs. In addition, most also include a 'peek' style API to read a single data item or status value on demand. This can be useful to determine the initial service state when a watchapp starts. Apps can subscribe to as many of these services as they require, and can also unsubscribe at any time to stop receiving events. Each event service is briefly discussed below with multiple snippets - handler implementation example, subscribing to the service, and any 'peek' API. ### Tick Timer Service The ``TickTimerService`` allows an app to be notified when different units of time change. This is decided based upon the ``TimeUnits`` value specified when a subscription is added. The [`struct tm`](http://www.cplusplus.com/reference/ctime/tm/) pointer provided in the handler is a standard C object that contains many data fields describing the current time. This can be used with [`strftime()`](http://www.cplusplus.com/reference/ctime/strftime/) to obtain a human-readable string. ```c static void tick_handler(struct tm *tick_time, TimeUnits changed) { static char s_buffer[8]; // Read time into a string buffer strftime(s_buffer, sizeof(s_buffer), "%H:%M", tick_time); APP_LOG(APP_LOG_LEVEL_INFO, "Time is now %s", s_buffer); } ``` ```c // Get updates when the current minute changes tick_timer_service_subscribe(MINUTE_UNIT, tick_handler); ``` > The ``TickTimerService`` has no 'peek' API, but a similar effect can be > achieved using the ``time()`` and ``localtime()`` APIs. ### Connection Service The ``ConnectionService`` uses a handler for each of two connection types: * `pebble_app_connection_handler` - the connection to the Pebble app on the phone, analogous with the bluetooth connection state. * `pebblekit_connection_handler` - the connection to an iOS companion app, if applicable. Will never occur on Android. Either one is optional, but at least one must be specified for a valid subscription. ```c static void app_connection_handler(bool connected) { APP_LOG(APP_LOG_LEVEL_INFO, "Pebble app %sconnected", connected ? "" : "dis"); } static void kit_connection_handler(bool connected) { APP_LOG(APP_LOG_LEVEL_INFO, "PebbleKit %sconnected", connected ? "" : "dis"); } ``` ```c connection_service_subscribe((ConnectionHandlers) { .pebble_app_connection_handler = app_connection_handler, .pebblekit_connection_handler = kit_connection_handler }); ``` ```c // Peek at either the Pebble app or PebbleKit connections bool app_connection = connection_service_peek_pebble_app_connection(); bool kit_connection = connection_service_peek_pebblekit_connection(); ``` ### Accelerometer Service The ``AccelerometerService`` can be used in two modes - tap events and raw data events. ``AccelTapHandler`` and ``AccelDataHandler`` are used for each of these respective use cases. See the {% guide_link events-and-services/accelerometer %} guide for more information. **Data Events** ```c static void accel_data_handler(AccelData *data, uint32_t num_samples) { APP_LOG(APP_LOG_LEVEL_INFO, "Got %d new samples", (int)num_samples); } ``` ```c const int num_samples = 10; // Subscribe to data events accel_data_service_subscribe(num_samples, accel_data_handler); ``` ```c // Peek at the last reading AccelData data; accel_service_peek(&data); ``` **Tap Events** ```c static void accel_tap_handler(AccelAxisType axis, int32_t direction) { APP_LOG(APP_LOG_LEVEL_INFO, "Tap event received"); } ``` ```c // Subscribe to tap events accel_tap_service_subscribe(accel_tap_handler); ``` ### Battery State Service The ``BatteryStateService`` allows apps to examine the state of the battery, and whether or not is is plugged in and charging. ```c static void battery_state_handler(BatteryChargeState charge) { // Report the current charge percentage APP_LOG(APP_LOG_LEVEL_INFO, "Battery charge is %d%%", (int)charge.charge_percent); } ``` ```c // Get battery state updates battery_state_service_subscribe(battery_state_handler); ``` ```c // Peek at the current battery state BatteryChargeState state = battery_state_service_peek(); ``` ### Health Service The ``HealthService`` uses the ``HealthEventHandler`` to notify a subscribed app when new data pertaining to a ``HealthMetric`` is available. See the {% guide_link events-and-services/health %} guide for more information. ```c static void health_handler(HealthEventType event, void *context) { if(event == HealthEventMovementUpdate) { APP_LOG(APP_LOG_LEVEL_INFO, "New health movement event"); } } ``` ```c // Subscribe to health-related events health_service_events_subscribe(health_handler, NULL); ``` ### App Focus Service The ``AppFocusService`` operates in two modes - basic and complete. **Basic Subscription** A basic subscription involves only one handler which will be fired when the app is moved in or out of focus, and any animated transition has completed. ```c static void focus_handler(bool in_focus) { APP_LOG(APP_LOG_LEVEL_INFO, "App is %s in focus", in_focus ? "now" : "not"); } ``` ```c // Add a basic subscription app_focus_service_subscribe(focus_handler); ``` **Complete Subscription** A complete subscription will notify the app with more detail about changes in focus using two handlers in an ``AppFocusHandlers`` object: * `.will_focus` - represents a change in focus that is *about* to occur, such as the start of a transition animation to or from a modal window. `will_focus` will be `true` if the app will be in focus at the end of the transition. * `.did_focus` - represents the end of a transition. `did_focus` will be `true` if the app is now completely in focus and the animation has finished. ```c void will_focus_handler(bool will_focus) { APP_LOG(APP_LOG_LEVEL_INFO, "Will %s focus", will_focus ? "gain" : "lose"); } void did_focus_handler(bool did_focus) { APP_LOG(APP_LOG_LEVEL_INFO, "%s focus", did_focus ? "Gained" : "Lost"); } ``` ```c // Subscribe to both types of events app_focus_service_subscribe_handlers((AppFocusHandlers) { .will_focus = will_focus_handler, .did_focus = did_focus_handler }); ``` ### Compass Service The ``CompassService`` provides access to regular updates about the watch's magnetic compass heading, if it is calibrated. See the {% guide_link events-and-services/compass %} guide for more information. ```c static void compass_heading_handler(CompassHeadingData heading_data) { // Is the compass calibrated? if(heading_data.compass_status == CompassStatusCalibrated) { APP_LOG(APP_LOG_LEVEL_INFO, "Calibrated! Heading is %ld", TRIGANGLE_TO_DEG(heading_data.magnetic_heading)); } } ``` ```c // Subscribe to compass heading updates compass_service_subscribe(compass_heading_handler); ``` ```c // Peek the compass heading data CompassHeadingData data; compass_service_peek(&data); ```
{ "source": "google/pebble", "title": "devsite/source/_guides/events-and-services/events.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/events-and-services/events.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 10548 }
--- # Copyright 2025 Google LLC # # 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. title: Pebble Health description: | Information on using the HealthService API to incorporate multiple types of health data into your apps. guide_group: events-and-services order: 6 platforms: - basalt - chalk - diorite - emery related_docs: - HealthService related_examples: - title: Simple Health Example url: https://github.com/pebble-examples/simple-health-example --- [Pebble Health](https://blog.getpebble.com/2015/12/15/health/) provides builtin health data tracking to allow users to improve their activity and sleep habits. With SDK 3.9, the ``HealthService`` API opens this data up to developers to include and use within their apps. For example, a watchface could display a brief summary of the user's activity for the day. ## API Availability In order to use the ``HealthService`` (and indeed Pebble Health), the user must enable the 'Pebble Health' app in the 'Apps/Timeline' view of the official Pebble mobile app. If this is not enabled health data will not be available to apps, and API calls will return values to reflect this. In addition, any app using the ``HealthService`` API must declare the 'health' capability in order to be accepted by the [developer portal](https://dev-portal.getpebble.com/). This can be done in CloudPebble 'Settings', or in `package.json` in the local SDK: ```js "capabilities": [ "health" ] ``` Since Pebble Health is not available on the Aplite platform, developers should check the API return values and hence the lack of ``HealthService`` on that platform gracefully. In addition, the `PBL_HEALTH` define and `PBL_IF_HEALTH_ELSE()` macro can be used to selectively omit affected code. ## Available Metrics The ``HealthMetric`` `enum` lists the types of data (or 'metrics') that can be read using the API. These are described below: | Metric | Description | |--------|-------------| | `HealthMetricStepCount` | The user's step count. | | `HealthMetricActiveSeconds` | Duration of time the user was considered 'active'. | | `HealthMetricWalkedDistanceMeters` | Estimation of the distance travelled in meters. | | `HealthMetricSleepSeconds` | Duration of time the user was considered asleep. | | `HealthMetricSleepRestfulSeconds` | Duration of time the user was considered in deep restful sleep. | | `HealthMetricRestingKCalories` | The number of kcal (thousand calories) burned due to resting metabolism. | | `HealthMetricActiveKCalories` | The number of kcal (thousand calories) burned due to activity. | | `HealthMetricHeartRateBPM` | The heart rate, in beats per minute. | ## Subscribing to HealthService Events Like other Event Services, an app can subscribe a handler function to receive a callback when new health data is available. This is useful for showing near-realtime activity updates. The handler must be a suitable implementation of ``HealthEventHandler``. The `event` parameter describes the type of each update, and is one of the following from the ``HealthEventType`` `enum`: | Event Type | Value | Description | |------------|-------|-------------| | `HealthEventSignificantUpdate` | `0` | All data is considered as outdated, apps should re-read all health data. This can happen on a change of the day or in other cases that significantly change the underlying data. | | `HealthEventMovementUpdate` | `1` | Recent values around `HealthMetricStepCount`, `HealthMetricActiveSeconds`, `HealthMetricWalkedDistanceMeters`, and `HealthActivityMask` changed. | | `HealthEventSleepUpdate` | `2` | Recent values around `HealthMetricSleepSeconds`, `HealthMetricSleepRestfulSeconds`, `HealthActivitySleep`, and `HealthActivityRestfulSleep` changed. | | `HealthEventHeartRateUpdate` | `4` | The value of `HealthMetricHeartRateBPM` has changed. | A simple example handler is shown below, which outputs to app logs the type of event that fired the callback: ```c static void health_handler(HealthEventType event, void *context) { // Which type of event occurred? switch(event) { case HealthEventSignificantUpdate: APP_LOG(APP_LOG_LEVEL_INFO, "New HealthService HealthEventSignificantUpdate event"); break; case HealthEventMovementUpdate: APP_LOG(APP_LOG_LEVEL_INFO, "New HealthService HealthEventMovementUpdate event"); break; case HealthEventSleepUpdate: APP_LOG(APP_LOG_LEVEL_INFO, "New HealthService HealthEventSleepUpdate event"); break; case HealthEventHeartRateUpdate: APP_LOG(APP_LOG_LEVEL_INFO, "New HealthService HealthEventHeartRateUpdate event"); break; } } ``` The subscription is then registered in the usual way, optionally providing a `context` parameter that is relayed to each event callback. The return value should be used to determine whether the subscription was successful: ```c #if defined(PBL_HEALTH) // Attempt to subscribe if(!health_service_events_subscribe(health_handler, NULL)) { APP_LOG(APP_LOG_LEVEL_ERROR, "Health not available!"); } #else APP_LOG(APP_LOG_LEVEL_ERROR, "Health not available!"); #endif ``` ## Reading Health Data Health data is collected in the background as part of Pebble Health regardless of the state of the app using the ``HealthService`` API, and is available to apps through various ``HealthService`` API functions. Before reading any health data, it is recommended to check that data is available for the desired time range, if applicable. In addition to the ``HealthServiceAccessibilityMask`` value, health-related code can be conditionally compiled using `PBL_HEALTH`. For example, to check whether any data is available for a given time range: ```c #if defined(PBL_HEALTH) // Use the step count metric HealthMetric metric = HealthMetricStepCount; // Create timestamps for midnight (the start time) and now (the end time) time_t start = time_start_of_today(); time_t end = time(NULL); // Check step data is available HealthServiceAccessibilityMask mask = health_service_metric_accessible(metric, start, end); bool any_data_available = mask & HealthServiceAccessibilityMaskAvailable; #else // Health data is not available here bool any_data_available = false; #endif ``` Most applications will want to read the sum of a metric for the current day's activity. This is the simplest method for accessing summaries of users' health data, and is shown in the example below: ```c HealthMetric metric = HealthMetricStepCount; time_t start = time_start_of_today(); time_t end = time(NULL); // Check the metric has data available for today HealthServiceAccessibilityMask mask = health_service_metric_accessible(metric, start, end); if(mask & HealthServiceAccessibilityMaskAvailable) { // Data is available! APP_LOG(APP_LOG_LEVEL_INFO, "Steps today: %d", (int)health_service_sum_today(metric)); } else { // No data recorded yet today APP_LOG(APP_LOG_LEVEL_ERROR, "Data unavailable!"); } ``` For more specific data queries, the API also allows developers to request data records and sums of metrics from a specific time range. If data is available, it can be read as a sum of all values recorded between that time range. You can use the convenience constants from ``Time``, such as ``SECONDS_PER_HOUR`` to adjust a timestamp relative to the current moment returned by ``time()``. > Note: The value returned will be an average since midnight, weighted for the > length of the specified time range. This may change in the future. An example of this process is shown below: ```c // Make a timestamp for now time_t end = time(NULL); // Make a timestamp for the last hour's worth of data time_t start = end - SECONDS_PER_HOUR; // Check data is available HealthServiceAccessibilityMask result = health_service_metric_accessible(HealthMetricStepCount, start, end); if(result & HealthServiceAccessibilityMaskAvailable) { // Data is available! Read it HealthValue steps = health_service_sum(HealthMetricStepCount, start, end); APP_LOG(APP_LOG_LEVEL_INFO, "Steps in the last hour: %d", (int)steps); } else { APP_LOG(APP_LOG_LEVEL_ERROR, "No data available!"); } ``` ## Representing Health Data Depending on the locale of the user, the conventional measurement system used to represent distances may vary between metric and imperial. For this reason it is recommended to query the user's preferred ``MeasurementSystem`` before formatting distance data from the ``HealthService``: > Note: This API is currently only meaningful when querying the > ``HealthMetricWalkedDistanceMeters`` metric. ``MeasurementSystemUnknown`` will > be returned for all other queries. ```c const HealthMetric metric = HealthMetricWalkedDistanceMeters; const HealthValue distance = health_service_sum_today(metric); // Get the preferred measurement system MeasurementSystem system = health_service_get_measurement_system_for_display( metric); // Format accordingly static char s_buffer[32]; switch(system) { case MeasurementSystemMetric: snprintf(s_buffer, sizeof(s_buffer), "Walked %d meters", (int)distance); break; case MeasurementSystemImperial: { // Convert to imperial first int feet = (int)((float)distance * 3.28F); snprintf(s_buffer, sizeof(s_buffer), "Walked %d feet", (int)feet); } break; case MeasurementSystemUnknown: default: APP_LOG(APP_LOG_LEVEL_INFO, "MeasurementSystem unknown or does not apply"); } // Display to user in correct units text_layer_set_text(s_some_layer, s_buffer); ``` ## Obtaining Averaged Data The ``HealthService`` also allows developers to read average values of a particular ``HealthMetric`` with varying degrees of scope. This is useful for apps that wish to display an average value (e.g.: as a goal for the user) alongside a summed value. In this context, the `start` and `end` parameters specify the time period to be used for the daily average calculation. For example, a start time of midnight and an end time ten hours later will return the average value for the specified metric measured until 10 AM on average across the days specified by the scope. The ``HealthServiceTimeScope`` specified when querying for averaged data over a given time range determines how the average is calculated, as detailed in the table below: | Scope Type | Description | |------------|-------------| | `HealthServiceTimeScopeOnce` | No average computed. The result is the same as calling ``health_service_sum()``. | | `HealthServiceTimeScopeWeekly` | Compute average using the same day from each week (up to four weeks). For example, every Monday if the provided time range falls on a Monday. | | `HealthServiceTimeScopeDailyWeekdayOrWeekend` | Compute average using either weekdays (Monday to Friday) or weekends (Saturday and Sunday), depending on which day the provided time range falls. | | `HealthServiceTimeScopeDaily` | Compute average across all days of the week. | > Note: If the difference between the start and end times is greater than one > day, an average will be returned that takes both days into account. Similarly, > if the time range crosses between scopes (such as including weekend days and > weekdays with ``HealthServiceTimeScopeDailyWeekdayOrWeekend``), the start time > will be used to determine which days are used. Reading averaged data values works in a similar way to reading sums. The example below shows how to read an average step count across all days of the week for a given time range: ```c // Define query parameters const HealthMetric metric = HealthMetricStepCount; const HealthServiceTimeScope scope = HealthServiceTimeScopeDaily; // Use the average daily value from midnight to the current time const time_t start = time_start_of_today(); const time_t end = time(NULL); // Check that an averaged value is accessible HealthServiceAccessibilityMask mask = health_service_metric_averaged_accessible(metric, start, end, scope); if(mask & HealthServiceAccessibilityMaskAvailable) { // Average is available, read it HealthValue average = health_service_sum_averaged(metric, start, end, scope); APP_LOG(APP_LOG_LEVEL_INFO, "Average step count: %d steps", (int)average); } ``` ## Detecting Activities It is possible to detect when the user is sleeping using a ``HealthActivityMask`` value. A useful application of this information could be to disable a watchface's animations or tick at a reduced rate once the user is asleep. This is done by checking certain bits of the returned value: ```c // Get an activities mask HealthActivityMask activities = health_service_peek_current_activities(); // Determine which bits are set, and hence which activity is active if(activities & HealthActivitySleep) { APP_LOG(APP_LOG_LEVEL_INFO, "The user is sleeping."); } else if(activities & HealthActivityRestfulSleep) { APP_LOG(APP_LOG_LEVEL_INFO, "The user is sleeping peacefully."); } else { APP_LOG(APP_LOG_LEVEL_INFO, "The user is not currently sleeping."); } ``` ## Read Per-Minute History The ``HealthMinuteData`` structure contains multiple types of activity-related data that are recorded in a minute-by-minute fashion. This style of data access is best suited to those applications requiring more granular detail (such as creating a new fitness algorithm). Up to seven days worth of data is available with this API. > See [*Notes on Minute-level Data*](#notes-on-minute-level-data) below for more > information on minute-level data. The data items contained in the ``HealthMinuteData`` structure are summarized below: | Item | Type | Description | |------|------|-------------| | `steps` | `uint8_t` | Number of steps taken in this minute. | | `orientation` | `uint8_t` | Quantized average orientation, encoding the x-y plane (the "yaw") in the lower 4 bits (360 degrees linearly mapped to 1 of 16 values) and the z axis (the "pitch") in the upper 4 bits. | | `vmc` | `uint16_t` | Vector Magnitude Counts (VMC). This is a measure of the total amount of movement seen by the watch. More vigorous movement yields higher VMC values. | | `is_invalid` | `bool` | `true` if the item doesn't represent actual data, and should be ignored. | | `heart_rate_bpm` | `uint8_t` | Heart rate in beats per minute (if available). | These data items can be obtained in the following manner, similar to obtaining a sum. ```c // Create an array to store data const uint32_t max_records = 60; HealthMinuteData *minute_data = (HealthMinuteData*) malloc(max_records * sizeof(HealthMinuteData)); // Make a timestamp for 15 minutes ago and an hour before that time_t end = time(NULL) - (15 * SECONDS_PER_MINUTE); time_t start = end - SECONDS_PER_HOUR; // Obtain the minute-by-minute records uint32_t num_records = health_service_get_minute_history(minute_data, max_records, &start, &end); APP_LOG(APP_LOG_LEVEL_INFO, "num_records: %d", (int)num_records); // Print the number of steps for each minute for(uint32_t i = 0; i < num_records; i++) { APP_LOG(APP_LOG_LEVEL_INFO, "Item %d steps: %d", (int)i, (int)minute_data[i].steps); } ``` Don't forget to free the array once the data is finished with: ```c // Free the array free(minute_data); ``` ### Notes on Minute-level Data Missing minute-level records can occur if the watch is reset, goes into low power (watch-only) mode due to critically low battery, or Pebble Health is disabled during the time period requested. ``health_service_get_minute_history()`` will return as many **consecutive** minute-level records that are available after the provided `start` timestamp, skipping any missing records until one is found. This API behavior enables one to easily continue reading data after a previous query encountered a missing minute. If there are some minutes with missing data, the API will return all available records up to the last available minute, and no further. Conversely, records returned will begin with the first available record after the provided `start` timestamp, skipping any missing records until one is found. This can be used to continue reading data after a previous query encountered a missing minute. The code snippet below shows an example function that packs a provided ``HealthMinuteData`` array with all available values in a time range, up to an arbitrary maximum number. Any missing minutes are collapsed, so that as much data can be returned as is possible for the allocated array size and time range requested. > This example shows querying up to 60 records. More can be obtained, but this > increases the heap allocation required as well as the time taken to process > the query. ```c static uint32_t get_available_records(HealthMinuteData *array, time_t query_start, time_t query_end, uint32_t max_records) { time_t next_start = query_start; time_t next_end = query_end; uint32_t num_records_found = 0; // Find more records until no more are returned while (num_records_found < max_records) { int ask_num_records = max_records - num_records_found; uint32_t ret_val = health_service_get_minute_history(&array[num_records_found], ask_num_records, &next_start, &next_end); if (ret_val == 0) { // a 0 return value means no more data is available return num_records_found; } num_records_found += ret_val; next_start = next_end; next_end = query_end; } return num_records_found; } static void print_last_hours_steps() { // Query for the last hour, max 60 minute-level records // (except the last 15 minutes) const time_t query_end = time(NULL) - (15 * SECONDS_PER_MINUTE); const time_t query_start = query_end - SECONDS_PER_HOUR; const uint32_t max_records = (query_end - query_start) / SECONDS_PER_MINUTE; HealthMinuteData *data = (HealthMinuteData*)malloc(max_records * sizeof(HealthMinuteData)); // Populate the array max_records = get_available_records(data, query_start, query_end, max_records); // Print the results for(uint32_t i = 0; i < max_records; i++) { if(!data[i].is_invalid) { APP_LOG(APP_LOG_LEVEL_INFO, "Record %d contains %d steps.", (int)i, (int)data[i].steps); } else { APP_LOG(APP_LOG_LEVEL_INFO, "Record %d was not valid.", (int)i); } } free(data); } ```
{ "source": "google/pebble", "title": "devsite/source/_guides/events-and-services/health.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/events-and-services/health.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 19078 }
--- # Copyright 2025 Google LLC # # 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. title: Heart Rate Monitor description: | Information on using the HealthService API to obtain information from the Heart Rate Monitor. guide_group: events-and-services order: 6 related_docs: - HealthService related_examples: - title: HRM Watchface url: https://github.com/pebble-examples/watchface-tutorial-hrm - title: HRM Activity url: https://github.com/pebble-examples/hrm-activity-example platform_choice: true --- The Pebble Time 2 and Pebble 2 (excluding SE model) {% guide_link tools-and-resources/hardware-information "devices" %} include a heart rate monitor. This guide will demonstrate how to use the ``HealthService`` API to retrieve information about the user's current, and historical heart rates. If you aren't already familiar with the ``HealthService``, we recommended that you read the {% guide_link events-and-services/health "Health guide" %} before proceeding. ## Enable Health Data <div class="platform-specific" data-sdk-platform="local"> {% markdown {} %} Before your application is able to access the heart rate information, you will need to add `heath` to the `capabilities` array in your applications `package.json` file. ```js { ... "pebble": { ... "capabilities": [ "health" ], ... } } ``` {% endmarkdown %} </div> ^CP^ Before your application is able to access heart rate information, you will need to enable the `USES HEALTH` option in your project settings on [CloudPebble]({{ site.data.links.cloudpebble }}). ## Data Quality Heart rate sensors aren't perfect, and their readings can be affected by improper positioning, environmental factors and excessive movement. The raw data from the HRM sensor contains a metric to indicate the quality of the readings it receives. The HRM API provides a raw BPM reading (``HealthMetricHeartRateRawBPM``) and a filtered reading (``HealthMetricHeartRateBPM``). This filtered value minimizes the effect of hand movement and improper sensor placement, by removing the bad quality readings. This filtered data makes it easy for developers to integrate in their applications, without needing to filter the data themselves. ## Obtaining the Current Heart Rate To obtain the current heart rate, you should first check whether the ``HealthMetricHeartRateBPM`` is available by using the ``health_service_metric_accessible`` method. Then you can obtain the current heart rate using the ``health_service_peek_current_value`` method: ```c HealthServiceAccessibilityMask hr = health_service_metric_accessible(HealthMetricHeartRateBPM, time(NULL), time(NULL)); if (hr & HealthServiceAccessibilityMaskAvailable) { HealthValue val = health_service_peek_current_value(HealthMetricHeartRateBPM); if(val > 0) { // Display HRM value static char s_hrm_buffer[8]; snprintf(s_hrm_buffer, sizeof(s_hrm_buffer), "%lu BPM", (uint32_t)val); text_layer_set_text(s_hrm_layer, s_hrm_buffer); } } ``` > **Note** this value is averaged from readings taken over the past minute, but due to the [sampling rate](#heart-rate-sample-periods) and our data filters, this value could be several minutes old. Use `HealthMetricHeartRateRawBPM` for the raw, unfiltered value. ## Subscribing to Heart Rate Updates The user's heart rate can also be monitored via an event subscription, in a similar way to the other health metrics. If you wanted your watchface to update the displayed heart rate every time the HRM takes a new reading, you could use the ``health_service_events_subscribe`` method. ```c static void prv_on_health_data(HealthEventType type, void *context) { // If the update was from the Heart Rate Monitor, query it if (type == HealthEventHeartRateUpdate) { HealthValue value = health_service_peek_current_value(HealthMetricHeartRateBPM); // Display the heart rate } } static void prv_init(void) { // Subscribe to health event handler health_service_events_subscribe(prv_on_health_data, NULL); // ... } ``` > **Note** The frequency of these updates does not directly correlate to the > sensor sampling rate. ## Heart Rate Sample Periods The default sample period is 10 minutes, but the system automatically controls the HRM sample rate based on the level of user activity. It increases the sampling rate during intense activity and reduces it again during inactivity. This aims to provide the optimal battery usage. ### Battery Considerations Like all active sensors, accelerometer, backlight etc, the HRM sensor will have a negative affect on battery life. It's important to consider this when using the APIs within your application. By default the system will automatically control the heart rate sampling period for the optimal balance between update frequency and battery usage. In addition, the APIs have been designed to allow developers to retrieve values for the most common use cases with minimal impact on battery life. ### Altering the Sampling Period Developers can request a specific sampling rate using the ``health_service_set_heart_rate_sample_period`` method. The system will use this value as a suggestion, but does not guarantee that value will be used. The actual sampling period may be greater or less due to other apps that require input from the sensor, or data quality issues. The shortest period you can currently specify is `1` second, and the longest period you can specify is `600` seconds (10 minutes). In this example, we will sample the heart rate monitor every second: ```c // Set the heart rate monitor to sample every second bool success = health_service_set_heart_rate_sample_period(1); ``` > **Note** This does not mean that you can peek the current value every second, > only that the sensor will capture more samples. ### Resetting the Sampling Period Developers **must** reset the heart rate sampling period when their application exits. Failing to do so may result in the heart rate monitor continuing at the increased rate for a period of time, even after your application closes. This is fundamentally different to other Pebble sensors and was designed so that applications which a reliant upon high sampling rates can be temporarily interupted for notifications, or music, without affecting the sensor data. ```c // Reset the heart rate sampling period to automatic health_service_set_heart_rate_sample_period(0); ``` ## Obtaining Historical Data If your application is using heart rate information, it may also want to obtain historical data to compare it against. In this section we'll look at how you can use the `health_service_aggregate` functions to obtain relevant historic data. Before requesting historic/aggregate data for a specific time period, you should ensure that it is available using the ``health_service_metric_accessible`` method. Then we'll use the ``health_service_aggregate_averaged`` method to obtain the average daily heart rate over the last 7 days. ```c // Obtain history for last 7 days time_t end_time = time(NULL); time_t start_time = end_time - (7 * SECONDS_PER_DAY); HealthServiceAccessibilityMask hr = health_service_metric_accessible(HealthMetricHeartRateBPM, start_time, end_time); if (hr & HealthServiceAccessibilityMaskAvailable) { uint32_t weekly_avg_hr = health_service_aggregate_averaged(HealthMetricHeartRateBPM, start_time, end_time, HealthAggregationAvg, HealthServiceTimeScopeDaily); } ``` You can also query the average `min` and `max` heart rates, but only within the past two hours (maximum). This limitation is due to very limited storage capacity on the device, but the implementation may change in the future. ```c // Obtain history for last 1 hour time_t end_time = time(NULL); time_t start_time = end_time - SECONDS_PER_HOUR; HealthServiceAccessibilityMask hr = health_service_metric_accessible(HealthMetricHeartRateBPM, start_time, end_time); if (hr & HealthServiceAccessibilityMaskAvailable) { uint32_t min_hr = health_service_aggregate_averaged(HealthMetricHeartRateBPM, start_time, end_time, HealthAggregationMin, HealthServiceTimeScopeOnce); uint32_t max_hr = health_service_aggregate_averaged(HealthMetricHeartRateBPM, start_time, end_time, HealthAggregationMax, HealthServiceTimeScopeOnce); } ``` ## Read Per-Minute History The ``HealthMinuteData`` structure contains multiple types of activity-related data that are recorded in a minute-by-minute fashion. Although this structure now contains HRM readings, it does not contain information about the quality of those readings. > **Note** Please refer to the > {% guide_link events-and-services/health#read-per-minute-history "Health Guide" %} > for futher information. ## Next Steps This guide covered the basics of how to interact with realtime and historic heart information. We encourage you to further explore the ``HealthService`` documentation, and integrate it into your next project.
{ "source": "google/pebble", "title": "devsite/source/_guides/events-and-services/hrm.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/events-and-services/hrm.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 9590 }
--- # Copyright 2025 Google LLC # # 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. title: Events and Services description: | How to get data from the onboard sensors including the accelerometer, compass, and microphone. guide_group: events-and-services menu: false permalink: /guides/events-and-services/ generate_toc: false hide_comments: true --- All Pebble watches contain a collection of sensors than can be used as input devices for apps. Available sensors include four buttons, an accelerometer, and a magnetometer (accessible via the ``CompassService`` API). In addition, the Basalt and Chalk platforms also include a microphone (accessible via the ``Dictation`` API) and access to Pebble Health data sets. Read {% guide_link tools-and-resources/hardware-information %} for more information on sensor availability per platform. While providing more interactivity, excessive regular use of these sensors will stop the watch's CPU from sleeping and result in faster battery drain, so use them sparingly. An alternative to constantly reading accelerometer data is to obtain data in batches, allowing sleeping periods in between. Read {% guide_link best-practices/conserving-battery-life %} for more information. ## Contents {% include guides/contents-group.md group=page.group_data %}
{ "source": "google/pebble", "title": "devsite/source/_guides/events-and-services/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/events-and-services/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 1795 }
--- # Copyright 2025 Google LLC # # 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. title: Persistent Storage description: | Using persistent storage to improve your app's UX. guide_group: events-and-services order: 7 related_docs: - Storage --- Developers can use the ``Storage`` API to persist multiple types of data between app launches, enabling apps to remember information previously entered by the user. A common use-case of this API is to enable the app to remember configuration data chosen in an app's configuration page, removing the tedious need to enter the information on the phone every time the watchapp is launched. Other use cases include to-to lists, stat trackers, game highscores etc. Read {% guide_link user-interfaces/app-configuration %} for more information on implementing an app configuration page. ## Persistent Storage Model Every app is allocated 4 kB of persistent storage space and can write values to storage using a key, similar to ``AppMessage`` dictionaries or the web `localStorage` API. To recall values, the app simply queries the API using the associated key . Keys are specified in the `uint32_t` type, and each value can have a size up to ``PERSIST_DATA_MAX_LENGTH`` (currently 256 bytes). When an app is updated the values saved using the ``Storage`` API will be persisted, but if it is uninstalled they will be removed. Apps that make large use of the ``Storage`` API may experience small pauses due to underlying housekeeping operations. Therefore it is recommended to read and write values when an app is launching or exiting, or during a time the user is waiting for some other action to complete. ## Types of Data Values can be stored as boolean, integer, string, or arbitrary data structure types. Before retrieving a value, the app should check that it has been previously persisted. If it has not, a default value should be chosen as appropriate. ```c uint32_t key = 0; int num_items = 0; if (persist_exists(key)) { // Read persisted value num_items = persist_read_int(key); } else { // Choose a default value num_items = 10; // Remember the default value until the user chooses their own value persist_write_int(key, num_items); } ``` The API provides a 'read' and 'write' function for each of these types, with builtin data types retrieved through assignment, and complex ones into a buffer provided by the app. Examples of each are shown below. ### Booleans ```c uint32_t key = 0; bool large_font_size = true; ``` ```c // Write a boolean value persist_write_bool(key, large_font_size); ``` ```c // Read the boolean value bool large_font_size = persist_read_bool(key); ``` ### Integers ```c uint32_t key = 1; int highscore = 432; ``` ```c // Write an integer persist_write_int(key, highscore); ``` ```c // Read the integer value int highscore = persist_read_int(key); ``` ### Strings ```c uint32_t key = 2; char *string = "Remember this!"; ``` ```c // Write the string persist_write_string(key, string); ``` ```c // Read the string char buffer[32]; persist_read_string(key, buffer, sizeof(buffer)); ``` ### Data Structures ```c typedef struct { int a; int b; } Data; uint32_t key = 3; Data data = (Data) { .a = 32, .b = 45 }; ``` ```c // Write the data structure persist_write_data(key, &data, sizeof(Data)); ``` ```c // Read the data structure persist_read_data(key, &data, sizeof(Data)); ``` > Note: If a persisted data structure's field layout changes between app > versions, the data read may no longer be compatible (see below). ## Versioning Persisted Data As already mentioned, automatic app updates will persist data between app versions. However, if the format of persisted data changes in a new app version (or keys change), developers should version their storage scheme and correctly handle version changes appropriately. One way to do this is to use an extra persisted integer as the storage scheme's version number. If the scheme changes, simply update the version number and migrate existing data as required. If old data cannot be migrated it should be deleted and replaced with fresh data in the correct scheme from the user. An example is shown below: ```c const uint32_t storage_version_key = 786; const int current_storage_version = 2; ``` ```c // Store the current storage scheme version number persist_write_int(storage_version_key, current_storage_version); ``` In this example, data stored in a key of `12` is now stored in a key of `13` due to a new key being inserted higher up the list of key values. ```c // The scheme has changed, increment the version number const int current_storage_version = 3; ``` ```c static void migrate_storage_data() { // Check the last storage scheme version the app used int last_storage_version = persist_read_int(storage_version_key); if (last_storage_version == current_storage_version) { // No migration necessary return; } // Migrate data switch(last_storage_version) { case 0: // ... break; case 1: // ... break; case 2: { uint32_t old_highscore_key = 12; uint32_t new_highscore_key = 13; // Migrate to scheme version 3 int highscore = persist_read_int(old_highscore_key); persist_write_int(new_highscore_key, highscore); // Delete old data persist_delete(old_highscore_key); break; } // Migration is complete, store the current storage scheme version number persist_write_int(storage_version_key, current_storage_version); } ``` ## Alternative Method In addition to the ``Storage`` API, data can also be persisted using the `localStorage` API in PebbleKit JS, and communicated with the watch over ``AppMessage`` when the app is lanched. However, this method uses more power and fails if the watch is not connected to the phone.
{ "source": "google/pebble", "title": "devsite/source/_guides/events-and-services/persistent-storage.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/events-and-services/persistent-storage.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 6326 }
--- # Copyright 2025 Google LLC # # 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. title: Wakeups description: | Using the Wakeup API to launch an app at some future time. guide_group: events-and-services order: 8 related_examples: - title: Tea Timer url: https://github.com/pebble-examples/feature-app-wakeup related_docs: - Wakeup - AppLaunchReason - launch_reason - Timer --- The ``Wakeup`` API allows developers to schedule an app launch in the future, even if the app itself is closed in the meantime. A wakeup event is scheduled in a similar manner to a ``Timer`` with a future timestamp calculated beforehand. ## Calculating Timestamps To schedule a wakeup event, first determine the timestamp of the desired wakeup time as a `time_t` variable. Most uses of the ``Wakeup`` API will fall into three distinct scenarios discussed below. ### A Future Time Call ``time()`` and add the offset, measured in seconds. For example, for 30 minutes in the future: ```c // 30 minutes from now time_t timestamp = time(NULL) + (30 * SECONDS_PER_MINUTE); ``` ### A Specific Time Use ``clock_to_timestamp()`` to obtain a `time_t` timestamp by specifying a day of the week and hours and minutes (in 24 hour format). For example, for the next occuring Monday at 5 PM: ```c // Next occuring monday at 17:00 time_t timestamp = clock_to_timestamp(MONDAY, 17, 0); ``` ### Using a Timestamp Provided by a Web Service The timestamp will need to be translated using the [`getTimezoneOffset()`](http://www.w3schools.com/jsref/jsref_gettimezoneoffset.asp) method available in PebbleKit JS or with any timezone information given by the web service. ## Scheduling a Wakeup Once a `time_t` timestamp has been calculated, the wakeup event can be scheduled: ```c // Let the timestamp be 30 minutes from now const time_t future_timestamp = time() + (30 * SECONDS_PER_MINUTE); // Choose a 'cookie' value representing the reason for the wakeup const int cookie = 0; // If true, the user will be notified if they missed the wakeup // (i.e. their watch was off) const bool notify_if_missed = true; // Schedule wakeup event WakeupId id = wakeup_schedule(future_timestamp, cookie, notify_if_missed); // Check the scheduling was successful if(id >= 0) { // Persist the ID so that a future launch can query it const wakeup_id_key = 43; persist_write_int(wakeup_id_key, id); } ``` After scheduling a wakeup event it is possible to perform some interaction with it. For example, reading the timestamp for when the event will occur using the ``WakeupId`` with ``wakeup_query()``, and then perform simple arithmetic to get the time remaining: ```c // This will be set by wakeup_query() time_t wakeup_timestamp = 0; // Is the wakeup still scheduled? if(wakeup_query(id, &wakeup_timestamp)) { // Get the time remaining int seconds_remaining = wakeup_timestamp - time(NULL); APP_LOG(APP_LOG_LEVEL_INFO, "%d seconds until wakeup", seconds_remaining); } ``` To cancel a scheduled event, use the ``WakeupId`` obtained when it was scheduled: ```c // Cancel a wakeup wakeup_cancel(id); ``` To cancel all scheduled wakeup events: ```c // Cancel all wakeups wakeup_cancel_all(); ``` ## Limitations There are three limitations that should be taken into account when using the Wakeup API: * There can be no more than 8 scheduled wakeup events per app at any one time. * Wakeup events cannot be scheduled within 30 seconds of the current time. * Wakeup events are given a one minute window either side of the wakeup time. In this time no app may schedule an event. The return ``StatusCode`` of ``wakeup_schedule()`` should be checked to determine whether the scheduling of the new event should be reattempted. A negative value indicates that the wakeup could not be scheduled successfully. The possible ``StatusCode`` values are detailed below: |StatusCode|Value|Description| |----------|-----|-----------| | `E_RANGE` | `-8` | The wakeup event cannot be scheduled due to another event in that period. | | `E_INVALID_ARGUMENT` | `-4` | The time requested is in the past. | | `E_OUT_OF_RESOURCES` | `-7` | The application has already scheduled all 8 wakeup events. | | `E_INTERNAL` | `-3` | A system error occurred during scheduling. | ## Handling Wakeup Events A wakeup event can occur at two different times - when the app is closed, and when it is already launched and in the foreground. If the app is launched due to a previously scheduled wakeup event, check the ``AppLaunchReason`` and load the app accordingly: ```c static void init() { if(launch_reason() == APP_LAUNCH_WAKEUP) { // The app was started by a wakeup event. WakeupId id = 0; int32_t reason = 0; // Get details and handle the event appropriately wakeup_get_launch_event(&id, &reason); } /* other init code */ } ``` If the app is expecting a wakeup to occur while it is open, use a subscription to the wakeup service to be notified of such events: ```c static void wakeup_handler(WakeupId id, int32_t reason) { // A wakeup event has occurred while the app was already open } ``` ```c // Subscribe to wakeup service wakeup_service_subscribe(wakeup_handler); ``` The two approaches can also be combined for a unified response to being woken up, not depenent on the state of the app: ```c // Get details of the wakeup wakeup_get_launch_event(&id, &reason); // Manually handle using the handler wakeup_handler(id, reason); ```
{ "source": "google/pebble", "title": "devsite/source/_guides/events-and-services/wakeups.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/events-and-services/wakeups.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 5955 }
--- # Copyright 2025 Google LLC # # 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. title: Animations description: | How to use Animations and Timers to add life to your app. guide_group: graphics-and-animations order: 0 related_docs: - Animation - Timer - AnimationImplementation related_examples: - title: Composite Animations Example url: https://github.com/pebble-examples/composite-animations-example - title: Feature Property Animation url: https://github.com/pebble-examples/feature-property-animation --- The ``Animation`` API allows a variety of different types of value to be smoothly animated from an initial value to a new value over time. Animations can also use built-in easing curves to affect how the transition behaves. ## Using PropertyAnimations The most common use of animations is to move a ``Layer`` (or similar) around the display. For example, to show or hide some information or animate the time changing in a watchface. The simplest method of animating a ``Layer`` (such as a ``TextLayer``) is to use a ``PropertyAnimation``, which animates a property of the target object. In this example, the target is the frame property, which is a ``GRect`` To animate the this property, ``property_animation_create_layer_frame()`` is used, which is a convenience ``PropertyAnimation`` implementation provided by the SDK. ```c static Layer *s_layer; ``` Create the Layer during ``Window`` initialization: ```c // Create the Layer s_layer = layer_create(some_bounds); ``` Determine the start and end values of the ``Layer``'s frame. These are the 'from' and 'to' locations and sizes of the ``Layer`` before and after the animation takes place: ```c // The start and end frames - move the Layer 40 pixels to the right GRect start = GRect(10, 10, 20, 20); GRect finish = GRect(50, 10, 20, 20); ``` At the appropriate time, create a ``PropertyAnimation`` to animate the ``Layer``, specifying the `start` and `finish` values as parameters: ```c // Animate the Layer PropertyAnimation *prop_anim = property_animation_create_layer_frame(s_layer, &start, &finish); ``` Configure the attributes of the ``Animation``, such as the delay before starting, and total duration (in milliseconds): ```c // Get the Animation Animation *anim = property_animation_get_animation(prop_anim); // Choose parameters const int delay_ms = 1000; const int duration_ms = 500; // Configure the Animation's curve, delay, and duration animation_set_curve(anim, AnimationCurveEaseOut); animation_set_delay(anim, delay_ms); animation_set_duration(anim, duration_ms); ``` Finally, schedule the ``Animation`` to play at the next possible opportunity (usually immediately): ```c // Play the animation animation_schedule(anim); ``` If the app requires knowledge of the start and end times of an ``Animation``, it is possible to register ``AnimationHandlers`` to be notified of these events. The handlers should be created with the signature of these examples shown below: ```c static void anim_started_handler(Animation *animation, void *context) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Animation started!"); } static void anim_stopped_handler(Animation *animation, bool finished, void *context) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Animation stopped!"); } ``` Register the handlers with an optional third context parameter **before** scheduling the ``Animation``: ```c // Set some handlers animation_set_handlers(anim, (AnimationHandlers) { .started = anim_started_handler, .stopped = anim_stopped_handler }, NULL); ``` With the handlers registered, the start and end times of the ``Animation`` can be detected by the app and used as appropriate. ### Other Types of PropertyAnimation In addition to ``property_animation_create_layer_frame()``, it is also possible to animate the origin of a ``Layer``'s bounds using ``property_animation_create_bounds_origin()``. Animation of more types of data can be achieved using custom implementations and one the following provided update implementations and the associated [getters and setters](``property_animation_update_int16``): * ``property_animation_update_int16`` - Animate an `int16`. * ``property_animation_update_uint32`` - Animate a `uint32`. * ``property_animation_update_gpoint`` - Animate a ``GPoint``. * ``property_animation_update_grect`` - Animate a ``GRect`` * ``property_animation_update_gcolor8`` - Animate a ``GColor8``. ## Custom Animation Implementations Beyond the convenience functions provided by the SDK, apps can implement their own ``Animation`` by using custom callbacks for each stage of the animation playback process. A ``PropertyAnimation`` is an example of such an implementation. The callbacks to implement are the `.setup`, `.update`, and `.teardown` members of an ``AnimationImplementation`` object. Some example implementations are shown below. It is in the `.update` callback where the value of `progress` can be used to modify the custom target of the animation. For example, some percentage of completion: ```c static void implementation_setup(Animation *animation) { APP_LOG(APP_LOG_LEVEL_INFO, "Animation started!"); } static void implementation_update(Animation *animation, const AnimationProgress progress) { // Animate some completion variable s_animation_percent = ((int)progress * 100) / ANIMATION_NORMALIZED_MAX; APP_LOG(APP_LOG_LEVEL_INFO, "Animation progress: %d%%", s_animation_percent); } static void implementation_teardown(Animation *animation) { APP_LOG(APP_LOG_LEVEL_INFO, "Animation finished!"); } ``` Once these are in place, create a new ``Animation`` , specifying the new custom implementation as a `const` object pointer at the appropriate time: ```c // Create a new Animation Animation *animation = animation_create(); animation_set_delay(animation, 1000); animation_set_duration(animation, 1000); // Create the AnimationImplementation const AnimationImplementation implementation = { .setup = implementation_setup, .update = implementation_update, .teardown = implementation_teardown }; animation_set_implementation(animation, &implementation); // Play the Animation animation_schedule(animation); ``` The output of the example above will look like the snippet shown below (edited for brevity). Note the effect of the easing ``AnimationCurve`` on the progress value: ```nc|text [13:42:33] main.c:11> Animation started! [13:42:34] main.c:19> Animation progress: 0% [13:42:34] main.c:19> Animation progress: 0% [13:42:34] main.c:19> Animation progress: 0% [13:42:34] main.c:19> Animation progress: 2% [13:42:34] main.c:19> Animation progress: 3% [13:42:34] main.c:19> Animation progress: 5% [13:42:34] main.c:19> Animation progress: 7% [13:42:34] main.c:19> Animation progress: 10% [13:42:34] main.c:19> Animation progress: 14% [13:42:35] main.c:19> Animation progress: 17% [13:42:35] main.c:19> Animation progress: 21% [13:42:35] main.c:19> Animation progress: 26% ... [13:42:35] main.c:19> Animation progress: 85% [13:42:35] main.c:19> Animation progress: 88% [13:42:35] main.c:19> Animation progress: 91% [13:42:35] main.c:19> Animation progress: 93% [13:42:35] main.c:19> Animation progress: 95% [13:42:35] main.c:19> Animation progress: 97% [13:42:35] main.c:19> Animation progress: 98% [13:42:35] main.c:19> Animation progress: 99% [13:42:35] main.c:19> Animation progress: 99% [13:42:35] main.c:19> Animation progress: 100% [13:42:35] main.c:23> Animation finished! ``` ## Timers [`AppTimer`](``Timer``) objects can be used to schedule updates to variables and objects at a later time. They can be used to implement frame-by-frame animations as an alternative to using the ``Animation`` API. They can also be used in a more general way to schedule events to occur at some point in the future (such as UI updates) while the app is open. A thread-blocking alternative for small pauses is ``psleep()``, but this is **not** recommended for use in loops updating UI (such as a counter), or for scheduling ``AppMessage`` messages, which rely on the event loop to do their work. > Note: To create timed events in the future that persist after an app is > closed, check out the ``Wakeup`` API. When a timer elapses, it will call a developer-defined ``AppTimerCallback``. This is where the code to be executed after the timed interval should be placed. The callback will only be called once, so use this opportunity to re-register the timer if it should repeat. ```c static void timer_callback(void *context) { APP_LOG(APP_LOG_LEVEL_INFO, "Timer elapsed!"); } ``` Schedule the timer with a specific `delay` interval, the name of the callback to fire, and an optional context pointer: ```c const int delay_ms = 5000; // Schedule the timer app_timer_register(delay_ms, timer_callback, NULL); ``` If the timer may need to be cancelled or rescheduled at a later time, ensure a reference to it is kept for later use: ```c static AppTimer *s_timer; ``` ```c // Register the timer, and keep a handle to it s_timer = app_timer_register(delay_ms, timer_callback, NULL); ``` If the timer needs to be cancelled, use the previous reference. If it has already elapsed, nothing will occur: ```c // Cancel the timer app_timer_cancel(s_timer); ``` ## Sequence and Spawn Animations The Pebble SDK also includes the capability to build up composite animations built from other ``Animation`` objects. There are two types: a sequence animation and a spawn animation. * A sequence animation is a set of two or more other animations that are played out in **series** (one after another). For example, a pair of timed animations to show and hide a ``Layer``. * A spawn animation is a set of two or more other animations that are played out in **parallel**. A spawn animation acts the same as creating and starting two or more animations at the same time, but has the advantage that it can be included as part of a sequence animation. > Note: Composite animations can be composed of other composite animations. ### Important Considerations When incorporating an ``Animation`` into a sequence or spawn animation, there are a couple of points to note: * Any single animation cannot appear more than once in the list of animations used to create a more complex animation. * A composite animation assumes ownership of its component animations once it has been created. * Once an animation has been added to a composite animation, it becomes immutable. This means it can only be read, and not written to. Attempts to modify such an animation after it has been added to a composite animation will fail. * Once an animation has been added to a composite animation, it cannot then be used to build a different composite animation. ### Creating a Sequence Animation To create a sequence animation, first create the component ``Animation`` objects that will be used to build it. ```c // Create the first Animation PropertyAnimation *prop_anim = property_animation_create_layer_frame(s_layer, &start, &finish); Animation *animation_a = property_animation_get_animation(prop_anim); // Set some properties animation_set_delay(animation_a, 1000); animation_set_duration(animation_a, 500); // Clone the first, modify the duration and reverse it. Animation *animation_b = animation_clone(animation_a); animation_set_reverse(animation_b, true); animation_set_duration(animation_b, 1000); ``` Use these component animations to create the sequence animation. You can either specify the components as a list or pass an array. Both approaches are shown below. #### Using a List You can specify up to 20 ``Animation`` objects as parameters to `animation_sequence_create()`. The list must always be terminated with `NULL` to mark the end. ```c // Create the sequence Animation *sequence = animation_sequence_create(animation_a, animation_b, NULL); // Play the sequence animation_schedule(sequence); ``` #### Using an Array You can also specify the component animations using a dynamically allocated array. Give this to `animation_sequence_create_from_array()` along with the size of the array. ```c const uint32_t array_length = 2; // Create the array Animation **arr = (Animation**)malloc(array_length * sizeof(Animation*)); arr[0] = animation_a; arr[1] = animation_b; // Create the sequence, set to loop forever Animation *sequence = animation_sequence_create_from_array(arr, array_length); animation_set_play_count(sequence, ANIMATION_DURATION_INFINITE); // Play the sequence animation_schedule(sequence); // Destroy the array free(arr); ``` ### Creating a Spawn Animation Creating a spawn animation is done in a very similiar way to a sequence animation. The animation is built up from component animations which are then all started at the same time. This simplifies the task of precisely timing animations that are designed to coincide. The first step is the same as for sequence animations, which is to create a number of component animations to be spawned together. ```c // Create the first animation Animation *animation_a = animation_create(); animation_set_duration(animation_a, 1000); // Clone the first, modify the duration and reverse it. Animation *animation_b = animation_clone(animation_a); animation_set_reverse(animation_b, true); animation_set_duration(animation_b, 300); ``` Next, the spawn animation is created in a similar manner to the sequence animation with a `NULL` terminated list of parameters: ```c // Create the spawn animation Animation *spawn = animation_spawn_create(animation_a, animation_b, NULL); // Play the animation animation_schedule(spawn); ``` Alternatively the spawn animation can be created with an array of ``Animation`` objects. ```c const uint32_t array_length = 2; // Create the array Animation **arr = (Animation**)malloc(array_length * sizeof(Animation*)); arr[0] = animation_a; arr[1] = animation_b; // Create the sequence and set the play count to 3 Animation *spawn = animation_spawn_create_from_array(arr, array_length); animation_set_play_count(spawn, 3); // Play the spawn animation animation_schedule(spawn); // Destroy the array free(arr); ```
{ "source": "google/pebble", "title": "devsite/source/_guides/graphics-and-animations/animations.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/graphics-and-animations/animations.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 14756 }
--- # Copyright 2025 Google LLC # # 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. title: Drawing Primitives, Images and Text description: | How to draw primitive shapes, image, and text onto the Graphics Context. guide_group: graphics-and-animations order: 1 --- While ``Layer`` types such as ``TextLayer`` and ``BitmapLayer`` allow easy rendering of text and bitmaps, more precise drawing can be achieved through the use of the ``Graphics Context`` APIs. Custom drawing of primitive shapes such as line, rectangles, and circles is also supported. Clever use of these functions can remove the need to pre-prepare bitmap images for many UI elements and icons. ## Obtaining a Drawing Context All custom drawing requires a ``GContext`` instance. These cannot be created, and are only available inside a ``LayerUpdateProc``. This update procedure is simply a function that is called when a ``Layer`` is to be rendered, and is defined by the developer as opposed to the system. For example, a ``BitmapLayer`` is simply a ``Layer`` with a ``LayerUpdateProc`` abstracted away for convenience by the SDK. First, create the ``Layer`` that will have a custom drawing procedure: ```c static Layer *s_canvas_layer; ``` Allocate the ``Layer`` during ``Window`` creation: ```c GRect bounds = layer_get_bounds(window_get_root_layer(window)); // Create canvas layer s_canvas_layer = layer_create(bounds); ``` Next, define the ``LayerUpdateProc`` according to the function specification: ```c static void canvas_update_proc(Layer *layer, GContext *ctx) { // Custom drawing happens here! } ``` Assign this procedure to the canvas layer and add it to the ``Window`` to make it visible: ```c // Assign the custom drawing procedure layer_set_update_proc(s_canvas_layer, canvas_update_proc); // Add to Window layer_add_child(window_get_root_layer(window), s_canvas_layer); ``` From now on, every time the ``Layer`` needs to be redrawn (for example, if other layer geometry changes), the ``LayerUpdateProc`` will be called to allow the developer to draw it. It can also be explicitly marked for redrawing at the next opportunity: ```c // Redraw this as soon as possible layer_mark_dirty(s_canvas_layer); ``` ## Drawing Primitive Shapes The ``Graphics Context`` API allows drawing and filling of lines, rectangles, circles, and arbitrary paths. For each of these, the colors of the output can be set using the appropriate function: ```c // Set the line color graphics_context_set_stroke_color(ctx, GColorRed); // Set the fill color graphics_context_set_fill_color(ctx, GColorBlue); ``` In addition, the stroke width and antialiasing mode can also be changed: ```c // Set the stroke width (must be an odd integer value) graphics_context_set_stroke_width(ctx, 5); // Disable antialiasing (enabled by default where available) graphics_context_set_antialiased(ctx, false); ``` ### Lines Drawing a simple line requires only the start and end positions, expressed as ``GPoint`` values: ```c GPoint start = GPoint(10, 10); GPoint end = GPoint(40, 60); // Draw a line graphics_draw_line(ctx, start, end); ``` ### Rectangles Drawing a rectangle requires a bounding ``GRect``, as well as other parameters if it is to be filled: ```c GRect rect_bounds = GRect(10, 10, 40, 60); // Draw a rectangle graphics_draw_rect(ctx, rect_bounds); // Fill a rectangle with rounded corners int corner_radius = 10; graphics_fill_rect(ctx, rect_bounds, corner_radius, GCornersAll); ``` It is also possible to draw a rounded unfilled rectangle: ```c // Draw outline of a rounded rectangle graphics_draw_round_rect(ctx, rect_bounds, corner_radius); ``` ### Circles Drawing a circle requries its center ``GPoint`` and radius: ```c GPoint center = GPoint(25, 25); uint16_t radius = 50; // Draw the outline of a circle graphics_draw_circle(ctx, center, radius); // Fill a circle graphics_fill_circle(ctx, center, radius); ``` In addition, it is possble to draw and fill arcs. In these cases, the ``GOvalScaleMode`` determines how the shape is adjusted to fill the rectangle, and the cartesian angle values are transformed to preserve accuracy: ```c int32_t angle_start = DEG_TO_TRIGANGLE(0); int32_t angle_end = DEG_TO_TRIGANGLE(45); // Draw an arc graphics_draw_arc(ctx, rect_bounds, GOvalScaleModeFitCircle, angle_start, angle_end); ``` Lastly, a filled circle with a sector removed can also be drawn in a similar manner. The value of `inset_thickness` determines the inner inset size that is removed from the full circle: ```c uint16_t inset_thickness = 10; // Fill a radial section of a circle graphics_fill_radial(ctx, rect_bounds, GOvalScaleModeFitCircle, inset_thickness, angle_start, angle_end); ``` For more guidance on using round elements in apps, watch the presentation given at the 2015 Developer Retreat on [developing for Pebble Time Round](https://www.youtube.com/watch?v=3a1V4n9HDvY). ## Bitmaps Manually drawing ``GBitmap`` images with the ``Graphics Context`` API is a simple task, and has much in common with the alternative approach of using a ``BitmapLayer`` (which provides additional convenience funcionality). The first step is to load the image data from resources (read {% guide_link app-resources/images %} to learn how to include images in a Pebble project): ```c static GBitmap *s_bitmap; ``` ```c // Load the image data s_bitmap = gbitmap_create_with_resource(RESOURCE_ID_EXAMPLE_IMAGE); ``` When the appropriate ``LayerUpdateProc`` is called, draw the image inside the desired rectangle: > Note: Unlike ``BitmapLayer``, the image will be drawn relative to the > ``Layer``'s origin, and not centered. ```c // Get the bounds of the image GRect bitmap_bounds = gbitmap_get_bounds(s_bitmap); // Set the compositing mode (GCompOpSet is required for transparency) graphics_context_set_compositing_mode(ctx, GCompOpSet); // Draw the image graphics_draw_bitmap_in_rect(ctx, s_bitmap, bitmap_bounds); ``` Once the image is no longer needed (i.e.: the app is exiting), free the data: ```c // Destroy the image data gbitmap_destroy(s_bitmap); ``` ## Drawing Text Similar to the ``TextLayer`` UI component, a ``LayerUpdateProc`` can also be used to draw text. Advantages can include being able to draw in multiple fonts with only one ``Layer`` and combining text with other drawing operations. The first operation to perform inside the ``LayerUpdateProc`` is to get or load the font to be used for drawing and set the text's color: ```c // Load the font GFont font = fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD); // Set the color graphics_context_set_text_color(ctx, GColorBlack); ``` Next, determine the bounds that will guide the text's position and overflow behavior. This can either be the size of the ``Layer``, or a more precise bounds of the text itself. This information can be useful for drawing multiple text items after one another with automatic spacing. ```c char *text = "Example test string for the Developer Website guide!"; // Determine a reduced bounding box GRect layer_bounds = layer_get_bounds(layer); GRect bounds = GRect(layer_bounds.origin.x, layer_bounds.origin.y, layer_bounds.size.w / 2, layer_bounds.size.h); // Calculate the size of the text to be drawn, with restricted space GSize text_size = graphics_text_layout_get_content_size(text, font, bounds, GTextOverflowModeWordWrap, GTextAlignmentCenter); ``` Finally, the text can be drawn into the appropriate bounding rectangle: ```c // Draw the text graphics_draw_text(ctx, text, font, bounds, GTextOverflowModeWordWrap, GTextAlignmentCenter, NULL); ```
{ "source": "google/pebble", "title": "devsite/source/_guides/graphics-and-animations/drawing-primitives-images-and-text.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/graphics-and-animations/drawing-primitives-images-and-text.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 8299 }
--- # Copyright 2025 Google LLC # # 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. title: Framebuffer Graphics description: | How to perform advanced drawing using direct framebuffer access. guide_group: graphics-and-animations order: 2 related_docs: - Graphics Context - GBitmap - GBitmapDataRowInfo --- In the context of a Pebble app, the framebuffer is the data region used to store the contents of the what is shown on the display. Using the ``Graphics Context`` API allows developers to draw primitive shapes and text, but at a slower speed and with a restricted set of drawing patterns. Getting direct access to the framebuffer allows arbitrary transforms, special effects, and other modifications to be applied to the display contents, and allows drawing at a much greater speed than standard SDK APIs. ## Accessing the Framebuffer Access to the framebuffer can only be obtained during a ``LayerUpdateProc``, when redrawing is taking place. When the time comes to update the associated ``Layer``, the framebuffer can be obtained as a ``GBitmap``: ```c static void layer_update_proc(Layer *layer, GContext *ctx) { // Get the framebuffer GBitmap *fb = graphics_capture_frame_buffer(ctx); // Manipulate the image data... // Finally, release the framebuffer graphics_release_frame_buffer(ctx, fb); } ``` > Note: Once obtained, the framebuffer **must** be released back to the app so > that it may continue drawing. The format of the data returned will vary by platform, as will the representation of a single pixel, shown in the table below. | Platform | Framebuffer Bitmap Format | Pixel Format | |:--------:|---------------------------|--------------| | Aplite | ``GBitmapFormat1Bit`` | One bit (black or white) | | Basalt | ``GBitmapFormat8Bit`` | One byte (two bits per color) | | Chalk | ``GBitmapFormat8BitCircular`` | One byte (two bits per color) | ## Modifying the Framebuffer Data Once the framebuffer has been captured, the underlying data can be manipulated on a row-by-row or even pixel-by-pixel basis. This data region can be obtained using ``gbitmap_get_data()``, but the recommended approach is to make use of ``gbitmap_get_data_row_info()`` objects to cater for platforms (such as Chalk), where not every row is of the same width. The ``GBitmapDataRowInfo`` object helps with this by providing a `min_x` and `max_x` value for each `y` used to build it. To iterate over all rows and columns, safely avoiding those with irregular start and end indices, use two nested loops as shown below. The implementation of `set_pixel_color()` is shown in [*Getting and Setting Pixels*](#getting-and-setting-pixels): > Note: it is only necessary to call ``gbitmap_get_data_row_info()`` once per > row. Calling it more often (such as for every pixel) will incur a sigificant > speed penalty. ```c GRect bounds = layer_get_bounds(layer); // Iterate over all rows for(int y = 0; y < bounds.size.h; y++) { // Get this row's range and data GBitmapDataRowInfo info = gbitmap_get_data_row_info(fb, y); // Iterate over all visible columns for(int x = info.min_x; x <= info.max_x; x++) { // Manipulate the pixel at x,y... const GColor random_color = (GColor){ .argb = rand() % 255 }; // ...to be a random color set_pixel_color(info, GPoint(x, y), random_color); } } ``` ## Getting and Setting Pixels To modify a pixel's value, simply set a new value at the appropriate position in the `data` field of that row's ``GBitmapDataRowInfo`` object. This will modify the underlying data, and update the display once the frame buffer is released. This process will be different depending on the ``GBitmapFormat`` of the captured framebuffer. On a color platform, each pixel is stored as a single byte. However, on black and white platforms this will be one bit per byte. Using ``memset()`` to read or modify the correct pixel on a black and white display requires a bit more logic, shown below: ```c static GColor get_pixel_color(GBitmapDataRowInfo info, GPoint point) { #if defined(PBL_COLOR) // Read the single byte color pixel return (GColor){ .argb = info.data[point.x] }; #elif defined(PBL_BW) // Read the single bit of the correct byte uint8_t byte = point.x / 8; uint8_t bit = point.x % 8; return byte_get_bit(&info.data[byte], bit) ? GColorWhite : GColorBlack; #endif } ``` Setting a pixel value is achieved in much the same way, with different logic depending on the format of the framebuffer on each platform: ```c static void set_pixel_color(GBitmapDataRowInfo info, GPoint point, GColor color) { #if defined(PBL_COLOR) // Write the pixel's byte color memset(&info.data[point.x], color.argb, 1); #elif defined(PBL_BW) // Find the correct byte, then set the appropriate bit uint8_t byte = point.x / 8; uint8_t bit = point.x % 8; byte_set_bit(&info.data[byte], bit, gcolor_equal(color, GColorWhite) ? 1 : 0); #endif } ``` The `byte_get_bit()` and `byte_set_bit()` implementations are shown here for convenience: ```c static bool byte_get_bit(uint8_t *byte, uint8_t bit) { return ((*byte) >> bit) & 1; } static void byte_set_bit(uint8_t *byte, uint8_t bit, uint8_t value) { *byte ^= (-value ^ *byte) & (1 << bit); } ``` ## Learn More To see an example of what can be achieved with direct access to the framebuffer and learn more about the underlying principles, watch the [talk given at the 2014 Developer Retreat](https://www.youtube.com/watch?v=lYoHh19RNy4). [EMBED](//www.youtube.com/watch?v=lYoHh19RNy4)
{ "source": "google/pebble", "title": "devsite/source/_guides/graphics-and-animations/framebuffer-graphics.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/graphics-and-animations/framebuffer-graphics.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 6074 }
--- # Copyright 2025 Google LLC # # 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. title: Graphics and Animations description: | Information on using animations and drawing shapes, text, and images, as well as more advanced techniques. guide_group: graphics-and-animations menu: false permalink: /guides/graphics-and-animations/ generate_toc: false hide_comments: true --- The Pebble SDK allows drawing of many types of graphics in apps. Using the ``Graphics Context``, ``GBitmap``, ``GDrawCommand`` and [`Framebuffer`](``graphics_capture_frame_buffer``) APIs gives developers complete control over the contents of the display, and also can be used to complement UI created with the various types of ``Layer`` available to enable more complex UI layouts. Both image-based and property-based animations are available, as well as scheduling regular updates to UI components with ``Timer`` objects. Creative use of ``Animation`` and ``PropertyAnimation`` can help to delight and engage users, as well as highlight important information inside apps. ## Contents {% include guides/contents-group.md group=page.group_data %}
{ "source": "google/pebble", "title": "devsite/source/_guides/graphics-and-animations/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/graphics-and-animations/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 1623 }
--- # Copyright 2025 Google LLC # # 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. title: Vector Graphics description: | How to draw simple images using vector images, instead of bitmaps. guide_group: graphics-and-animations order: 3 platform_choice: true related_docs: - Draw Commands related_examples: - title: PDC Image url: https://github.com/pebble-examples/pdc-image - title: PDC Sequence url: https://github.com/pebble-examples/pdc-sequence --- This is an overview of drawing vector images using Pebble Draw Command files. See the [*Vector Animations*](/tutorials/advanced/vector-animations) tutorial for more information. ## Vector Graphics on Pebble As opposed to bitmaps which contain data for every pixel to be drawn, a vector file contains only instructions about points contained in the image and how to draw lines connecting them up. Instructions such as fill color, stroke color, and stroke width are also included. Vector images on Pebble are implemented using the ``Draw Commands`` API, which allows apps to load and display PDC (Pebble Draw Command) images and sequences that contain sets of these instructions. An example is the weather icon used in weather timeline pins. The benefit of using vector graphics for this icon is that is allows the image to stretch in the familiar manner as it moves between the timeline view and the pin detail view: ![weather >{pebble-screenshot,pebble-screenshot--time-red}](/images/tutorials/advanced/weather.png) The main benefits of vectors over bitmaps for simple images and icons are: * Smaller resource size - instructions for joining points are less memory expensive than per-pixel bitmap data. * Flexible rendering - vector images can be rendered as intended, or manipulated at runtime to move the individual points around. This allows icons to appear more organic and life-like than static PNG images. Scaling and distortion is also made possible. However, there are also some drawbacks to choosing vector images in certain cases: * Vector files require more specialized tools to create than bitmaps, and so are harder to produce. * Complicated vector files may take more time to render than if they were simply drawn per-pixel as a bitmap, depending on the drawing implementation. ## Creating Compatible Files The file format of vector image files on Pebble is the PDC (Pebble Draw Command) format, which includes all the instructions necessary to allow drawing of vectors. These files are created from compatible SVG (Scalar Vector Graphics) files. Read {% guide_link app-resources/converting-svg-to-pdc %} for more information. <div class="alert alert--fg-white alert--bg-dark-red"> Pebble Draw Command files can only be used from app resources, and cannot be created at runtime. </div> ## Drawing Vector Graphics ^CP^ Add the PDC file as a project resource using the 'Add new' under 'Resources' on the left-hand side of the CloudPebble editor as a 'raw binary blob'. ^LC^ Add the PDC file to the project resources in `package.json` with the 'type' field to `raw`: <div class="platform-specific" data-sdk-platform="local"> {% highlight {} %} "media": [ { "type": "raw", "name": "EXAMPLE_IMAGE", "file": "example_image.pdc" } ] {% endhighlight %} </div> ^LC^ Drawing a Pebble Draw Command image is just as simple as drawing a normal PNG image to a graphics context, requiring only one draw call. First, load the `.pdc` file from resources as shown below. ^CP^ Drawing a Pebble Draw Command image is just as simple as drawing a normal PNG image to a graphics context, requiring only one draw call. First, load the `.pdc` file from resources, as shown below. First, declare a pointer of type ``GDrawCommandImage`` at the top of the file: ```c static GDrawCommandImage *s_command_image; ``` Create and assign the ``GDrawCommandImage`` in `init()`, before calling `window_stack_push()`: ```nc|c // Create the object from resource file s_command_image = gdraw_command_image_create_with_resource(RESOURCE_ID_EXAMPLE_IMAGE); ``` Next, define the ``LayerUpdateProc`` that will be used to draw the PDC image: ```c static void update_proc(Layer *layer, GContext *ctx) { // Set the origin offset from the context for drawing the image GPoint origin = GPoint(10, 20); // Draw the GDrawCommandImage to the GContext gdraw_command_image_draw(ctx, s_command_image, origin); } ``` Next, create a ``Layer`` to display the image: ```c static Layer *s_canvas_layer; ``` Assign the ``LayerUpdateProc`` that will do the rendering to the canvas ``Layer`` and add it to the desired ``Window`` during `window_load()`: ```c // Create the canvas Layer s_canvas_layer = layer_create(GRect(30, 30, bounds.size.w, bounds.size.h)); // Set the LayerUpdateProc layer_set_update_proc(s_canvas_layer, update_proc); // Add to parent Window layer_add_child(window_layer, s_canvas_layer); ``` Finally, don't forget to free the memory used by the sub-components of the ``Window`` in `main_window_unload()`: ```c // Destroy the canvas Layer layer_destroy(s_canvas_layer); // Destroy the PDC image gdraw_command_image_destroy(s_command_image); ``` When run, the PDC image will be loaded, and rendered in the ``LayerUpdateProc``. To put the image into contrast, optionally change the ``Window`` background color after `window_create()`: ```c window_set_background_color(s_main_window, GColorBlueMoon); ``` The result will look similar to the example shown below. ![weather-image >{pebble-screenshot,pebble-screenshot--time-red}](/images/tutorials/advanced/weather-image.png)
{ "source": "google/pebble", "title": "devsite/source/_guides/graphics-and-animations/vector-graphics.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/graphics-and-animations/vector-graphics.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 6087 }
--- # Copyright 2025 Google LLC # # 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. title: SDK 3.x on Aplite Migration Guide description: How to migrate apps that use SDK 2.x on Aplite to SDK 3.x permalink: /guides/migration/3x-aplite-migration/ generate_toc: true guide_group: migration order: 3 --- With the release of SDK 3.8, all Pebble platforms can be targeted with one SDK. This enables developers to make use of lots of new APIs added since SDK 2.9, as well as the countless bug fixes and improvements also added in the intervening time. Some examples are: * Timezone support * Sequence and spawn animations * Pebble timeline support * Pebble Draw Commands * Native PNG image support * 8k `AppMessage` buffers * New UI components such as `ActionMenu`, `StatusBarLayer`, and `ContentIndicator`. * The stroke width, drawing arcs, polar points APIs, and the color gray! ## Get the Beta SDK To try out the beta SDK, read the instructions on the [SDK Beta](/sdk/beta) page. ## Mandatory Changes To be compatible with users who update their Pebble Classic or Pebble Steel to firmware 3.x the following important changes **MUST** be made: * If you are adding support for Aplite, add `aplite` to your `targetPlatforms` array in `package.json`, or tick the 'Build Aplite' box in 'Settings' on CloudPebble. * Recompile your app with at least Pebble SDK 3.8 (coming soon!). The 3.x on Aplite files will reside in `/aplite/` instead of the `.pbw` root folder. Frankenpbws are **not** encouraged - a 2.x compatible release can be uploaded separately (see [*Appstore Changes*](#appstore-changes)). * Update any old practices such as direct struct member access. An example is shown below: ```c // 2.x - don't do this! GRect bitmap_bounds = s_bitmap->bounds; // 3.x - please do this! GRect bitmap_bounds = gbitmap_get_bounds(s_bitmap); ``` * Apps that make use of the `png-trans` resource type should now make use of built-in PNG support, which allows a single black and white image with transparency to be used in place of the older compositing technique. * If your app uses either the ``Dictation`` or ``Smartstrap`` APIs, you must check that any code dependant on these hardware features fails gracefully when they are not available. This should be done by checking for `NULL` or appropriate `enum` values returned from affected API calls. An example is shown below: ```c if(smartstrap_subscribe(handlers) != SmartstrapResultNotPresent) { // OK to use Smartstrap API! } else { // Not available, handle gracefully text_layer_set_text(s_text_layer, "Smartstrap not available!"); } DictationSession *session = dictation_session_create(size, callback, context); if(session) { // OK to use Dictation API! } else { // Not available, handle gracefully text_layer_set_text(s_text_layer, "Dictation not available!"); } ``` ## Appstore Changes To handle the transition as users update their Aplite to firmware 3.x (or choose not to), the appstore will include the following changes: * You can now have multiple published releases. When you publish a new release, it doesn’t unpublish the previous one. You can still manually unpublish releases whenever they want. * The appstore will provide the most recently compatible release of an app to users. This means that if you publish a new release that has 3.x Aplite support, the newest published release that supports 2.x Aplite will be provided to users on 2.x Aplite. * There will be a fourth Asset Collection type that you can create: Legacy Aplite. Apps that have different UI designs between 2.x and 3.x on Aplite should use the Legacy Aplite asset collection for their 2.x assets. ## Suggested Changes To fully migrate to SDK 3.x, we also suggest you make these nonessential changes: * Remove any code conditionally compiled with `PBL_SDK_2` defines. It will no longer be compiled at all. * Ensure that any use of ``app_message_inbox_size_maximum()`` and ``app_message_outbox_size_maximum()`` does not cause your app to run out of memory. These calls now create ``AppMessage`` buffers of 8k size by default. Aplite apps limited to 24k of RAM will quickly run out if they use much more memory. * Colors not available on the black and white Aplite display will be silently displayed as the closet match (black, or white). We recommend checking every instance of a `GColor`to ensure each is the correct one. `GColorDarkGray` and `GColorLightGray` will result in a 50/50 dithered gray for **fill** operations. All other line and text drawing will be mapped to the nearest solid color (black or white). * Apps using image resources should take advantage of the new `bitmap` resource type, which optimizes image files for you. Read the [*Unifying Bitmap Resources*](/blog/2015/12/02/Bitmap-Resources/) blog post to learn more. * In addition to the point above, investigate how the contrast and readability of your app can be improved by making use of gray. Examples of this can be seen in the system UI: ![3x-aplite-system >{pebble-screenshot,pebble-screenshot--black}](/images/guides/migration/3x-aplite-system.png)
{ "source": "google/pebble", "title": "devsite/source/_guides/migration/3x-aplite-migration.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/migration/3x-aplite-migration.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 5750 }
--- # Copyright 2025 Google LLC # # 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. title: Migrating Older Apps description: | Details on how to update older apps affected by API changes. guide_group: migration menu: false permalink: /guides/migration/ generate_toc: false hide_comments: true --- When the Pebble SDK major version is increased (such as from 2.x to 3.x), some breaking API and build process changes are made. This means that some apps written for an older SDK may no longer compile with the newer one. To help developers transition their code, these guides detail the specific changes they should look out for and highlighting the changes to APIs they may have previously been using. When breaking changes are made in the future, new guides will be added here to help developers make the required changes. ## Contents {% include guides/contents-group.md group=page.group_data %}
{ "source": "google/pebble", "title": "devsite/source/_guides/migration/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/migration/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 1396 }
--- # Copyright 2025 Google LLC # # 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. title: SDK 3.x Migration Guide description: Migrating Pebble apps from SDK 2.x to SDK 3.x. permalink: /guides/migration/migration-guide-3/ generate_toc: true guide_group: migration order: 2 --- This guide provides a detailed list of the changes to existing APIs in Pebble SDK 3.x. To migrate an older app's code successfully from Pebble SDK 2.x to Pebble SDK 3.x, consider the information outlined here and make the necessary changes if the app uses a changed API. The number of breaking changes in SDK 3.x for existing apps has been minimized as much as possible. This means that: * Apps built with SDK 2.x **will continue to run on firmware 3.x without any recompilation needed**. * Apps built with SDK 3.x will generate a `.pbw` file that will run on firmware 3.x. ## Backwards Compatibility Developers can easily modify an existing app (or create a new one) to be compilable for both Pebble/Pebble Steel as well as Pebble Time, Pebble Time Steel, and Pebble Time Round by using `#ifdef` and various defines that are made available by the SDK at build time. For example, to check that the app will run on hardware supporting color: ```c #ifdef PBL_COLOR window_set_background_color(s_main_window, GColorDukeBlue); #else window_set_background_color(s_main_window, GColorBlack); #endif ``` When the app is compiled, it will be built once for each platform with `PBL_COLOR` defined as is appropriate. By catering for all cases, apps will run and look good on both platforms with minimal effort. This avoids the need to maintain two Pebble projects for one app. In addition, as of Pebble SDK 3.6 there are macros that can be used to selectively include code in single statements. This is an alternative to the approach shown above using `#ifdef`: ```c window_set_background_color(s_main_window, PBL_IF_COLOR_ELSE(GColorDukeBlue, GColorBlack)); ``` See {% guide_link best-practices/building-for-every-pebble %} to learn more about these macros, as well as see a complete list. ## PebbleKit Considerations Apps that use PebbleKit Android will need to be re-compiled in Android Studio (or similar) with the PebbleKit Android **3.x** (see {% guide_link communication/using-pebblekit-android %}) library in order to be compatible with the Pebble Time mobile application. No code changes are required, however. PebbleKit iOS developers remain unaffected and their apps will continue to run with the new Pebble mobile application. However, iOS companion apps will need to be recompiled with PebbleKit iOS **3.x** (see {% guide_link migration/pebblekit-ios-3 "PebbleKit iOS 3.0 Migration Guide" %}) to work with Pebble Time Round. ## Changes to appinfo.json There is a new field for tracking which version of the SDK the app is built for. For example, when using 3.x SDK add this line to the project's `appinfo.json`. ``` "sdkVersion": "3" ``` Apps will specify which hardware platforms they support (and wish to be built for) by declaring them in the `targetPlatforms` field of the project's `appinfo.json` file. ``` "targetPlatforms": [ "aplite", "basalt", "chalk" ] ``` For each platform listed here, the SDK will generate an appropriate binary and resource pack that will be included in the `.pbw` file. This means that the app is actually compiled and resources are optimized once for each platform. The image below summarizes this build process: ![build process](/images/sdk/build-process-3.png) > Note: If `targetPlatforms` is not specified in `appinfo.json` the app will be > compiled for all platforms. Apps can also elect to not appear in the app menu on the watch (if is is only pushing timeline pins, for example) by setting `hiddenApp`: ``` "watchapp": { "watchface": false, "hiddenApp": true }, ``` ## Project Resource Processing SDK 3.x enhances the options for adding image resources to a Pebble project, including performing some pre-processing of images into compatible formats prior to bundling. For more details on the available resource types, check out the {% guide_link app-resources %} section of the guides. ## Platform-specific Resources **Different Resources per Platform** It is possible to include different versions of resources on only one of the platforms with a specific type of display. Do this by appending `~bw` or `~color` to the name of the resource file and the SDK will prefer that file over another with the same name, but lacking the suffix. This means is it possible to can include a smaller black and white version of an image by naming it `example-image~bw.png`, which will be included in the appropriate build over another file named `example-image.png`. In a similar manner, specify a resource for a color platform by appending `~color` to the file name. An example file structure is shown below. ```text my-project/ resources/ images/ example-image~bw.png example-image~color.png src/ main.c appinfo.json wscript ``` This resource will appear in `appinfo.json` as shown below. ``` "resources": { "media": [ { "type": "bitmap", "name": "EXAMPLE_IMAGE", "file": "images/example-image.png" } ] } ``` Read {% guide_link app-resources/platform-specific %} for more information about specifying resources per-platform. **Single-platform Resources** To only include a resource on a **specific** platform, add a `targetPlatforms` field to the resource's entry in the `media` array in `appinfo.json`. For example, the resource shown below will only be included for the Basalt build. ``` "resources": { "media": [ { "type": "bitmap", "name": "BACKGROUND_IMAGE", "file": "images/background.png", "targetPlatforms": [ "basalt" ] } ] } ``` ## Changes to wscript To support compilation for multiple hardware platforms and capabilities, the default `wscript` file included in every Pebble project has been updated. If a project uses a customized `wscript` file and `pebble convert-project` is run (which will fully replace the file with a new compatible version), the `wscript` will be copied to `wscript.backup`. View [this GitHub gist](https://gist.github.com/pebble-gists/72a1a7c85980816e7f9b) to see a sample of what the new format looks like, and re-add any customizations afterwards. ## Changes to Timezones With SDK 2.x, all time-related SDK functions returned values in local time, with no concept of timezones. With SDK 3.x, the watch is aware of the user's timezone (specified in Settings), and will return values adjusted for this value. ## API Changes Quick Reference ### Compatibility Macros Since SDK 3.0-dp2, `pebble.h` includes compatibility macros enabling developers to use the new APIs to access fields of opaque structures and still be compatible with both platforms. An example is shown below: ```c static GBitmap *s_bitmap; ``` ```c // SDK 2.9 GRect bounds = s_bitmap->bounds; // SDK 3.x GRect bounds = gbitmap_get_bounds(s_bitmap); ``` ### Comparing Colors Instead of comparing two GColor values directly, use the new ``gcolor_equal`` function to check for identical colors. ```c GColor a, b; // SDK 2.x, bad if (a == b) { } // SDK 3.x, good if (gcolor_equal(a, b)) { } ``` > Note: Two colors with an alpha transparency(`.a`) component equal to `0` > (completely transparent) are considered as equal. ### Assigning Colors From Integers Specify a color previously stored as an `int` and convert it to a `GColor`: ```c GColor a; // SDK 2.x a = (GColor)persist_read_int(key); // SDK 3.x a.argb = persist_read_int(key); /* OR */ a = (GColor){.argb = persist_read_int(key)}; ``` ### Specifying Black and White The internal representation of SDK 2.x colors such as ``GColorBlack`` and ``GColorWhite`` have changed, but they can still be used with the same name. ### PebbleKit JS Account Token In SDK 3.0 the behavior of `Pebble.getAccountToken()` changes slightly. In previous versions, the token returned on Android could differ from that returned on iOS by dropping some zero characters. The table below shows the different tokens received for a single user across platforms and versions: | Platform | Token | |:---------|-------| | iOS 2.6.5 | 29f00dd7872ada4bd14b90e5d49568a8 | | iOS 3.x | 29f00dd7872ada4bd14b90e5d49568a8 | | Android 2.3 | 29f0dd7872ada4bd14b90e5d49568a8 | | Android 3.x | 29f00dd7872ada4bd14b90e5d49568a8 | > Note: This process should **only** be applied to new tokens obtained from > Android platforms, to compare to tokens from older app versions. To account for this difference, developers should adapt the new account token as shown below. **JavaScript** ```js function newToOld(token) { return token.split('').map(function (x, i) { return (x !== '0' || i % 2 == 1) ? x : ''; }).join(''); } ``` **Python** ```python def new_to_old(token): return ''.join(x for i, x in enumerate(token) if x != '0' or i % 2 == 1) ``` **Ruby** ```ruby def new_to_old(token) token.split('').select.with_index { |c, i| (c != '0' or i % 2 == 1) }.join('') end ``` **PHP** <div> {% highlight { "language": "php", "options": { "startinline": true } } %} function newToOld($token) { $array = str_split($token); return implode('', array_map(function($char, $i) { return ($char !== '0' || $i % 2 == 1) ? $char : ''; }, $array, array_keys($array))); } {% endhighlight %} </div> ### Using the Status Bar To help apps integrate aesthetically with the new system experience, all ``Window``s are now fullscreen-only in SDK 3.x. To keep the time-telling functionality, developers should use the new ``StatusBarLayer`` API in their `.load` handler. > Note: Apps built with SDK 2.x will still keep the system status bar unless > specified otherwise with `window_set_fullscreen(window, true)`. As a result, > such apps that have been recompiled will be shifted up sixteen pixels, and > should account for this in any window layouts. ```c static StatusBarLayer *s_status_bar; ``` ```c static void main_window_load(Window *window) { Layer *window_layer = window_get_root_layer(window); /* other UI code */ // Set up the status bar last to ensure it is on top of other Layers s_status_bar = status_bar_layer_create(); layer_add_child(window_layer, status_bar_layer_get_layer(s_status_bar)); } ``` By default, the status bar will look the same as it did on 2.x, minus the battery meter. ![status-bar-default >{pebble-screenshot,pebble-screenshot--time-red}](/images/sdk/status-bar-default.png) To display the legacy battery meter on the Basalt platform, simply add an additional ``Layer`` after the ``StatusBarLayer``, and use the following code in its ``LayerUpdateProc``. ```c static void battery_proc(Layer *layer, GContext *ctx) { // Emulator battery meter on Aplite graphics_context_set_stroke_color(ctx, GColorWhite); graphics_draw_rect(ctx, GRect(126, 4, 14, 8)); graphics_draw_line(ctx, GPoint(140, 6), GPoint(140, 9)); BatteryChargeState state = battery_state_service_peek(); int width = (int)(float)(((float)state.charge_percent / 100.0F) * 10.0F); graphics_context_set_fill_color(ctx, GColorWhite); graphics_fill_rect(ctx, GRect(128, 6, width, 4), 0, GCornerNone); } ``` ```c static void main_window_load(Window *window) { Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_bounds(window_layer); /* other UI code */ // Set up the status bar last to ensure it is on top of other Layers s_status_bar = status_bar_layer_create(); layer_add_child(window_layer, status_bar_layer_get_layer(s_status_bar)); // Show legacy battery meter s_battery_layer = layer_create(GRect(bounds.origin.x, bounds.origin.y, bounds.size.w, STATUS_BAR_LAYER_HEIGHT)); layer_set_update_proc(s_battery_layer, battery_proc); layer_add_child(window_layer, s_battery_layer); } ``` > Note: To update the battery meter more frequently, use ``layer_mark_dirty()`` > in a ``BatteryStateService`` subscription. Unless the current ``Window`` is > long-running, this should not be neccessary. The ``StatusBarLayer`` can also be extended by the developer in similar ways to the above. The API also allows setting the layer's separator mode and foreground/background colors: ```c status_bar_layer_set_separator_mode(s_status_bar, StatusBarLayerSeparatorModeDotted); status_bar_layer_set_colors(s_status_bar, GColorClear, GColorWhite); ``` This results in a a look that is much easier to integrate into a color app. ![status-bar-color >{pebble-screenshot,pebble-screenshot--time-red}](/images/sdk/status-bar-color.png) ### Using PropertyAnimation The internal structure of ``PropertyAnimation`` has changed, but it is still possible to access the underlying ``Animation``: ```c // SDK 2.x Animation *animation = &prop_animation->animation; animation = (Animation*)prop_animation; // SDK 3.x Animation *animation = property_animation_get_animation(prop_animation); animation = (Animation*)prop_animation; ``` Accessing internal fields of ``PropertyAnimation`` has also changed. For example, to access the ``GPoint`` in the `from` member of an animation: ```c GPoint p; PropertyAnimation *prop_anim; // SDK 2.x prop_animation->values.from.gpoint = p; // SDK 3.x property_animation_set_from_gpoint(prop_anim, &p); ``` Animations are now automatically freed when they have finished. This means that code using ``animation_destroy()`` should be corrected to no longer do this manually when building with SDK 3.x, which will fail. **SDK 2.x code must still manually free Animations as before.** Developers can now create complex synchronized and chained animations using the new features of the Animation Framework. Read {% guide_link graphics-and-animations/animations %} to learn more. ### Accessing GBitmap Members ``GBitmap`` is now opaque, so accessing structure members directly is no longer possible. However, direct references to members can be obtained with the new accessor functions provided by SDK 3.x: ```c static GBitmap *s_bitmap = gbitmap_create_with_resource(RESOURCE_ID_EXAMPLE_IMAGE); // SDK 2.x GRect image_bounds = s_bitmap->bounds; // SDK 3.x GRect image_bounds = gbitmap_get_bounds(s_bitmap); ``` ### Drawing Rotated Bitmaps <div class="alert alert--fg-white alert--bg-dark-red"> {% markdown %} The bitmap rotation API requires a significant amount of CPU power and will have a substantial effect on users' battery life. There will also be a large reduction in performance of the app and a lower framerate may be seen. Use alternative drawing methods such as ``Draw Commands`` or [`GPaths`](``GPath``) wherever possible. {% endmarkdown %%} </div> Alternatively, draw a ``GBitmap`` with a rotation angle and center point inside a ``LayerUpdateProc`` using ``graphics_draw_rotated_bitmap()``. ### Using InverterLayer SDK 3.x deprecates the `InverterLayer` UI component which was primarily used for ``MenuLayer`` highlighting. Developers can now make use of `menu_cell_layer_is_highlighted()` inside a ``MenuLayerDrawRowCallback`` to determine which text and selection highlighting colors they prefer. > Using this for determining highlight behaviour is preferable to using > ``menu_layer_get_selected_index()``. Row drawing callbacks may be invoked > multiple times with a different highlight status on the same cell in order to > handle partially highlighted cells during animation.
{ "source": "google/pebble", "title": "devsite/source/_guides/migration/migration-guide-3.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/migration/migration-guide-3.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 16076 }
--- # Copyright 2025 Google LLC # # 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. title: SDK 4.x Migration Guide description: Migrating Pebble apps from SDK 3.x to SDK 4.x. permalink: /guides/migration/migration-guide-4/ generate_toc: true guide_group: migration order: 4 --- This guide provides details of the changes to existing APIs in Pebble SDK 4.x. To migrate an older app's code successfully from Pebble SDK 3.x to Pebble SDK 4.x, consider the information outlined here and make the necessary changes if the app uses a changed API. The number of breaking changes in SDK 4.x for existing apps has been minimized as much as possible. This means that: * Apps built with SDK 3.x **will continue to run on firmware 4.x without any recompilation needed**. * Apps built with SDK 4.x will generate a `.pbw` file that will run on firmware 4.x. ## New APIs * ``AppExitReason`` - API for the application to notify the system of the reason it will exit. * ``App Glance`` - API for the application to modify its glance. * ``UnobstructedArea`` - Detect changes to the available screen real-estate based on obstructions. ## Timeline Quick View Although technically not a breaking change, the timeline quick view feature will appear overlayed on a watchface which may impact the visual appearance and functionality of a watchface. Developers should read the {% guide_link user-interfaces/unobstructed-area "UnobstructedArea guide%} to learn how to adapt their watchface to handle obstructions. ## appinfo.json Since the [introduction of Pebble Packages in June 2016](/blog/2016/06/07/pebble-packages/), the `appinfo.json` file has been deprecated and replaced with `package.json`. Your project can automatically be converted when you run `pebble convert-project` inside your project folder. You can read more about the `package.json` file in the {% guide_link tools-and-resources/app-metadata "App Metadata" %} guide. ## Launcher Icon The new launcher in 4.0 allows developers to provide a custom icon for their watchapps and watchfaces. <div class="pebble-dual-image"> <div class="panel"> {% markdown %} ![Launcher Icon](/images/blog/2016-08-19-pikachu-icon.png) {% endmarkdown %} </div> <div class="panel"> {% markdown %} ![Launcher >{pebble-screenshot,pebble-screenshot--time-red}](/images/blog/2016-08-19-pikachu-launcher.png) {% endmarkdown %} </div> </div> > If your `png` file is color, we will use the luminance of the image to add > some subtle gray when rendering it in the launcher, rather than just black > and white. Transparency will be preserved. You should add a 25x25 `png` to the `resources.media` section of the `package.json` file, and set `"menuIcon": true`. Please note that icons that are larger will be ignored and your app will have the default icon instead. ```js "resources": { "media": [ { "menuIcon": true, "type": "png", "name": "IMAGE_MENU_ICON", "file": "images/icon.png" } ] } ```
{ "source": "google/pebble", "title": "devsite/source/_guides/migration/migration-guide-4.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/migration/migration-guide-4.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 3479 }
--- # Copyright 2025 Google LLC # # 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. title: SDK 2.x Migration Guide description: Migrating Pebble apps from SDK 1.x to SDK 2.x. permalink: /guides/migration/migration-guide/ generate_toc: true guide_group: migration order: 1 --- {% alert important %} This page is outdated, intended for updating SDK 1.x apps to SDK 2.x. All app should now be created with SDK 3.x. For migrating an app from SDK 2.x to SDK 3.x, the read {% guide_link migration/migration-guide-3 %}. {% endalert %} ## Introduction This guide provides you with a summary and a detailed list of the changes, updates and new APIs available in Pebble SDK 2.0. To migrate your code successfully from Pebble SDK 1.x to Pebble SDK 2.x, you should read this guide. In addition to updated and new Pebble APIs, you'll find updated developer tools and a simplified build system that makes it easier to create, build, and deploy Pebble apps. **Applications written for Pebble SDK 1.x do not work on Pebble 2.0.** It is extremely important that you upgrade your apps, so that your users can continue to enjoy your watchfaces and watchapps. These are the essential steps to perform the upgrade: * You'll need to upgrade Pebble SDK on your computer, the firmware on your Pebble, and the Pebble mobile application on your phone. * You need to upgrade the `arm-cs-tools`. The version shipped with Pebble SDK 2 contains several important improvements that help reduce the size of the binaries generated and improve the performance of your app. * You need to upgrade the python dependencies `pip install --user -r {{ site.pb_sdk_path }}{{ site.pb_sdk2_package }}/requirements.txt`). ## Discovering the new Pebble tools (Native SDK only) One of the new features introduced in Pebble native SDK 2.0 is the `pebble` command line tool. This tool is used to create new apps, build and install those apps on your Pebble. The tool was designed to simplify and optimize the build process for your Pebble watchfaces and watchapps. Give it a try right now: ```c $ pebble new-project helloworld $ cd helloworld $ ls appinfo.json resources src wscript ``` Notice that the new SDK does not require symlinks as the earlier SDK did. There is also a new `appinfo.json` file, described in greater detail later in this guide. The file provides you with a more readable format and includes all the metadata about your app. ```c $ pebble build ... Memory usage: ============= Total app footprint in RAM: 801 bytes / ~24kb Free RAM available (heap): 23775 bytes [12/13] inject-metadata: build/pebble-app.raw.bin build/app_resources.pbpack.data -> build/pebble-app.bin [13/13] helloworld.pbw: build/pebble-app.bin build/app_resources.pbpack -> build/helloworld.pbw ... 'build' finished successfully (0.562s) ``` You don't need to call the `waf` tool to configure and then build the project anymore (`pebble` still uses `waf`, however). The new SDK also gives you some interesting information on how much memory your app will use and how much memory will be left for you in RAM. ```c $ pebble install --phone 10.0.64.113 --logs [INFO ] Installation successful [INFO ] Enabling application logging... [INFO ] Displaying logs ... Ctrl-C to interrupt. [INFO ] D helloworld.c:58 Done initializing, pushed window: 0x2001a524 ``` Installing an app with `pebble` is extremely simple. It uses your phone and the official Pebble application as a gateway. You do need to configure your phone first, however. For more information on working with this tool, read {% guide_link tools-and-resources/pebble-tool %}. You don't need to run a local HTTP server or connect with Bluetooth like you did with SDK 1.x. You will also get logs sent directly to the console, which will make development a lot easier! ## Upgrading a 1.x app to 2.0 Pebble 2.0 is a major release with many changes visible to users and developers and some major changes in the system that are not visible at first sight but will have a strong impact on your apps. Here are the biggest changes in Pebble SDK 2.0 that will impact you when migrating your app. The changes are discussed in more detail below: * Every app now requires an `appinfo.json`, which includes your app name, UUID, resources and a few other new configuration parameters. For more information, refer to {% guide_link tools-and-resources/app-metadata %}. * Your app entry point is called `main()` and not `pbl_main()`. * Most of the system structures are not visible to apps anymore, and instead of allocating the memory yourself, you ask the system to allocate the memory and return a pointer to the structure. > This means that you'll have to change most of your system calls and > significantly rework your app. This change was required to allow us to > update the structs in the future (for example, to add new fields in them) > without forcing you to recompile your app code. * Pebble has redesigned many APIs to follow standard C best practices and futureproof the SDK. ### Application metadata To upgrade your app for Pebble SDK 2.0, you should first run the `pebble convert-project` command in your existing 1.x project. This will automatically try to generate the `appinfo.json` file based on your existing source code and resource file. It will not touch your C code. Please review your `appinfo.json` file and make sure everything is OK. If it is, you can safely remove the UUID and the `PBL_APP_INFO` in your C file. Refer to {% guide_link tools-and-resources/app-metadata %} for more information on application metadata and the basic structure of an app in Pebble SDK 2.0. ### Pebble Header files In Pebble SDK 1.x, you would reference Pebble header files with three include statements: ```c #include "pebble_os.h" #include "pebble_app.h" #include "pebble_fonts.h" ``` In Pebble SDK 2.x, you can replace them with one statement: ```c #include <pebble.h> ``` ### Initializing your app In Pebble SDK 1.x, your app was initialized in a `pbl_main()` function: ```c void pbl_main(void *params) { PebbleAppHandlers handlers = { .init_handler = &handle_init }; app_event_loop(params, &handlers); } ``` In Pebble SDK 2.0: * `pbl_main` is replaced by `main`. * The `PebbleAppHandlers` structure no longer exists. You call your init and destroy handlers directly from the `main()` function. ```c int main(void) { handle_init(); app_event_loop(); handle_deinit(); } ``` There were other fields in the `PebbleAppHandlers`: * `PebbleAppInputHandlers`: Use a ``ClickConfigProvider`` instead. * `PebbleAppMessagingInfo`: Refer to the section below on ``AppMessage`` changes. * `PebbleAppTickInfo`: Refer to the section below on Tick events. * `PebbleAppTimerHandler`: Refer to the section below on ``Timer`` events. * `PebbleAppRenderEventHandler`: Use a ``Layer`` and call ``layer_set_update_proc()`` to provide your own function to render. ### Opaque structures and Dynamic Memory allocation In Pebble SDK 2.0, system structures are opaque and your app can't directly allocate memory for them. Instead, you use system functions that allocate memory and initialize the structure at the same time. #### Allocating dynamic memory: A simple example In Pebble SDK 1.x, you would allocate memory for system structures inside your app with static global variables. For example, it was very common to write: ```c Window my_window; TextLayer text_layer; void handle_init(AppContextRef ctx) { window_init(&my_window, "My App"); text_layer_init(&text_layer, GRect(0, 0, 144, 20)); } ``` In Pebble SDK 2, you can't allocate memory statically in your program because the compiler doesn't know at compile time how big the system structures are (here, in the above code snippet ``Window`` and ``TextLayer``). Instead, you use pointers and ask the system to allocate the memory for you. This simple example becomes: ```c Window *my_window; TextLayer *text_layer; void handle_init(void) { my_window = window_create(); text_layer = text_layer_create(GRect(0, 0, 144, 20)); } ``` Instead of using `*_init()` functions and passing them a pointer to the structure, in SDK 2.0, you call functions that end in `_create()`, and these functions will allocate memory and return to your app a pointer to a structure that is initialized. Because the memory is dynamically allocated, it is extremely important that you release that memory when you are finished using the structure. This can be done with the `*_destroy()` functions. For our example, we could write: ```c void handle_deinit(void) { text_layer_destroy(text_layer); window_destroy(my_window); } ``` #### Dynamic memory: General rules in Pebble SDK 2.0 * Replace all statically allocated system structures with a pointer to the structure. * Replace functions that ended in `_init()` with their equivalent that end in `_create()`. * Keep pointers to the structures that you have initialized. Call the `*_destroy()` functions to release the memory. ### AppMessage changes * Instead of defining your buffer sizes in `PebbleAppMessagingInfo`, you pass them to ``app_message_open()`` * Instead of using a `AppMessageCallbacksNode` structure and `app_message_register_callbacks()`, you register handler for the different ``AppMessage`` events with: * ``app_message_register_inbox_received()`` * ``app_message_register_inbox_dropped()`` * ``app_message_register_outbox_failed()`` * ``app_message_register_outbox_sent()`` * ``app_message_set_context(void *context)``: To set the context that will be passed to all the handlers. * `app_message_out_get()` is replaced by ``app_message_outbox_begin()``. * `app_message_out_send()` is replaced by ``app_message_outbox_send()``. * `app_message_out_release()` is removed. You do not need to call this anymore. For more information, please review the ``AppMessage`` API Documentation. For working examples using AppMessage and AppSync in SDK 2.0, refer to: * `{{ site.pb_sdk2_package }}/PebbleSDK-2.x/Examples/pebblekit-js/quotes`: Demonstrates how to use PebbleKit JS to fetch price quotes from the web. It uses AppMessage on the C side. * `{{ site.pb_sdk2_package }}/PebbleSDK-2.x/Examples/pebblekit-js/weather`: A PebbleKit JS version of the traditional `weather-demo` example. It uses AppSync on the C side. ### Dealing with Tick events Callbacks for tick events can't be defined through `PebbleAppHandlers` anymore. Instead, use the Tick Timer Event service with: ``tick_timer_service_subscribe()``. For more information, read {% guide_link events-and-services/events %}/ ### Timer changes `app_timer_send_event()` is replaced by ``app_timer_register()``. For more information, refer to the ``Timer`` API documentation. ### WallTime API changes * `PblTm` has been removed and replaced by the libc standard struct. Use struct `tm` from `#include <time.h>`. * `tm string_format_time()` function is replaced by ``strftime()``. * `get_time()` is replaced by `localtime(time(NULL))`. This lets you convert a timestamp into a struct. * Pebble OS does not, as yet, support timezones. However, Pebble SDK 2 introduces `gmtime()` and `localtime()` functions to prepare for timezone support. ### Click handler changes In SDK 1.x, you would set up click handlers manually by modifying an array of config structures to contain the desired configuration. In SDK 2.x, how click handlers are registered and used has changed. The following functions for subscribing to events have been added in SDK 2.x: ```c void window_set_click_context(); void window_single_click_subscribe(); void window_single_repeating_click_subscribe(); void window_multi_click_subscribe(); void window_multi_click_subscribe(); void window_long_click_subscribe(); void window_raw_click_subscribe(); ``` For more information, refer to the ``Window`` API documentation. For example, in SDK 1.x you would do this: ```c void click_config_provider(ClickConfig **config, void *context) { config[BUTTON_ID_UP]->click.handler = up_click_handler; config[BUTTON_ID_UP]->context = context; config[BUTTON_ID_UP]->click.repeat_interval_ms = 100; config[BUTTON_ID_SELECT]->click.handler = select_click_handler; config[BUTTON_ID_DOWN]->multi_click.handler = down_click_handler; config[BUTTON_ID_DOWN]->multi_click.min = 2; config[BUTTON_ID_DOWN]->multi_click.max = 10; config[BUTTON_ID_DOWN]->multi_click.timeout = 0; /* default timeout */ config[BUTTON_ID_DOWN]->multi_click.last_click_only = true; config[BUTTON_ID_SELECT]->long_click.delay_ms = 1000; config[BUTTON_ID_SELECT]->long_click.handler = select_long_click_handler; } ``` In SDK 2.x, you would use the following calls instead: ```c void click_config_provider(void *context) { window_set_click_context(BUTTON_ID_UP, context); window_single_repeating_click_subscribe(BUTTON_ID_UP, 100, up_click_handler); window_single_click_subscribe(BUTTON_ID_SELECT, select_click_handler); window_multi_click_subscribe(BUTTON_ID_DOWN, 2, 10, 0, true, down_click_handler); window_long_click_subscribe(BUTTON_ID_SELECT, 1000, select_long_click_handler, NULL /* No handler on button release */); } ``` Notice that the signature of ``ClickConfigProvider`` has also changed. These ``Clicks`` API functions **must** be called from within the ClickConfigProvider function. If they are not, your app code will fail. ### Other changes * `graphics_text_draw()` has been renamed to ``graphics_draw_text()``, matching the rest of Pebble's graphics_draw_ functions. There are no changes with the usage of the function. ## Quick reference for the upgrader **Table 1. API changes from SDK 1.x to 2.x** API Call in SDK 1.x | API Call in SDK 2.x | :-----------|:------------| `#define APP_TIMER_INVALID_HANDLE ((AppTimerHandle)0)` | Changed. No longer needed; `app_timer_register()` always succeeds. See [``Timer``. `#define INT_MAX 32767` | Changed. See `#include <limits.h>` `AppTimerHandle app_timer_send_event();` | See ``app_timer_register()`` for more information at ``Timer``. `ARRAY_MAX` | Removed from Pebble headers. Now use limits.h `bool app_timer_cancel_event();` | Changed. See ``app_timer_cancel()`` for more information at ``Timer``. `GContext *app_get_current_graphics_context();` | Removed. Use the context supplied to you in the drawing callbacks. `GSize text_layer_get_max_used_size();` | Use ``text_layer_get_content_size()``. See ``TextLayer``. `INT_MAX` | Removed from Pebble headers. Now use limits.h `void get_time();` | Use `localtime(time(NULL))` from `#include <time.h>`. `void resource_init_current_app();` | No longer needed. `void string_format_time();` | Use ``strftime`` from `#include <time.h>`. `void window_render();` | No longer available. ### Using `*_create()/*_destroy()` instead of `*_init()/*_deinit()` functions If you were using the following `_init()/_deinit()` functions, you should now use `*_create()/*_destroy()` instead when making these calls: * `bool rotbmp_init_container();` See ``BitmapLayer``. * `bool rotbmp_pair_init_container();` ``BitmapLayer``. * `void action_bar_layer_init();` See ``ActionBarLayer``. * `void animation_init();` See ``Animation``. * `void bitmap_layer_init();` ``BitmapLayer``. * `void gbitmap_init_as_sub_bitmap();` See [Graphics Types](``Graphics Types``). * `void gbitmap_init_with_data();` See [Graphics Types](``Graphics Types``). * `void inverter_layer_init();` Now `InverterLayer` (deprecated in SDK 3.0). * `void layer_init();` See ``Layer``. * `void menu_layer_init();` See ``MenuLayer``. * `void number_window_init();` * `void property_animation_init_layer_frame();` See ``Animation``. * `void property_animation_init();` See ``Animation``. * `void rotbmp_deinit_container();` ``BitmapLayer``. * `void rotbmp_pair_deinit_container();` ``BitmapLayer``. * `void scroll_layer_init();` See ``ScrollLayer``. * `void simple_menu_layer_init();` See ``SimpleMenuLayer``. * `void text_layer_deinit();` See ``TextLayer``. * `void text_layer_init();` See ``TextLayer``. * `void window_deinit();` See ``Window``. * `void window_init();` See ``Window``.
{ "source": "google/pebble", "title": "devsite/source/_guides/migration/migration-guide.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/migration/migration-guide.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 16740 }
--- # Copyright 2025 Google LLC # # 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. title: PebbleKit iOS 3.0 Migration Guide description: How to migrate apps that use PebbleKit iOS to the 3.0 version. permalink: /guides/migration/pebblekit-ios-3/ generate_toc: true guide_group: migration order: 1 --- With previous Pebble firmware versions, iOS users had to manage two different Bluetooth pairings to Pebble. A future goal is removing the Bluetooth *Classic* pairing and keeping only the *LE* (Low Energy) one. This has a couple of advantages. By using only one Bluetooth connection Pebble saves energy, improving the battery life of both Pebble and the phone. It also has the potential to simplify the onboarding experience. In general, fewer moving parts means less opportunity for failures and bugs. The plan is to remove the Bluetooth *Classic* connection and switch to *LE* in gradual steps. The first step is to make the Pebble app communicate over *LE* if it is available. The Bluetooth *Classic* pairing and connection will be kept since as of today most iOS companion apps rely on the *Classic* connection in order to work properly. Building a companion app against PebbleKit iOS 3.0 will make it compatible with the new *LE* connection, while still remaining compatible with older Pebble watches which don't support the *LE* connection. Once it is decided to cut the Bluetooth *Classic* cord developers won't have to do anything, existing apps will continue to work. > Note: Pebble Time Round (the chalk platform) uses only Bluetooth LE, and so > companion apps **must** use PebbleKit iOS 3.0 to connect with it. ## What's New ### Sharing No More: Dedicated Channels per App A big problem with the Bluetooth *Classic* connection is that all iOS companion apps have to share a single communication channel which gets assigned on a "last one wins" basis. Another problem is that a "session" on this channel has to be opened and closed by the companion app. PebbleKit iOS 3.0 solved both these problems with *LE* based connections. When connected over *LE* each companion app has a dedicated and persistent communication channel to Pebble. This means that an app can stay connected as long as there is a physical Bluetooth LE connection, and it does not have to be closed before that other apps can use it! ### Starting an App from Pebble Since each companion app using the *LE* connection will have a dedicated and persistent channel, the user can now start using an app from the watch without having to pull out the phone to open the companion app. The companion app will already be connected and listening. However there are a few caveats to this: * The user must have launched the companion app at least once after rebooting the iOS device. * If the user force-quits the companion app (by swiping it out of the app manager) the channel to the companion app will be disconnected. Otherwise the channel is pretty robust. iOS will revive the companion app in the background when the watchapp sends a message if the companion app is suspended, has crashed, or was stopped/killed by iOS because it used too much memory. ## How to Upgrade 1. Download the new `PebbleKit.framework` from the [`pebble-ios-sdk`](https://github.com/pebble/pebble-ios-sdk/) repository. 2. Replace the existing `PebbleKit.framework` directory in the iOS project. 3. The `PebbleVendor.framework` isn't needed anymore. If it is not used, remove it from the project to reduce its size. 3. See the [Breaking API Changes](#breaking-api-changes) section below. 4. When submitting the iOS companion to the [Pebble appstore](https://dev-portal.getpebble.com/), make sure to check the checkbox shown below. ![](/images/guides/migration/companion-checkbox.png) > **Important**: Make sure to invoke `[[PBPebbleCentral defaultCentral] run]` > after the iOS app is launched, or watches won't connect! ## Breaking API Changes ### App UUIDs Are Now NSUUIDs Older example code showed how to use the `appUUID` property of the `PBPebbleCentral` object, which was passed as an `NSData` object. Now it is possible to directly use an `NSUUID` object. This also applies to the `PBWatch` APIs requiring `appUUID:` parameters. An example of each case is shown below. **Previous Versions of PebbleKit iOS** ```obj-c uuid_t myAppUUIDbytes; NSUUID *myAppUUID = [[NSUUID alloc] initWithUUIDString:@"226834ae-786e-4302-a52f-6e7efc9f990b"]; [myAppUUID getUUIDBytes:myAppUUIDbytes]; [PBPebbleCentral defaultCentral].appUUID = [NSData dataWithBytes:myAppUUIDbytes length:16]; ``` **With PebbleKit iOS 3.0** ```obj-c NSUUID *myAppUUID = [[NSUUID alloc] initWithUUIDString:@"226834ae-786e-4302-a52f-6e7efc9f990b"]; [PBPebbleCentral defaultCentral].appUUID = myAppUUID; ``` ### Cold PBPebbleCentral As soon as PebbleKit uses a `CoreBluetooth` API a pop-up asking for Bluetooth permissions will appear. Since it is undesirable for this pop-up to jump right into users' faces when they launch the iOS app, `PBPebbleCentral` will start in a "cold" state. This gives developers the option to explain to app users that this pop-up will appear, in order to provide a smoother onboarding experience. As soon as a pop-up would be appropriate to show (e.g.: during the app's onboarding flow), call `[central run]`, and the pop-up will be shown to the user. To help personalize the experience, add some custom text to the pop-up by adding a `NSBluetoothPeripheralUsageDescription` ("Privacy - Bluetooth Peripheral Usage Description") value to the project's `Info.plist` file. ```obj-c // MyAppDelegate.m - Set up PBPebbleCentral and run if the user has already // performed onboarding - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [PBPebbleCentral defaultCentral].delegate = self; [PBPebbleCentral defaultCentral].appUUID = myAppUUID; if ([MySettings sharedSettings].userDidPerformOnboarding) { [[PBPebbleCentral defaultCentral] run]; } } ``` ```obj-c // MyOnboarding.m - Once the pop-up has been accepted, begin PBPebbleCentral - (IBAction)didTapGrantBluetoothPermissionButton:(id)sender { [MySettings sharedSettings].userDidPerformOnboarding = YES; [[PBPebbleCentral defaultCentral] run]; // will trigger pop-up } ``` It is very unlikely that the Pebble watch represented by the `PBWatch` object returned by `lastConnectedWatch` is connected instantly after invoking `[central run]`. Instead, it is guaranteed that the delegate will receive `pebbleCentral:watchDidConnect:` as soon as the watch connects (which might take a few seconds). Once this has occurred, the app may then perform operations on the `PBWatch` object. ## New Features ### 8K AppMessage Buffers In previous versions of PebbleKit iOS, if an app wanted to transmit large amounts of data it had to split it up into packets of 126 bytes. As of firmware version 3.5, this is no longer the case - the maximum message size is now such that a dictionary with one byte array (`NSData`) of 8192 bytes fits in a single app message. The maximum available buffer sizes are increased for messages in both directions (i.e.: inbox and outbox buffer sizes). Note that the watchapp should be compiled with SDK 3.5 or later in order to use this capability. To check whether the connected watch supports the increased buffer sizes, use `getVersionInfo:` as shown below. ```obj-c [watch getVersionInfo:^(PBWatch *watch, PBVersionInfo *versionInfo) { // If 8k buffers are supported... if ((versionInfo.remoteProtocolCapabilitiesFlags & PBRemoteProtocolCapabilitiesFlagsAppMessage8kSupported) != 0) { // Send a larger message! NSDictionary *update = @{ @(0): someHugePayload }; [watch appMessagesPushUpdate:update onSent:^(PBWatch *watch, NSDictionary *update, NSError *error) { // ... }]; } else { // Fall back to sending smaller 126 byte messages... } }]; ``` ### Swift Support The library now exports a module which makes using PebbleKit iOS in [Swift](https://developer.apple.com/swift/) projects much easier. PebbleKit iOS 3.0 also adds nullability and generic annotations so that developers get the best Swift experience possible. ```obj-c func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let pebbleCentral = PBPebbleCentral.defaultCentral() pebbleCentral.appUUID = PBGolfUUID pebbleCentral.delegate = self pebbleCentral.run() return true } ``` ## Minor Changes and Deprecations * Removed the PebbleVendor framework. * Also removed CocoaLumberjack from the framework. This should reduce conflicts if the app is using CocoaLumberjack itself. * If the project need these classes, it can keep the PebbleVendor dependency, therwise just remove it. * Added `[watch releaseSharedSession]` which will close *Classic* sessions that are shared between iOS apps (but not *LE* sessions as they are not shared). * If the app doesn't need to talk to Pebble in the background, it doesn't have to use it. * If the app does talk to Pebble while in the background, call this method as soon as it is done talking. * Deprecated `[watch closeSession:]` - please use `[watch releaseSharedSession]` if required (see note above). The app can't close *LE* sessions actively. * Deprecated `[defaultCentral hasValidAppUUID]` - please use `[defaultCentral appUUID]` and check that it is not `nil`. * Added `[defaultCentral addAppUUID:]` if the app talks to multiple app UUIDs from the iOS application, allowing `PebbleCentral` to eagerly create *LE* sessions. * Added logging - PebbleKit iOS 3.0 now logs internal warnings and errors via `NSLog`. To change the verbosity, use `[PBPebbleCentral setLogLevel:]` or even override the `PBLog` function (to forward it to CocoaLumberjack for example). * Changed `[watch appMessagesAddReceiveUpdateHandler:]` - the handler must not be `nil`. ## Other Recommendations ### Faster Connection Set `central.appUUID` before calling `[central run]`. If using multiple app UUIDs please use the new `addAppUUID:` API before calling `[central run]` for every app UUID that the app will talk to. ### Background Apps If the app wants to run in the background (please remember that Apple might reject it unless it provides reasonable cause) add the following entries to the `UIBackgroundModes` item in the project's `Info.plist` file: * `bluetooth-peripheral` ("App shares data using CoreBluetooth") which is used for communication. * `bluetooth-central` ("App communicates using CoreBluetooth") which is used for discovering and reconnecting Pebbles. ### Compatibility with Older Pebbles Most of the Pebble users today will be using a firmware that is not capable of connecting to an iOS application using *LE*. *LE* support will gradually roll out to all Pebble watches. However, this will not happen overnight. Therefore, both *LE* and *Classic* PebbleKit connections have to be supported for some period of time. This has several implications for apps: * Apps still need to be whitelisted. Read {% guide_link appstore-publishing/whitelisting %} for more information and to whitelist a new app. * Because the *Classic* communication channel is shared on older Pebble firmware versions, iOS apps still need to provide a UI to let the user connect to/disconnect from the Pebble app. For example, a "Disconnect" button would cause `[watch releaseSharedSession]` to be called. * In the project's `Info.plist` file: * The `UISupportedExternalAccessoryProtocols` key still needs to be added with the value `com.getpebble.public`. * The `external-accessory` value needs to be added to the `UIBackgroundModes` array, if you want to support using the app while backgrounded.
{ "source": "google/pebble", "title": "devsite/source/_guides/migration/pebblekit-ios-3.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/migration/pebblekit-ios-3.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 12324 }
--- # Copyright 2025 Google LLC # # 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. title: Creating Pebble Packages description: How to create Pebble Packages permalink: /guides/pebble-packages/creating-packages/ generate_toc: true guide_group: pebble-packages --- {% alert notice %} Currently package _creation_ is only supported by the native SDK. However, you can still use packages in CloudPebble. {% endalert %} ## Getting Started To get started creating a package, run `pebble new-package some-name`. Make `some-name` something meaningful and unique; it is what you'll be publishing it under. You can check if it's taken on [npm](https://npmjs.org). If you'll be including a JavaScript component, you can add `--javascript` for a sample javascript file. ## Components of a Package ### C code {% alert notice %} **Tip**: If you want to use an ``Event Service``, you should use the [pebble-events](https://www.npmjs.com/package/pebble-events) package to handle subscriptions from multiple packages. {% endalert %} Packages can export C functions to their consumers, and the default package exports `somelib_find_truth` as an example. To export a function, it simply has to be declared in a C file in `src/c/`, and declared in a header file in `include/`. For instance: `src/c/somelib.c`: ```c #include <pebble.h> #include "somelib.h" bool somelib_find_truth(void) { return true; } ``` `include/somelib.h`: ```c #pragma once bool somelib_find_truth(void); ``` Notice that `include/` is already in the include path when building packages, so include files there can be included easily. By convention, packages should prefix their non-static functions with their name (in this case `somelib`) in order to avoid naming conflicts. If you don't want to export a function, don't include it in a file in `includes/`; you can instead use `src/c/`. You should still prefix any non-static symbols with your library name to avoid conflicts. Once the package is imported by a consumer — either an app or package — its include files will be in a directory named for the package, and so can be included with `#include <somelib/somelib.h>`. There is no limit on the number or structure of files in the `include` directory. ### JavaScript code Packages can export JavaScript code for use in PebbleKit JS. The default JavaScript entry point for packages is always in `src/js/index.js`. However, files can also be required directly, according to [standard node `require` rules](https://nodejs.org/api/modules.html). In either case they are looked up relative to their root in `src/js/`. JavaScript code can export functions by attaching them to the global `exports` object: `src/js/index.js`: ``` exports.addNumbers = function(a, b) { return a + b; }; ``` Because JavaScript code is scoped and namespaced already, there is no need to use any naming convention. ### Resources Packages can include resources in the same way as apps, and those resources can then be used by both the package and the app. They are included in `package.json` in [the same manner as they are for apps](/guides/app-resources/). To avoid naming conflicts, packages should prefix their resource names with the package name, e.g. `SOMELIB_IMAGE_LYRA`. It's best practice to define an image resource using the package name as a prefix on the resource `name`: ```javascript "resources": { "media": [ { "name": "MEDIA_PACKAGE_IMAGE_01_TINY", "type": "bitmap", "file": "images/01-tiny.png" }, //... ] } ``` Create a `publishedMedia` entry if you want to make the images available for {% guide_link user-interfaces/appglance-c "AppGlance slices" %} or {% guide_link pebble-timeline/pin-structure "Timeline pins" %}. ```javascript "resources": { //... "publishedMedia": [ { "name": "MEDIA_PACKAGE_IMAGE_01", "glance": "MEDIA_PACKAGE_IMAGE_01_TINY", "timeline": { "tiny": "MEDIA_PACKAGE_IMAGE_01_TINY", "small": "MEDIA_PACKAGE_IMAGE_01_SMALL", "large": "MEDIA_PACKAGE_IMAGE_01_LARGE" } } ] } ``` > Note: Do NOT assign an `id` when defining `publishedMedia` within packages, see {% guide_link pebble-packages/using-packages "Using Packages" %}. Resource IDs are not assigned until the package has been linked with an app and compiled, so `RESOURCE_ID_*` constants cannot be used as constant initializers in packages. To work around this, either assign them at runtime or reference them directly. It is also no longer valid to try iterating over the resource id numbers directly; you must use the name defined for you by the SDK. ### AppMessage Keys Libraries can use AppMessage keys to reduce friction when creating a package that needs to communicate with the phone or internet, such as a weather package. A list of key names can be included in `package.json`, under `pebble.messageKeys`. These keys will be allocated numbers at app build time. We will inject them into your C code with the prefix `MESSAGE_KEY_`, e.g. `MESSAGE_KEY_CURRENT_TEMP`. If you want to use multiple keys as an 'array', you can specify a name like `ELEMENTS[6]`. This will create a single key, `ELEMENTS`, but leave five empty spaces after it, for a total of six available keys. You can then use arithmetic to access the additional keys, such as `MESSAGE_KEY_ELEMENTS + 5`. To use arrays in JavaScript you will need to know the actual numeric values of your keys. They will exist as keys on an object you can access via `require('message_keys')`. For instance: ```js var keys = require('message_keys'); var elements = ['honesty', 'generosity', 'loyalty', 'kindness', 'laughter', 'magic']; var dict = {} for (var i = 0; i < 6; ++i) { dict[keys.ELEMENTS + i] = elements[i]; } Pebble.sendAppMessage(dict, successCallback, failureCallback); ``` ## Building and testing Run `pebble build` to build your package. You can install it in a test project using `pebble package install ../path/to/package`. Note that you will have to repeat both steps when you change the package. If you try symlinking the package, you are likely to run into problems building your app. ## Publishing Publishing a Pebble Package requires you to have an npm account. For your convenience, you can create or log in to one using `pebble package login` (as distinct from `pebble login`). Having done this once, you can use `pebble package publish` to publish a package. Remember to document your package! It isn't any use to anyone if they can't figure out how to use it. README.md is a good place to include some documentation. Adding extra metadata to package.json is also worthwhile. In particular, it is worth specifying: * `repository`: if your package is open source, the repo you can find it in. If it's hosted on github, `"username/repo-name"` works; otherwise a git URL. * `license`: the license the package is licensed under. If you're not sure, try [choosealicense.com](http://choosealicense.com). You will also want to include a copy of the full license text in a file called LICENSE. * `description`: a one-sentence description of the package. For more details on package.json, check out [npm's package.json documentation](https://docs.npmjs.com/getting-started/using-a-package.json).
{ "source": "google/pebble", "title": "devsite/source/_guides/pebble-packages/creating-packages.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/pebble-packages/creating-packages.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 7743 }
--- # Copyright 2025 Google LLC # # 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. title: Pebble Packages description: | Details on how to create and use Pebble Packages guide_group: pebble-packages menu: false permalink: /guides/pebble-packages/ generate_toc: false hide_comments: true --- It is very common to want to use some piece of common functionality that we do not provide directly in our SDK: for instance, show the weather or swap our colors in a bitmap. To provide this functionality, developers can create _Pebble Packages_, which provide developers with easy ways to share their code. ## Contents {% include guides/contents-group.md group=page.group_data %}
{ "source": "google/pebble", "title": "devsite/source/_guides/pebble-packages/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/pebble-packages/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 1174 }
--- # Copyright 2025 Google LLC # # 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. title: Using Pebble Packages description: How to use Pebble Packages permalink: /guides/pebble-packages/using-packages/ generate_toc: true guide_group: pebble-packages --- ## Getting started Using pebble packages is easy: 1. Find a package. We will have a searchable listing soon, but for now you can [browse the pebble-package keyword on npm](https://www.npmjs.com/browse/keyword/pebble-package). 2. Run `pebble package install pebble-somelib` to install pebble-somelib. 3. Use the package. It is possible to use _some_ standard npm packages. However, packages that depend on being run in node, or in a real web browser, are likely to fail. If you install an npm package, you can use it in the usual manner, as described below. ### C code Packages should document their specific usage. However, in general, for C packages you can include their headers and call them like so: ```c #include <pebble-somelib/somelib.h> int main() { somelib_do_the_thing(); } ``` All of the package's include files will be in a folder named after the package. Packages may have any structure inside that folder, so you are advised to read their documentation. {% alert notice %} **Tip**: If you want to use an ``Event Service``, you should use the [pebble-events](https://www.npmjs.com/package/pebble-events) package to avoid conflicting with handlers registered by packages. {% endalert %} ### JavaScript code JavaScript packages are used via the `require` function. In most cases you can just `require` the package by name: ```js var somelib = require('pebble-somelib'); somelib.doTheThing(); ``` ### Resources If the package you are using has included image resources, you can reference them directly using their `RESOURCE_ID_*` identifiers. ```c static GBitmap *s_image_01; s_image_01 = gbitmap_create_with_resource(RESOURCE_ID_MEDIA_PACKAGE_IMAGE_01_TINY); ``` ### Published Media If the package you are using has defined `publishedMedia` resources, you can either reference the resources using their resource identifier (as above), or you can create an alias within the `package.json`. The `name` you specify in your own project can be used to reference that `publishedMedia` item for AppGlances and Timeline pins, eg. `PUBLISHED_ID_<name>` For example, if the package exposes the following `publishedMedia`: ```javascript "resources": { //... "publishedMedia": [ { "name": "MEDIA_PACKAGE_IMAGE_01", "glance": "MEDIA_PACKAGE_IMAGE_01_TINY", "timeline": { "tiny": "MEDIA_PACKAGE_IMAGE_01_TINY", "small": "MEDIA_PACKAGE_IMAGE_01_SMALL", "large": "MEDIA_PACKAGE_IMAGE_01_LARGE" } } ] } ``` You could define the following `name` and `alias` with a unique `id` in your `package.json`: ```javascript "resources": { //... "publishedMedia": [ { "name": "SHARED_IMAGE_01", "id": 1, "alias": "MEDIA_PACKAGE_IMAGE_01" } ] } ``` You can then proceed to use that `name`, prefixed with `PUBLISHED_ID_`, within your code: ```c const AppGlanceSlice entry = (AppGlanceSlice) { .layout = { .icon = PUBLISHED_ID_SHARED_IMAGE_01, .subtitle_template_string = "message" } }; ```
{ "source": "google/pebble", "title": "devsite/source/_guides/pebble-packages/using-packages.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/pebble-packages/using-packages.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 3757 }
--- # Copyright 2025 Google LLC # # 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. title: Pebble Timeline description: | How to use Pebble timeline to bring timely information to app users outside the app itself via web services. guide_group: pebble-timeline permalink: /guides/pebble-timeline/ generate_toc: false menu: false related_examples: - title: Timeline Push Pin url: https://github.com/pebble-examples/timeline-push-pin - title: Hello Timeline url: https://github.com/pebble-examples/hello-timeline - title: Timeline TV Tracker url: https://github.com/pebble-examples/timeline-tv-tracker hide_comments: true --- The Pebble timeline is a system-level display of chronological events that apps can insert data into to deliver user-specific data, events, notifications and reminders. These items are called pins and are accessible outside the running app, but are deeply associated with an app the user has installed on their watch. Every user can view their personal list of pins from the main watchface by pressing Up for the past and Down for the future. Examples of events the user may see include weather information, calendar events, sports scores, news items, and notifications from any web-based external service. ## Contents {% include guides/contents-group.md group=page.group_data %} ## Enabling a New App To push pins via the Pebble timeline API, a first version of a new app must be uploaded to the [Developer Portal](https://dev-portal.getpebble.com). This is required so that the appstore can identify the app's UUID, and so generate sandbox and production API keys for the developer to push pins to. It is then possible to use the timeline web API in sandbox mode for development or in production mode for published apps. 1. In the Developer Portal, go to the watchapp's details page in the 'Dashboard' view and click the 'Enable timeline' button. 2. To obtain API keys, click the 'Manage Timeline Settings' button at the top-right of the page. New API keys can also be generated from this page. If required, users with sandbox mode access can also be whitelisted here. ## About Sandbox Mode The sandbox mode is automatically used when the app is sideloaded using the SDK. By default, sandbox pins will be delivered to all users who sideload a PBW. The production mode is used when a user installs the app from the Pebble appstore. Use the two respective API key types for these purposes. If whitelisting is enabled in sandbox mode, the developer's account is automatically included, and they can add more Pebble users by adding the users' email addresses in the [Developer Portal](https://dev-portal.getpebble.com). If preferred, it is possible to enable whitelisting to limit this access to only users involved in development and testing of the app. Enter the email addresses of users to be authorized to use the app's timeline in sandbox mode on the 'Manage Timeline Settings' page of an app listing. > When whitelisting is enabled, the `Pebble.getTimelineToken()` will return an > error for users who are not in the whitelist.
{ "source": "google/pebble", "title": "devsite/source/_guides/pebble-timeline/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/pebble-timeline/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 3592 }
--- # Copyright 2025 Google LLC # # 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. title: Creating Pins description: | How to create timeline pins with reminders, actions, and layouts. guide_group: pebble-timeline order: 0 --- A timeline pin contains all the information required to be displayed on the watch, and is written in the JSON object format. It can contain basic information such as title and times, or more advanced data such as notifications, reminders, or actions that can be used out from the pin view. ## Pin Overview The table below details the pin object fields and their function within the object. Those marked in **bold** are required. | Field | Type | Function | |-------|------|----------| | **`id`** | String (max. 64 chars) | Developer-implemented identifier for this pin event, which cannot be re-used. This means that any pin that was previously deleted cannot then be re-created with the same `id`. | | **`time`** | String ([ISO date-time](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString)) | The start time of the event the pin represents, such as the beginning of a meeting. See {% guide_link pebble-timeline/timeline-public#pin-time-limitations "Pin Time Limitations" %} for information on the acceptable time range. | | `duration` | Integer number | The duration of the event the pin represents, in minutes. | | `createNotification` | [Notification object](#notification-object) | The notification shown when the event is first created. | | `updateNotification` | [Notification object](#notification-object) | The notification shown when the event is updated but already exists. | | **`layout`** | [Layout object](#layout-object) | Description of the values to populate the layout when the user views the pin. | | `reminders` | [Reminder object](#reminder-object) array (Max. 3) | Collection of event reminders to display before an event starts. | | `actions` | [Action object](#action-object) array | Collection of event actions that can be executed by the user. | ### Notification Object The notification objects used for `createNotification` and `updateNotification` contain only one common field: a Layout object describing the visual properties of the notification. The other field (`time`) is used only in an `updateNotification` object. The `createNotification` type does **not** require a `time` attribute. | Field | Type | Function | |-------|------|----------| | `layout` | [Layout object](#layout-object) | The layout that will be used to display this notification. | | `time` | String (ISO date-time) | The new time of the pin update. | The `createNotification` is shown when the pin is first delivered to the watch. The `updateNotification` is shown when the pin already existed and is being updated on the watch. It will only be shown if the `updateNotification.time` is newer than the last `updateNotification.time` received by the watch. Using these fields, developers can build a great experience for their users when live updating pins. For example, when sending updates about a sports game the app could use the `createNotification` to tell the user that "The game has just been added to your timeline" and the `updateNotification` to tell them that "The game starting time has just been updated in your timeline.". ### Layout Object The Layout object is used to describe any message shown in a customizable layout. This includes a pin in the timeline, a notification, and also reminders. Developers can choose between different layout types and customize them with attributes. Required fields are shown in **bold**. Some layout types have additional required fields not shown below, but listed in their dedicated sections. Values for icon URIs can be found below under [Pin Icons](#pin-icons), although not all icons are available at all sizes. | Field | Type | Function | |-------|------|----------| | **`type`** | String | The type of layout the pin will use. See [*Pin Layouts*](#pin-layouts) for a list of available types. | | `title` | String | The title of the pin when viewed. | | `subtitle` | String | Shorter subtitle for details. | | `body` | String | The body text of the pin. Maximum of 512 characters. | | `tinyIcon` | String | URI of the pin's tiny icon. | | `smallIcon` | String | URI of the pin's small icon. | | `largeIcon` | String | URI of the pin's large icon. | The following attributes are also available for all pin layout types **(excluding notifications and reminders)**. | Field | Type | Function | |-------|------|----------| | `primaryColor` | String | Six-digit color hexadecimal string or case-insensitive SDK constant (e.g.: "665566" or "mintgreen"), describing the primary text color. | | `secondaryColor` | String | Similar to `primaryColor`, except applies to the layout's secondary-colored elements. | | `backgroundColor` | String | Similar to `primaryColor`, except applies to the layout's background color. | | `headings` | Array of Strings | List of section headings in this layout. The list must be less than 128 characters in length, including the underlying delimiters (one byte) between each item. Longer items will be truncated with an ellipsis ('...'). | | `paragraphs` | Array of Strings | List of paragraphs in this layout. **Must equal the number of `headings`**. The list must be less than 1024 characters in length, including the underlying delimiters (one byte) between each item. Longer items will be truncated with an ellipsis ('...'). | | `lastUpdated` | ISO date-time | Timestamp of when the pin’s data (e.g: weather forecast or sports score) was last updated. | ### Reminder Object Reminders are synchronized to the watch and will be shown at the precise time set in the reminder. They work even when Pebble is disconnected from the user's mobile phone. | Field | Type | Function | |-------|------|----------| | `time` | String (ISO date-time) | The time the reminder is scheduled to be shown. | | `layout` | [Layout object](#layout-object) | The layout of the reminder. | ### Action Object | Field | Type | Function | |-------|------|----------| | `title` | String | The name of the action that appears on the watch. | | `type` | String | The type of action this will execute. See [*Pin Actions*](#pin-actions) for a list of available actions. | ## Minimal Pin Example The example pin object shown below includes only the required fields for a generic pin. ```json { "id": "example-pin-generic-1", "time": "2015-03-19T18:00:00Z", "layout": { "type": "genericPin", "title": "News at 6 o'clock", "tinyIcon": "system://images/NOTIFICATION_FLAG" } } ``` ## Complete Pin Example Below is a more advanced example pin object: ```json { "id": "meeting-453923", "time": "2015-03-19T15:00:00Z", "duration": 60, "createNotification": { "layout": { "type": "genericNotification", "title": "New Item", "tinyIcon": "system://images/NOTIFICATION_FLAG", "body": "A new appointment has been added to your calendar at 4pm." } }, "updateNotification": { "time": "2015-03-19T16:00:00Z", "layout": { "type": "genericNotification", "tinyIcon": "system://images/NOTIFICATION_FLAG", "title": "Reminder", "body": "The meeting has been rescheduled to 4pm." } }, "layout": { "title": "Client Meeting", "type": "genericPin", "tinyIcon": "system://images/TIMELINE_CALENDAR", "body": "Meeting in Kepler at 4:00pm. Topic: discuss pizza toppings for party." }, "reminders": [ { "time": "2015-03-19T14:45:00Z", "layout": { "type": "genericReminder", "tinyIcon": "system://images/TIMELINE_CALENDAR", "title": "Meeting in 15 minutes" } }, { "time": "2015-03-19T14:55:00Z", "layout": { "type": "genericReminder", "tinyIcon": "system://images/TIMELINE_CALENDAR", "title": "Meeting in 5 minutes" } } ], "actions": [ { "title": "View Schedule", "type": "openWatchApp", "launchCode": 15 }, { "title": "Show Directions", "type": "openWatchApp", "launchCode": 22 } ] } ``` ## View Modes When viewing pins in the timeline, they can be displayed in two different ways. | State | Preview | Details | |-------|---------|---------| | Selected | ![](/images/guides/timeline/timeline-selected.png) | Three lines of text shown from the title, location and sender. | | Not selected | ![](/images/guides/timeline/timeline-one-line.png) | Time, short title, and icon are shown. | ## Pin Icons The tables below detail the available icons provided by the system. Each icon can be used when pushing a pin in the following manner: ``` "layout": { "type": "genericNotification", "title": "Example Pin", "tinyIcon": "system://images/NOTIFICATION_FLAG" } ``` > For general use in watchapps, PDC files are available for these icons in > {% guide_link app-resources/app-assets#pebble-timeline-pin-icons %}. ### Notifications | Preview | Name | Description | |---------|------|-------------| | ![](/images/guides/timeline/NOTIFICATION_GENERIC.svg =25) | `NOTIFICATION_GENERIC` | Generic notification | | ![](/images/guides/timeline/NOTIFICATION_REMINDER.svg =25) | `NOTIFICATION_REMINDER` | Reminder notification | | ![](/images/guides/timeline/NOTIFICATION_FLAG.svg =25) | `NOTIFICATION_FLAG` | Generic notification flag | | ![](/images/guides/timeline/NOTIFICATION_LIGHTHOUSE.svg =25) | `NOTIFICATION_LIGHTHOUSE` | Generic lighthouse | ### Generic | Preview | Name | Description | |---------|------|-------------| | ![](/images/guides/timeline/GENERIC_EMAIL.svg =25) | `GENERIC_EMAIL` | Generic email | | ![](/images/guides/timeline/GENERIC_SMS.svg =25) | `GENERIC_SMS` | Generic SMS icon | | ![](/images/guides/timeline/GENERIC_WARNING.svg =25) | `GENERIC_WARNING` | Generic warning icon | | ![](/images/guides/timeline/GENERIC_CONFIRMATION.svg =25) | `GENERIC_CONFIRMATION` | Generic confirmation icon | | ![](/images/guides/timeline/GENERIC_QUESTION.svg =25) | `GENERIC_QUESTION` | Generic question icon | ### Weather | Preview | Name | Description | |---------|------|-------------| | ![](/images/guides/timeline/PARTLY_CLOUDY.svg =25) | `PARTLY_CLOUDY` | Partly cloudy weather | | ![](/images/guides/timeline/CLOUDY_DAY.svg =25) | `CLOUDY_DAY` | Cloudy weather | | ![](/images/guides/timeline/LIGHT_SNOW.svg =25) | `LIGHT_SNOW` | Light snow weather | | ![](/images/guides/timeline/LIGHT_RAIN.svg =25) | `LIGHT_RAIN` | Light rain weather | | ![](/images/guides/timeline/HEAVY_RAIN.svg =25) | `HEAVY_RAIN` | Heavy rain weather icon | | ![](/images/guides/timeline/HEAVY_SNOW.svg =25) | `HEAVY_SNOW` | Heavy snow weather icon | | ![](/images/guides/timeline/TIMELINE_WEATHER.svg =25) | `TIMELINE_WEATHER` | Generic weather icon | | ![](/images/guides/timeline/TIMELINE_SUN.svg =25) | `TIMELINE_SUN` | Sunny weather icon | | ![](/images/guides/timeline/RAINING_AND_SNOWING.svg =25) | `RAINING_AND_SNOWING` | Raining and snowing weather icon | | ![](/images/guides/timeline/SUNRISE.svg =25) | `SUNRISE` | Sunrise weather icon | | ![](/images/guides/timeline/SUNSET.svg =25) | `SUNSET` | Sunset weather icon | ### Timeline | Preview | Name | Description | |---------|------|-------------| | ![](/images/guides/timeline/TIMELINE_MISSED_CALL.svg =25) | `TIMELINE_MISSED_CALL` | Generic missed call icon | | ![](/images/guides/timeline/TIMELINE_CALENDAR.svg =25) | `TIMELINE_CALENDAR` | Generic calendar event icon | | ![](/images/guides/timeline/TIMELINE_SPORTS.svg =25) | `TIMELINE_SPORTS` | Generic sports icon | ### Sports | Preview | Name | Description | |---------|------|-------------| | ![](/images/guides/timeline/TIMELINE_BASEBALL.svg =25) | `TIMELINE_BASEBALL` | Baseball sports icon | | ![](/images/guides/timeline/AMERICAN_FOOTBALL.svg =25) | `AMERICAN_FOOTBALL` | American football sports icon | | ![](/images/guides/timeline/BASKETBALL.svg =25) | `BASKETBALL` | Basketball sports icon | | ![](/images/guides/timeline/CRICKET_GAME.svg =25) | `CRICKET_GAME` | Cricket sports icon | | ![](/images/guides/timeline/SOCCER_GAME.svg =25) | `SOCCER_GAME` | Soccer sports icon | | ![](/images/guides/timeline/HOCKEY_GAME.svg =25) | `HOCKEY_GAME` | Hockey sports icon | ### Action Results | Preview | Name | Description | |---------|------|-------------| | ![](/images/guides/timeline/RESULT_DISMISSED.svg =25) | `RESULT_DISMISSED` | Dismissed event | | ![](/images/guides/timeline/RESULT_DELETED.svg =25) | `RESULT_DELETED` | Deleted event | | ![](/images/guides/timeline/RESULT_MUTE.svg =25) | `RESULT_MUTE` | Mute event | | ![](/images/guides/timeline/RESULT_SENT.svg =25) | `RESULT_SENT` | Generic message sent event | | ![](/images/guides/timeline/RESULT_FAILED.svg =25) | `RESULT_FAILED` | Generic failure event | ### Events | Preview | Name | Description | |---------|------|-------------| | ![](/images/guides/timeline/STOCKS_EVENT.svg =25) | `STOCKS_EVENT` | Stocks icon | | ![](/images/guides/timeline/MUSIC_EVENT.svg =25) | `MUSIC_EVENT` | Music event | | ![](/images/guides/timeline/BIRTHDAY_EVENT.svg =25) | `BIRTHDAY_EVENT` | Birthday event | | ![](/images/guides/timeline/NEWS_EVENT.svg =25) | `NEWS_EVENT` | Generic news story event | | ![](/images/guides/timeline/SCHEDULED_EVENT.svg =25) | `SCHEDULED_EVENT` | Generic scheduled event | | ![](/images/guides/timeline/MOVIE_EVENT.svg =25) | `MOVIE_EVENT` | Generic movie icon | | ![](/images/guides/timeline/NO_EVENTS.svg =25) | `NO_EVENTS` | No events icon | ### Miscellaneous | Preview | Name | Description | |---------|------|-------------| | ![](/images/guides/timeline/PAY_BILL.svg =25) | `PAY_BILL` | Pay bill event | | ![](/images/guides/timeline/HOTEL_RESERVATION.svg =25) | `HOTEL_RESERVATION` | Hotel event | | ![](/images/guides/timeline/TIDE_IS_HIGH.svg =25) | `TIDE_IS_HIGH` | High tide event | | ![](/images/guides/timeline/INCOMING_PHONE_CALL.svg =25) | `INCOMING_PHONE_CALL` | Incoming phone call event | | ![](/images/guides/timeline/DURING_PHONE_CALL.svg =25) | `DURING_PHONE_CALL` | Phone call event | | ![](/images/guides/timeline/DURING_PHONE_CALL_CENTERED.svg =25) | `DURING_PHONE_CALL_CENTERED` | Phone call event centered | | ![](/images/guides/timeline/DISMISSED_PHONE_CALL.svg =25) | `DISMISSED_PHONE_CALL` | Phone call dismissed event | | ![](/images/guides/timeline/CHECK_INTERNET_CONNECTION.svg =25) | `CHECK_INTERNET_CONNECTION` | Check Internet connection event | | ![](/images/guides/timeline/GLUCOSE_MONITOR.svg =25) | `GLUCOSE_MONITOR` | Sensor monitor event | | ![](/images/guides/timeline/ALARM_CLOCK.svg =25) | `ALARM_CLOCK` | Alarm clock event | | ![](/images/guides/timeline/CAR_RENTAL.svg =25) | `CAR_RENTAL` | Generic car rental event | | ![](/images/guides/timeline/DINNER_RESERVATION.svg =25) | `DINNER_RESERVATION` | Dinner reservation event | | ![](/images/guides/timeline/RADIO_SHOW.svg =25) | `RADIO_SHOW` | Radio show event | | ![](/images/guides/timeline/AUDIO_CASSETTE.svg =25) | `AUDIO_CASSETTE` | Audio cassette icon | | ![](/images/guides/timeline/SCHEDULED_FLIGHT.svg =25) | `SCHEDULED_FLIGHT` | Scheduled flight event | | ![](/images/guides/timeline/REACHED_FITNESS_GOAL.svg =25) | `REACHED_FITNESS_GOAL` | Reached fitness goal event | | ![](/images/guides/timeline/DAY_SEPARATOR.svg =25) | `DAY_SEPARATOR` | Day separator icon | | ![](/images/guides/timeline/WATCH_DISCONNECTED.svg =25) | `WATCH_DISCONNECTED` | Watch disconnected event | | ![](/images/guides/timeline/TV_SHOW.svg =25) | `TV_SHOW` | Generic TV show icon | | ![](/images/guides/timeline/LOCATION.svg =25) | `LOCATION` | Generic location icon | | ![](/images/guides/timeline/SETTINGS.svg =25) | `SETTINGS` | Generic settings icon | ### Custom Icons Custom icons were introduced in SDK 4.0. They allow you to use custom images for timeline pins, by utilizing the {% guide_link tools-and-resources/app-metadata#published-media "Published Media" %} `name`. E.g. `app://images/*name*` ## Pin Layouts Developers can customize how pins, reminders and notifications are shown to the user using different layouts. The Pebble SDK includes layouts appropriate for a broad set of apps. Each layout has different customization options, called the layout attributes. Most layouts also offer the option of showing an icon, which must be one of the standard system provided icons, listed under [*Pin Icons*](#pin-icons) above. The sub-sections below detail the available layouts and the fields they will display. Required attributes are shown in **bold**. ### Generic Layout Generic layout for generic pins of no particular type. **Timeline view** {% screenshot_viewer %} { "image": "/images/guides/timeline/generic-pin.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} **Detail view** {% screenshot_viewer %} { "image": "/images/guides/timeline/generic-layout.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} **Standard Attributes** **`title`**, **`tinyIcon`**, `subtitle`, `body`. **Color Elements** | Layout Property | Applies To | |-----------------|------------| | `primaryColor` | Time, body | | `secondaryColor` | Title | | `backgroundColor` | Background | **Example JSON** ```json { "id": "pin-generic-1", "time": "2015-09-22T16:30:00Z", "layout": { "type": "genericPin", "title": "This is a genericPin!", "tinyIcon": "system://images/NOTIFICATION_FLAG", "primaryColor": "#FFFFFF", "secondaryColor": "#666666", "backgroundColor": "#5556FF" } } ``` ### Calendar Layout Standard layout for pins displaying calendar events. **Timeline view** {% screenshot_viewer %} { "image": "/images/guides/timeline/calendar-pin.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} **Detail view** {% screenshot_viewer %} { "image": "/images/guides/timeline/calendar-layout.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} **Standard Attributes** **`title`**, `body`. **Special Attributes** | Field | Type | Function | |-------|------|----------| | `locationName` | String | Name of the location of this pin event. Used if `shortSubtitle` is not present on the list view, and always in the detail view. | **Color Elements** | Layout Property | Applies To | |-----------------|------------| | `primaryColor` | Times, body | | `secondaryColor` | Title | | `backgroundColor` | Background | **Example JSON** ```json { "id": "pin-calendar-1", "time": "2015-03-18T15:45:00Z", "duration": 60, "layout": { "type": "calendarPin", "title": "Pin Layout Meeting", "locationName": "Conf Room 1", "body": "Discuss layout types with Design Team." } } ``` ### Sports Layout Generic layout for displaying sports game pins including team ranks, scores and records. **Timeline view** {% screenshot_viewer %} { "image": "/images/guides/timeline/sport-pin.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} **Detail view** {% screenshot_viewer %} { "image": "/images/guides/timeline/sport-layout.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} **Standard Attributes** **`title`** (name of the game), `subtitle` (friendly name of the period), `body` (game description), **`tinyIcon`**, `largeIcon`, `lastUpdated`. **Special Attributes** > Note: The `rankAway` and `rankHome` fields will be shown before the event > begins, otherwise `scoreAway` and `scoreHome` will be shown. | Field | Type | Function | |-------|------|----------| | `rankAway` | String (~2 characters) | The rank of the away team. | | `rankHome` | String (~2 characters) | The rank of the home team. | | `nameAway` | String (Max 4 characters) | Short name of the away team. | | `nameHome` | String (Max 4 characters) | Short name of the home team. | | `recordAway` | String (~5 characters) | Record of the away team (wins-losses). | | `recordHome` | String (~5 characters) | Record of the home team (wins-losses). | | `scoreAway` | String (~2 characters) | Score of the away team. | | `scoreHome` | String (~2 characters) | Score of the home team. | | `sportsGameState` | String | `in-game` for in game or post game, `pre-game` for pre game. | **Color Elements** | Layout Property | Applies To | |-----------------|------------| | `primaryColor` | Text body | | `secondaryColor` | Team names and scores | | `backgroundColor` | Background | **Example JSON** ```json { "id": "pin-sports-1", "time": "2015-03-18T19:00:00Z", "layout": { "type": "sportsPin", "title": "Bulls at Bears", "subtitle": "Halftime", "body": "Game of the Century", "tinyIcon": "system://images/AMERICAN_FOOTBALL", "largeIcon": "system://images/AMERICAN_FOOTBALL", "lastUpdated": "2015-03-18T18:45:00Z", "rankAway": "03", "rankHome": "08", "nameAway": "POR", "nameHome": "LAC", "recordAway": "39-19", "recordHome": "39-21", "scoreAway": "54", "scoreHome": "49", "sportsGameState": "in-game" } } ``` ### Weather Layout Standard layout for pins displaying the weather. **Timeline view** {% screenshot_viewer %} { "image": "/images/guides/timeline/weather-pin.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} **Detail view** {% screenshot_viewer %} { "image": "/images/guides/timeline/weather-layout.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} **Standard Attributes** **`title`** (part of the day), **`tinyIcon`**, `largeIcon`, `body` (shortcast), `lastUpdated`. **Special Attributes** | Field | Type | Function | |-------|------|----------| | `shortTitle` | String | Used instead of `title` in the main timeline view unless it is not specified. | | `subtitle` | String | Show high/low temperatures. Note: currently only numbers and the degree symbol (°) are supported. | | `shortSubtitle` | String | Used instead of `subtitle` in the main timeline view unless it is not specified. | | **`locationName`** | String | Name of the location of this pin event. | | `displayTime` | String | Use a value of 'pin' to display the pin's time in title of the detail view and description, or 'none' to not show the time. Defaults to 'pin' if not specified. | **Color Elements** | Layout Property | Applies To | |-----------------|------------| | `primaryColor` | All text | | `backgroundColor` | Background | **Example JSON** ```json { "id": "pin-weather-1", "time": "2015-03-18T19:00:00Z", "layout": { "type": "weatherPin", "title": "Nice day", "subtitle": "40/65", "tinyIcon": "system://images/TIMELINE_SUN", "largeIcon": "system://images/TIMELINE_SUN", "locationName": "Palo Alto", "body": "Sunny with a chance of rain.", "lastUpdated": "2015-03-18T18:00:00Z" } } ``` ### Generic Reminder Generic layout for pin reminders, which can be set at various times before an event is due to occur to remind the user ahead of time. {% screenshot_viewer %} { "image": "/images/guides/timeline/generic-reminder.png", "platforms": [ {"hw": "aplite", "wrapper": "black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} **Standard Attributes** **`title`**, **`tinyIcon`**. **Special Attributes** | Field | Type | Function | |-------|------|----------| | `locationName` | String | Name of the location of this pin event. | **Example JSON** ```json { "id": "pin-generic-reminder-1", "time": "2015-03-18T23:00:00Z", "layout": { "type": "genericPin", "title": "This is a genericPin!", "subtitle": "With a reminder!.", "tinyIcon": "system://images/NOTIFICATION_FLAG" }, "reminders": [ { "time": "2015-03-18T22:55:00Z", "layout": { "type": "genericReminder", "title": "Reminder!", "locationName": "Conf Rm 1", "tinyIcon": "system://images/ALARM_CLOCK" } } ] } ``` ### Generic Notification Generic notification layout which can be used with `createNotification` and `updateNotification` to alert the user to a new pin being created on their timeline. {% screenshot_viewer %} { "image": "/images/guides/timeline/generic-notification-layout.png", "platforms": [ {"hw": "aplite", "wrapper": "steel-black"}, {"hw": "basalt", "wrapper": "time-red"}, {"hw": "chalk", "wrapper": "time-round-rosegold-14"} ] } {% endscreenshot_viewer %} **Standard Attributes** **`title`**, **`tinyIcon`**, `body`. **Color Elements** | Layout Property | Applies To | |-----------------|------------| | `primaryColor` | Title | | `backgroundColor` | Banner background | **Example JSON** ```json { "id": "pin-generic-createmessage-1", "time": "2015-04-30T23:45:00Z", "layout": { "type": "genericPin", "title": "This is a genericPin!", "subtitle": "With a notification", "tinyIcon": "system://images/NOTIFICATION_FLAG" }, "createNotification": { "layout": { "type": "genericNotification", "title": "Notification!", "tinyIcon": "system://images/NOTIFICATION_FLAG", "body": "A new genericPin has appeared!" } } } ``` ## Pin Actions Pins can be further customized by adding actions to them. This allows bi- directional interactivity for pin-based apps. These apps can have multiple actions associated with them, allowing different launch behavior depending on how the user interacts with the pin. The table below shows the available actions that can be added to a pin. Required attributes are shown in **bold**. | Action `type` | Description | Attributes | |---------------|-------------|------------| | `openWatchApp` | Launch the watchapp associated with this pin. The `launchCode` field of this action object will be passed to the watchapp and can be obtained with ``launch_get_args()``. | **`title`**, **`launchCode`**. | | `http` | Execute an HTTP request that invokes this action on the remote service. | See [*HTTP Actions*](#http-actions) for full attribute details. | ### Using a Launch Code Launch codes can be used to pass a single integer value from a specific timeline pin to the app associated with it when it is lauched from that pin. This mechanism allows the context to be given to the app to allow it to change behavior based on the action chosen. For example, a pin could have two actions associated with an app for making restaurant table reservations that allowed the user to cancel the reservation or review the restaurant. To set up these actions, add them to the pin when it is pushed to the timeline API. ``` "actions": [ { "title": "Cancel Table", "type": "openWatchApp", "launchCode": 15 }, { "title": "Leave Rating", "type": "openWatchApp", "launchCode": 22 } ] ``` ### Reading the Launch Code When the user sees the pin and opens the action menu, they can select one of these actions which will launch the watchapp (as dictated by the `openWatchApp` pin action `type`). When the app launches, use ``launch_get_args()`` to read the value of the `launchCode` associated with the chosen action, and react accordingly. An example is shown below; ```c if(launch_reason() == APP_LAUNCH_TIMELINE_ACTION) { uint32_t arg = launch_get_args(); switch(arg) { case LAUNCH_ARG_CANCEL: // Cancel table UI... break; case LAUNCH_ARG_REVIEW: // Leave a review UI... break; } } ``` ### HTTP Actions With the `http` pin action `type`, pins can include actions that carry out an arbitrary HTTP request. This makes it possible for a web service to be used purely by pushed pins with actions that respond to those events. The table below details the attributes of this type of pin action object. Items shown in **bold** are required. | Attribute | Type | Default | Description | |-----------|------|---------|-------------| | **`title`** | String | *mandatory* | The title of the action. | | **`url`** | String | *mandatory* | The URL of the remote service to send the request to. | | `method` | String | `POST` | The request method, such as `GET`, `POST`, `PUT` or `DELETE`. | | `headers` | Object | `{}` | Dictionary of key-value pairs of headers (`Content-Type` is implied by using `bodyJSON`) as required by the remote service. | | `bodyText` | String | `''` | The data body of the request in String format. | | `bodyJSON` | Object | *unspecified* | The data body of the request in JSON object format. | | `successText` | String | "Done!" | The string to display if the action is successful. | | `successIcon` | Pin Icon URL | `system://images/GENERIC_CONFIRMATION` | The icon to display if the action is successful. | | `failureText` | String | "Failed!" | The string to display if the action is unsuccessful. | | `failureIcon` | Pin Icon URL | `system://images/RESULT_FAILED` | The icon to display if the action is unsuccessful. | > Note: `bodyText` and `bodyJSON` are mutually exclusive fields (they cannot be > used together in the same request). You should choose that which is most > convenient for your implementation. > Note: Do not include a body with HTTP methods that do not support one. This > means that `bodyText` and `bodyJSON` cannot be used with `GET` or `DELETE` > requests. The following is an example action, using the `http` action `type` to confirm attendance at a meeting managed by a fictitious meeting scheduling service. ```js "actions": [ { "type": "http", "title": "Confirm Meeting", "url": "http://some-meeting-service.com/api/v1/meetings/46146717", "method": "PUT", "headers": { "X-Request-Source": "pebble-timeline", "Content-Type": "application/x-www-form-urlencoded" }, "bodyText": "type=confirm&value=1", "successIcon": "system://images/GENERIC_CONFIRMATION", "successText": "Confirmed!" } ] ``` Alternatively, pins can use the `bodyJSON` field to encode a JSON object. Include this data using the `bodyJSON` field. ```js "actions": [ { "type": "http", "title": "Confirm Meeting", "url": "http://some-meeting-service.com/api/v1/meetings/46146717", "method": "PUT", "headers": { "X-Request-Source": "pebble-timeline" }, "bodyJSON": { "type": "confirm", "value": true }, "successIcon": "system://images/GENERIC_CONFIRMATION", "successText": "Confirmed!" } ] ``` ### Included Headers When using the `http` action, the request will also include the following additional headers. Developers can use these to personalize the timeline experience to each individual user. | Header Key | Value | |------------|-------| | `X-Pebble-Account-Token` | Same as [`Pebble.getAccountToken()`](/guides/communication/using-pebblekit-js) | | `X-Pebble-Watch-Token` | Same as [`Pebble.getWatchToken()`](/guides/communication/using-pebblekit-js) | ## Testing Pins **Using CloudPebble** When editing a CloudPebble project, developers can test inserting and deleting any pin using the 'Timeline' tab at the top left of the screen. Use the text field to construct the pin, then one of the two buttons to test it out. > Note: Once a pin with a specific `id` has been deleted, that `id` cannot be > reused. ![](/images/guides/timeline/cloudpebble-ui.png) **Push Pins with the Pebble Tool** It is also possible to push new timeline pins using the `pebble` {% guide_link tools-and-resources/pebble-tool %}. Prepare your pin in a JSON file, such as `example-pin.json` shown below: ```json { "id": "pin-generic-1", "time": "2015-03-18T15:45:00Z", "layout": { "type": "genericPin", "title": "This is a genericPin!", "tinyIcon": "system://images/NOTIFICATION_FLAG" } } ``` Push this pin to your emulator to preview how it will appear for users. ```nc|bash $ pebble insert-pin example-pin.json ``` The pin will appear as shown below: ![pin-preview >{pebble-screenshot,pebble-screenshot--time-red}](/images/guides/timeline/generic-pin~basalt.png) It is possible to delete the pin in a similar manner, making sure the `id` is the same as the pin to be removed: ```nc|bash $ pebble delete-pin --id pin-generic-1 ```
{ "source": "google/pebble", "title": "devsite/source/_guides/pebble-timeline/pin-structure.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/pebble-timeline/pin-structure.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 33716 }
--- # Copyright 2025 Google LLC # # 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. title: Service Architecture description: | Find out what the timeline is, how it works and how developers can take advantage of it in their apps. guide_group: pebble-timeline order: 4 --- Every item on the timeline is called a 'pin'. A pin can have information attached to it which is used to show it to the user, such as layout, title, start time and actions. When the user is viewing their timeline, they can use the information provided about the immediate past and future to make decisions about how they plan the rest of their day and how to respond to any missed notifications or events. While the system and mobile application populate the user's timeline automatically with items such as calendar appointments and weather details, the real value of the timeline is realized by third party apps. For example, a sports app could show a pin representing an upcoming match and the user could tell how much time remained until they needed to be home to watch it. Developers can use a watchapp to subscribe their users to one of two types pin: * Personal pins pushed to a user's timeline token. These pins are only delivered to the user the token belongs to, allows a high degree of personalization in the pin's contents. * Channels called 'topics' (one more more, depending on their preferences), allow an app to push pins to a large number of users at once. Topics are created on a per-app basis, meaning a user receiving pins for a 'football' topic from one app will not receive pins from another app using the same topic name. Developers can use the PebbleKit JS API to combine the user's preferences with their location and data from other web-connected sources to make pin updates more personal, or more intelligently delivered. The public timeline web API is used to push data from a own backend server to app users according to the topics they have subscribed to, or to individual users. Methods for doing this are discussed below under [Three Ways to Use Pins](#three-ways-to-use-pins). ## Architecture Overview ![diagram](/images/guides/3.0/timeline-architecture.png) The timeline architecture consists of multiple components that work together to bring timely and relevant data, events, and notifications to the user without their intervention. These components are discussed in more detail below. ### Public Web API The Pebble timeline web API (detailed in {% guide_link pebble-timeline/timeline-public %}) manages the currently available topics, published pins, and timeline-enabled apps' data. All pins that are delivered to users pass through this service. When a developer pushes a pin it is sent to this service for distribution to the applicable users. ### Pebble Mobile App The Pebble mobile app is responsible for synchronizing the pins visible on the watch with those that are currently available in the cloud. The PebbleKit JS APIs allow a developer to use a configuration page (detailed in {% guide_link user-interfaces/app-configuration %}) or onboard menu to give users the choice of which pins they receive via the topics they are subscribed to. Developers can also send the user's token to their own server to maintain a custom list of users, and provide a more personal service. The Pebble mobile app is also responsible for inserting pins directly into the user's timeline for their upcoming calendar events and missed calls. These pins originate on the phone and are sent straight to the watch, not via the public web API. Alarm pin are also inserted directly from the watch itself. ### Developer's App Server/Service When a developer wants to push pins, they can do so from their own third-party server. Such a server will generate pins using topics that the watchapp subscribes to (either for all users or just those that elect to be subscribed) or user tokens received from PebbleKit JS to target individual users. See {% guide_link pebble-timeline/timeline-public %} for information on how to do this. ## Three Ways to Use Pins The timeline API is flexible enough to enable apps to use it to send data to users in three distinct ways. ### Push to All Users ![all-users](/images/guides/timeline/all-users.png) The most basic subscription method involves subscribing a user to a topic that is global to the app. This means all users of the app will receive the pins pushed to that topic. To do this, a developer can choose a single topic name such as 'all-users' and subscribe all users to that topic when the app is first installed, or the user opts in to receive pins. Read {% guide_link pebble-timeline/timeline-public#shared-pins "Shared Pins" %} to find out how to create topics. ### Let Users Choose Their Pins ![some-users](/images/guides/timeline/some-users.png) Developers can also use a configuration page in their app to allow users to subscribe to different topics, leeting them customize their experience and only receive pins they want to see. In the image above, the pin broadcast with the topic 'baseball' is received by users 1 and 3, but not User 2 who has only subscribed to the 'golf' topic. ### Target Individual Users ![individual](/images/guides/timeline/individual.png) Lastly, developers can use the timeline token to target individual users. This adds another dimension to how personal an app can become, allowing apps to be customized to the user in more ways than just their topic preferences. The image above shows a pin pushed from an app's pin server to just the user with the matching `X-User-Token`. For example, an app tracking the delivery of a user's packages will only be applicable to that user. See {% guide_link pebble-timeline/timeline-public#create-a-pin "Create a Pin" %} to learn how to send a pin to a single user.
{ "source": "google/pebble", "title": "devsite/source/_guides/pebble-timeline/timeline-architecture.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/pebble-timeline/timeline-architecture.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 6331 }
--- # Copyright 2025 Google LLC # # 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. title: Managing Subscriptions description: | How to integrate the timeline into apps with the PebbleKit JS subscriptions API according to user preferences. guide_group: pebble-timeline order: 2 related_examples: - title: Timeline Push Pin url: https://github.com/pebble-examples/timeline-push-pin - title: Hello Timeline url: https://github.com/pebble-examples/hello-timeline - title: Timeline TV Tracker url: https://github.com/pebble-examples/timeline-tv-tracker --- The following PebbleKit JS APIs allow developers to intereact with the timeline API, such as adding and removing the user's subscribed topics. By combining these with user preferences from a configuration page (detailed in {% guide_link user-interfaces/app-configuration %}) it is possible to allow users to choose which pin sources they receive updates and events from. > The timeline APIs to subscribe users to topics and retrieve user tokens are > only available in PebbleKit JS. > > If you wish to use the timeline APIs with a Pebble app that uses PebbleKit iOS > or Android please [contact us](/contact) to discuss your specific use-case. ## Requirements These APIs require some knowledge of your app before they can work. For example, in order to return the user's timeline token, the web API must know your app's UUID. This also ensures that only users who have your app installed will receive the correct pins. If you have not performed this process for your app and attempt to use these APIs, you will receive an error similar to the following message: ```text [INFO ] No token available for this app and user. ``` ## Get a Timeline Token The timeline token is unique for each user/app combination. This can be used by an app's third party backend server to selectively send pins only to those users who require them, or even to target users individually for complete personalization. ```js Pebble.getTimelineToken(function(token) { console.log('My timeline token is ' + token); }, function(error) { console.log('Error getting timeline token: ' + error); }); ``` ## Subscribe to a Topic A user can also subscribe to a specific topic in each app. Every user that subscribes to this topic will receive the pins pushed to it. This can be used to let the user choose which features of your app they wish to subscribe to. For example, they may want 'world news' stories but not 'technology' stories. In this case they would be subscribed only to the topic that includes pins with 'world news' information. ```js Pebble.timelineSubscribe('world-news', function() { console.log('Subscribed to world-news'); }, function(err) { console.log('Error subscribing to topic: ' + err); }); ``` ## Unsubscribe from a Topic The user may unsubscribe from a topic they previously subscribed to. They will no longer receive pins from this topic. ```js Pebble.timelineUnsubscribe('world-news', function() { console.log('Unsubscribed from world-news'); }, function(err) { console.log('Error unsubscribing from topic: ' + err); }); ``` ## List Current Subscriptions You can use the function below to list all the topics a user has subscribed to. ```js Pebble.timelineSubscriptions(function(topics) { // List all the subscribed topics console.log('Subscribed to ' + topics.join(', ')); }, function(errorString) { console.log('Error getting subscriptions: ' + errorString); }); ```
{ "source": "google/pebble", "title": "devsite/source/_guides/pebble-timeline/timeline-js.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/pebble-timeline/timeline-js.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 3970 }
--- # Copyright 2025 Google LLC # # 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. title: Libraries for Pushing Pins description: | A list of libraries available for interacting with the Pebble timeline. guide_group: pebble-timeline order: 1 related_examples: - title: Hello Timeline url: https://github.com/pebble-examples/hello-timeline - title: Timeline TV Tracker url: https://github.com/pebble-examples/timeline-tv-tracker - title: Timeline Push Pin url: https://github.com/pebble-examples/timeline-push-pin --- This page contains libraries that are currently available to interact with the timeline. You can use these to build apps and services that push pins to your users. ## timeline.js **JavaScript Code Snippet** - [Available on GitHub](https://gist.github.com/pebble-gists/6a4082ef12e625d23455) **Install** Copy into the `src/pkjs/` directory of your project, add `enableMultiJS: true` in `package.json`, then `require` and use in `index.js`. **Example** ```js var timeline = require('./timeline'); // Push a pin when the app starts Pebble.addEventListener('ready', function() { // An hour ahead var date = new Date(); date.setHours(date.getHours() + 1); // Create the pin var pin = { "id": "example-pin-0", "time": date.toISOString(), "layout": { "type": "genericPin", "title": "Example Pin", "tinyIcon": "system://images/SCHEDULED_EVENT" } }; console.log('Inserting pin in the future: ' + JSON.stringify(pin)); // Push the pin timeline.insertUserPin(pin, function(responseText) { console.log('Result: ' + responseText); }); }); ``` ## pebble-api **Node Module** - [Available on NPM](https://www.npmjs.com/package/pebble-api) **Install** ```bash npm install pebble-api --save ``` **Example** ```js var Timeline = require('pebble-api'); var USER_TOKEN = 'a70b23d3820e9ee640aeb590fdf03a56'; var timeline = new Timeline(); var pin = new Timeline.Pin({ id: 'test-pin-5245', time: new Date(), duration: 10, layout: new Timeline.Pin.Layout({ type: Timeline.Pin.LayoutType.GENERIC_PIN, tinyIcon: Timeline.Pin.Icon.PIN, title: 'Pin Title' }) }); timeline.sendUserPin(USER_TOKEN, pin, function (err) { if (err) { return console.error(err); } console.log('Pin sent successfully!'); }); ``` ## PebbleTimeline API Ruby **Ruby Gem** - [Available on RubyGems](https://rubygems.org/gems/pebble_timeline/versions/0.0.1) **Install** ```bash gem install pebble_timeline ``` **Example** ```ruby require 'pebble_timeline' api = PebbleTimeline::API.new(ENV['PEBBLE_TIMELINE_API_KEY']) # Shared pins pins = PebbleTimeline::Pins.new(api) pins.create(id: "test-1", topics: 'test', time: "2015-06-10T08:01:10.229Z", layout: { type: 'genericPin', title: 'test 1' }) pins.delete("test-1") # User pins user_pins = PebbleTimeline::Pins.new(api, 'user', USER_TOKEN) user_pins.create(id: "test-1", time: "2015-06-12T16:42:00Z", layout: { type: 'genericPin', title: 'test 1' }) user_pins.delete("test-1") ``` ## pypebbleapi **Python Library** - [Available on pip](https://pypi.python.org/pypi/pypebbleapi/0.0.1) **Install** ```bash pip install pypebbleapi ``` **Example** ```python from pypebbleapi import Timeline, Pin import datetime timeline = Timeline(my_api_key) my_pin = Pin(id='123', datetime.date.today().isoformat()) timeline.send_shared_pin(['a_topic', 'another_topic'], my_pin) ``` ## php-pebble-timeline **PHPebbleTimeline** - [Available on Github](https://github.com/fletchto99/PHPebbleTimeline) **Install** Copy the TimelineAPI folder (from the above repository) to your project's directory and include the required files. **Example** <div> {% highlight { "language": "php", "options": { "startinline": true } } %} //Include the timeline API require_once 'TimelineAPI/Timeline.php'; //Import the required classes use TimelineAPI\Pin; use TimelineAPI\PinLayout; use TimelineAPI\PinLayoutType; use TimelineAPI\PinIcon; use TimelineAPI\PinReminder; use TimelineAPI\Timeline; //Create some layouts which our pin will use $reminderlayout = new PinLayout(PinLayoutType::GENERIC_REMINDER, 'Sample reminder!', null, null, null, PinIcon::NOTIFICATION_FLAG); $pinlayout = new PinLayout(PinLayoutType::GENERIC_PIN, 'Our title', null, null, null, PinIcon::NOTIFICATION_FLAG); //Create a reminder which our pin will push before the event $reminder = new PinReminder($reminderlayout, (new DateTime('now')) -> add(new DateInterval('PT10M'))); //Create the pin $pin = new Pin('<YOUR USER TOKEN HERE>', (new DateTime('now')) -> add(new DateInterval('PT5M')), $pinlayout); //Attach the reminder $pin -> addReminder($reminder); //Push the pin to the timeline Timeline::pushPin('sample-userToken', $pin); {% endhighlight %} </div> ## PinPusher **PHP Library** - [Available on Composer](https://packagist.org/packages/valorin/pinpusher) **Install** ```bash composer require valorin/pinpusher ``` **Example** <div> {% highlight { "language": "php", "options": { "startinline": true } } %} use Valorin\PinPusher\Pusher; use Valorin\PinPusher\Pin; $pin = new Pin( 'example-pin-generic-1', new DateTime('2015-03-19T18:00:00Z'), new Pin\Layout\Generic( "News at 6 o'clock", Pin\Icon::NOTIFICATION_FLAG ) ); $pusher = new Pusher() $pusher->pushToUser($userToken, $pin); {% endhighlight %} </div> ## pebble-api-dotnet **PCL C# Library** - [Available on Github](https://github.com/nothingmn/pebble-api-dotnet) **Install** ```text git clone [email protected]:nothingmn/pebble-api-dotnet.git ``` **Example** In your C# project, define your global API Key. ```csharp public static string APIKey = "APIKEY"; ``` Launch your app on the watch, and make the API call... Now, on the server, you can use your "userToken" from the client app, and send pins as follows: ```csharp var timeline = new Timeline(APIKey); var result = await timeline.SendUserPin(userToken, new Pin() { Id = System.Guid.NewGuid().ToString(), Layout = new GenericLayout() { Title = "Generic Layout", Type = LayoutTypes.genericPin, SmallIcon = Icons.Notification.Flag }, }); ``` See more examples on the [GitHub repo](https://github.com/nothingmn/pebble-api-dotnet).
{ "source": "google/pebble", "title": "devsite/source/_guides/pebble-timeline/timeline-libraries.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/pebble-timeline/timeline-libraries.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 6737 }
--- # Copyright 2025 Google LLC # # 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. title: Public Web API description: | How to push Pebble timeline data to an app's users using the public web API. guide_group: pebble-timeline order: 3 related_examples: - title: Hello Timeline url: https://github.com/pebble-examples/hello-timeline - title: Timeline TV Tracker url: https://github.com/pebble-examples/timeline-tv-tracker - title: Timeline Push Pin url: https://github.com/pebble-examples/timeline-push-pin --- While users can register subscriptions and receive data from the timeline using the PebbleKit JS subscriptions API (detailed in {% guide_link pebble-timeline/timeline-js %}), app developers can use the public timeline web API to provide that data by pushing pins. Developers will need to create a simple web server to enable them to process and send the data they want to display in the timeline. Each pin represents a specific event in the past or the future, and will be shown on the watch once pushed to the public timeline web API and automatically synchronized with the watch via the Pebble mobile applications. The Pebble SDK emulator supports the timeline and automatically synchronizes every 30 seconds. ## Pushing Pins Developers can push data to the timeline using their own backend servers. Pins are created and updated using HTTPS requests to the Pebble timeline web API. > Pins pushed to the Pebble timeline web API may take **up to** 15 minutes to > appear on a user's watch. Although most pins can arrive faster than this, we > recommend developers do not design apps that rely on near-realtime updating of > pins. ### Create a Pin To create a pin, send a `PUT` request to the following URL scheme, where `ID` is the `id` of the pin object. For example 'reservation-1395203': ```text PUT https://timeline-api.getpebble.com/v1/user/pins/ID ``` Use the following headers, where `X-User-Token` is the user's timeline token (read {% guide_link pebble-timeline/timeline-js#get-a-timeline-token "Get a Timeline Token" %} to learn how to get a token): ```text Content-Type: application/json X-User-Token: a70b23d3820e9ee640aeb590fdf03a56 ``` Include the JSON object as the request body from a file such as `pin.json`. A sample of an object is shown below: ```json { "id": "reservation-1395203", "time": "2014-03-07T08:01:10.229Z", "layout": { "shortTitle": "Dinner at La Fondue", ... }, ... } ``` #### Curl Example ```bash $ curl -X PUT https://timeline-api.getpebble.com/v1/user/pins/reservation-1395203 \ --header "Content-Type: application/json" \ --header "X-User-Token: a70b23d3820e9ee640aeb590fdf03a56" \ -d @pin.json OK ``` ### Update a Pin To update a pin, send a `PUT` request with a new JSON object with the **same `id`**. ```text PUT https://timeline-api.getpebble.com/v1/user/pins/reservation-1395203 ``` Remember to include the user token in the headers. ```text X-User-Token: a70b23d3820e9ee640aeb590fdf03a56 ``` When an update to an existing pin is issued, it replaces the original pin entirely, so all fields (including those that have not changed) should be included. The example below shows an event updated with a new `time`: ```json { "id": "reservation-1395203", "time": "2014-03-07T09:01:10.229Z", "layout": { "shortTitle": "Dinner at La Fondue", ... }, ... } ``` #### Curl Example ```bash $ curl -X PUT https://timeline-api.getpebble.com/v1/user/pins/reservation-1395203 \ --header "Content-Type: application/json" \ --header "X-User-Token: a70b23d3820e9ee640aeb590fdf03a56" \ -d @pin.json OK ``` ### Delete a Pin Delete a pin by issuing a HTTP `DELETE` request. ```text DELETE https://timeline-api.getpebble.com/v1/user/pins/reservation-1395203 ``` Remember to include the user token in the headers. ```text X-User-Token: a70b23d3820e9ee640aeb590fdf03a56 ``` This pin will then be removed from that timeline on the user's watch. In some cases it may be preferred to simply update a pin with a cancelled event's details so that it can remain visible and useful to the user. #### Curl Example ```bash $ curl -X DELETE https://timeline-api.getpebble.com/v1/user/pins/reservation-1395203 \ --header "Content-Type: application/json" \ --header "X-User-Token: a70b23d3820e9ee640aeb590fdf03a56" OK ``` ## Shared Pins ### Create a Shared Pin It is possible to send a pin (and updates) to multiple users at once by modifying the `PUT` header to include `X-Pin-Topics` (the topics a user must be subscribed to in order to receive this pin) and `X-API-Key` (issued by the [Developer Portal](https://dev-portal.getpebble.com/)). In this case, the URL is also modified: ```text PUT /v1/shared/pins/giants-game-1 ``` The new headers: ```text Content-Type: application/json X-API-Key: fbbd2e4c5a8e1dbef2b00b97bf83bdc9 X-Pin-Topics: giants,redsox,baseball ``` The pin body remains the same: ```json { "id": "giants-game-1", "time": "2014-03-07T10:01:10.229Z", "layout": { "title": "Giants vs Red Sox: 5-3", ... }, ... } ``` #### Curl Example ```bash $ curl -X PUT https://timeline-api.getpebble.com/v1/shared/pins/giants-game-1 \ --header "Content-Type: application/json" \ --header "X-API-Key: fbbd2e4c5a8e1dbef2b00b97bf83bdc9" \ --header "X-Pin-Topics: giants,redsox,baseball" \ -d @pin.json OK ``` ### Delete a Shared Pin Similar to deleting a user pin, shared pins can be deleted by issuing a `DELETE` request: ```text DELETE /v1/shared/pins/giants-game-1 ``` As with creating a shared pin, the API key must also be provided in the request headers: ```text X-API-Key: fbbd2e4c5a8e1dbef2b00b97bf83bdc9 ``` #### Curl Example ```bash $ curl -X DELETE https://timeline-api.getpebble.com/v1/shared/pins/giants-game-1 \ --header "Content-Type: application/json" \ --header "X-API-Key: fbbd2e4c5a8e1dbef2b00b97bf83bdc9" \ OK ``` ## Listing Topic Subscriptions Developers can also query the public web API for a given user's currently subscribed pin topics with a `GET` request: ```text GET /v1/user/subscriptions ``` This requires the user's timeline token: ```text X-User-Token: a70b23d3820e9ee640aeb590fdf03a56 ``` #### Curl Example ```bash $ curl -X GET https://timeline-api.getpebble.com/v1/user/subscriptions \ --header "X-User-Token: a70b23d3820e9ee640aeb590fdf03a56" \ ``` The response will be a JSON object containing an array of topics the user is currently subscribed to for that app: ```json { "topics": [ "topic1", "topic2" ] } ``` ## Pin Time Limitations The `time` property on a pin pushed to the public API must not be more than two days in the past, or a year in the future. The same condition applies to the `time` associated with a pin's reminders and notifications. Any pins that fall outside these conditions may be rejected by the web API. In addition, the actual range of events shown on the watch may be different under some conditions. For shared pins, the date and time of an event will vary depending on the user's timezone. ## Error Handling In the event of an error pushing a pin, the public timeline API will return one of the following responses. | HTTP Status | Response Body | Description | |-------------|---------------|-------------| | 200 | None | Success. | | 400 | `{ "errorCode": "INVALID_JSON" }` | The pin object submitted was invalid. | | 403 | `{ "errorCode": "INVALID_API_KEY" }` | The API key submitted was invalid. | | 410 | `{ "errorCode": "INVALID_USER_TOKEN" }` | The user token has been invalidated, or does not exist. All further updates with this user token will fail. You should not send further updates for this user token. A user token can become invalidated when a user uninstalls an app for example. | | 429 | `{ "errorCode": "RATE_LIMIT_EXCEEDED" }` | Server is sending updates too quickly, and has been rate limited (see [*Rate Limiting*](#rate-limiting) below). | | 503 | `{ "errorCode": "SERVICE_UNAVAILABLE" }` | Could not save pin due to a temporary server error. | ## Rate Limiting For requests using API Keys, developers can make up to 5000 requests per minute. For requests using User Tokens, up to 300 requests every 15 minutes can be made. Check the returned HTTP headers of any API request to see the current rate limit status: ```text $ curl -i https://timeline-api.getpebble.com/v1/user/pins/reservation-1395203 HTTP/1.1 429 OK date: Wed, 13 May 2015 21:36:58 GMT x-ratelimit-percent: 100 retry-after: 43 ``` The headers contain information about the current rate limit status: | Header Name | Description | |-------------|-------------| | `x-ratelimit-percent` | The percentage of the rate limit currently utilized. | | `retry-after` | When `x-ratelimit-percent` has reached `100`, this header will be set to the number of seconds after which the rate limit will reset. | When the rate limit is exceeded, the response body also reports the error: ```text { "errorCode":"RATE_LIMIT_EXCEEDED" } ```
{ "source": "google/pebble", "title": "devsite/source/_guides/pebble-timeline/timeline-public.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/pebble-timeline/timeline-public.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 9547 }
--- # Copyright 2025 Google LLC # # 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. title: Rocky.js JavaScript API description: | Information on using JavaScript to create watchfaces with Rocky.js guide_group: rocky-js menu: false permalink: /guides/rocky-js/ generate_toc: false hide_comments: true --- This section of the developer guides contains information and resources surrounding creating Pebble watchfaces using the Rocky.js JavaScript API. Rocky.js is ECMAScript 5.1 JavaScript running natively on Pebble smartwatches, thanks to [our collaboration](https://github.com/Samsung/jerryscript/wiki/JerryScriptWorkshopApril2016) with [JerryScript](https://github.com/pebble/jerryscript). ![Rocky >{pebble-screenshot,pebble-screenshot--time-red}](/images/blog/2016-08-16-jotw.png) At present, Rocky.js can only be used to create watchfaces, but we're adding more APIs and functionality with every release. ## Contents {% include guides/contents-group.md group=page.group_data %}
{ "source": "google/pebble", "title": "devsite/source/_guides/rocky-js/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/rocky-js/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 1485 }
--- # Copyright 2025 Google LLC # # 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. title: Rocky.js Overview description: | Details of Rocky.js projects, available APIs, limitations, and how to get started. guide_group: rocky-js order: 1 platform_choice: true related_examples: - title: Tutorial Part 1 url: https://github.com/pebble-examples/rocky-watchface-tutorial-part1 - title: Tutorial Part 2 url: https://github.com/pebble-examples/rocky-watchface-tutorial-part2 - title: Memory Pressure url: https://github.com/pebble-examples/rocky-memorypressure --- Rocky.js can be used to create Pebble 4.0 watchfaces using ECMAScript 5.1 JavaScript, which runs natively on the watch. Rocky.js is possible due to [our collaboration](https://github.com/Samsung/jerryscript/wiki/JerryScriptWorkshopApril2016) with [JerryScript](https://github.com/pebble/jerryscript). > At this time, Rocky.js cannot be used to create watchapps, but we're currently working towards this goal. ## It's JavaScript on the freakin' watch! ```javascript var rocky = require('rocky'); rocky.on('minutechange', function(event) { rocky.requestDraw(); }); rocky.on('draw', function(event) { var ctx = event.context; ctx.clearRect(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight); ctx.fillStyle = 'white'; ctx.textAlign = 'center'; var w = ctx.canvas.unobstructedWidth; var h = ctx.canvas.unobstructedHeight; ctx.fillText('JavaScript\non the watch!', w / 2, h / 2); }); ``` ![Rocky >{pebble-screenshot,pebble-screenshot--time-red}](/images/blog/2016-08-16-jotw.png) ## Rocky.js Projects Rocky.js projects have a different structure from projects created using our C SDK. There is a Rocky.js (rocky) component which runs on the watch, and a {% guide_link communication/using-pebblekit-js "PebbleKit JS" %} (pkjs) component which runs on the phone. The pkjs component allows developers to access web services, use geolocation, and offload data processing tasks to the phone. ### Creating a Project ^CP^ Go to [CloudPebble]({{ site.links.cloudpebble }}) and click 'CREATE', enter a project name, then select the 'Rocky.js' project type. <div class="platform-specific" data-sdk-platform="local"> {% markdown {} %} Once you've installed the Pebble SDK, you can create a new Rocky.js project using the following command: ```nc|text $ pebble new-project --rocky <strong><em>projectname</em></strong> ``` {% endmarkdown %} </div> ### Rocky JS ^CP^ In [CloudPebble]({{ site.links.cloudpebble }}), add a new App Source, the file type is JavaScript and the target is `Rocky JS`. `index.js` is now the main entry point into the application on the watch. ^LC^ In the local SDK, our main entry point into the application on the watch is `/src/rocky/index.js`. This is file is where our Rocky.js JavaScript code resides. All code within this file will be executed on the smartwatch. In addition to standard JavaScript, developers have access to the [rocky](/docs/rockyjs/rocky/) object. Additional scripts may also be added, see [below](#additional-scripts). ### PebbleKit JS ^CP^ In [CloudPebble]({{ site.links.cloudpebble }}), add a new App Source, the file type is JavaScript and the target is [PebbleKit JS](/docs/pebblekit-js/). This file should be named `index.js`. ^LC^ In the local SDK, our primary [PebbleKit JS](/docs/pebblekit-js/) script is `/src/pkjs/index.js`. All PebbleKit JS code will execute on the mobile device connected to the smartwatch. In addition to standard JavaScript, developers have access to [WebSockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API), [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest), [Geolocation](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation), [LocalStorage](https://developer.mozilla.org/en-US/docs/Web/API/LocalStorage) and the [Pebble](/docs/pebblekit-js/) object. Additional scripts may also be added, see [below](#additional-scripts). ### Shared JS If you need to share code between Rocky.js and PebbleKit JS, you can place JavaScript files in a shared area. ^CP^ In [CloudPebble]({{ site.links.cloudpebble }}), add a new App Source, the file type is JavaScript and the target is `Shared JS`. ^LC^ In the local SDK, place your shared files in `/src/common/`. Shared JavaScript files can be referenced using the [CommonJS Module](http://www.commonjs.org/specs/modules/1.0/) format. ```javascript // Shared JS (index.js) function test() { console.log('Hello from shared code'); } module.exports.test = test; ``` ```javascript // Rocky JS var shared = require('../common/index'); shared.test(); ``` ```javascript // PebbleKit JS var shared = require('../common/index'); shared.test(); ``` ### Additional Scripts Both the `Rocky JS` and ` PebbleKit JS` support the use of multiple .js files. This helps to keep your code clean and modular. Use the [CommonJS Module](http://www.commonjs.org/specs/modules/1.0/) format for your additional scripts, then `require()` them within your script. ```javascript // additional.js function test() { console.log('Additional File'); } module.exports.test = test; ``` ```javascript var additional = require('./additional'); additional.test(); ``` ## Available APIs In this initial release of Rocky.js, we have focused on the ability to create watchfaces only. We will be adding more and more APIs as time progresses, and we're determined for JavaScript to have feature parity with the rest of the Pebble developer ecosystem. We've developed our API in-line with standard [Web APIs](https://developer.mozilla.org/en-US/docs/Web/API), which may appear strange to existing Pebble developers, but we're confident that this will facilitate code re-use and provide a better experience overall. ### System Events We've provided a series of events which every watchface will likely require, and each of these events allow you to provide a callback function that is called when the event occurs. Existing Pebble developers will be familiar with the tick style events, including: * [`secondchange`](/docs/rockyjs/rocky/#on) * [`minutechange`](/docs/rockyjs/rocky/#on) * [`hourchange`](/docs/rockyjs/rocky/#on) * [`daychange`](/docs/rockyjs/rocky/#on) By using these events, instead of [`setInterval`](/docs/rockyjs), we're automatically kept in sync with the wall clock time. We also have a [`message`](/docs/rockyjs/rocky/#on) event for receiving JavaScript JSON objects from the `pkjs` component, a [`memorypressure`](/docs/rockyjs/rocky/#on) event when there is a notable change in available system memory, and a [`draw`](/docs/rockyjs/rocky/#on) event which you'll use to control the screen updates. ```javascript var rocky = require('rocky'); rocky.on('minutechange', function(event) { // Request the screen to be redrawn on next pass rocky.requestDraw(); }); ``` ### Drawing Canvas The canvas is a 2D rendering context and represents the display of the Pebble smartwatch. We use the canvas context for drawing text and shapes. We're aiming to support standard Web API methods and properties where possible, so the canvas has been made available as a [CanvasRenderingContext2D](/docs/rockyjs/CanvasRenderingContext2D/). > Please note that the canvas isn't fully implemented yet, so certain methods and properties are not available at this time. We're still working on this, so expect more features in future updates! ```javascript rocky.on('draw', function(event) { var ctx = event.context; ctx.fillStyle = 'red'; ctx.textAlign = 'center'; ctx.font = '14px Gothic'; var w = ctx.canvas.unobstructedWidth; var h = ctx.canvas.unobstructedHeight; ctx.fillText('Rocky.js Rocks!', w / 2, h / 2); }); ``` ### Messaging For Rocky.js projects only, we've added a new simplified communication channel [`postMessage()`](/docs/rockyjs/rocky/#postMessage) and [`on('message', ...)`](/docs/rockyjs/rocky/#on) which allows you to send and receive JavaScript JSON objects between the phone and smartwatch. ```javascript // Rocky.js (rocky) // Receive data from the phone (pkjs) rocky.on('message', function(event) { console.log(JSON.stringify(event.data)); }); // Send data to the phone (pkjs) rocky.postMessage({command: 'fetch'}); ``` ```javascript // PebbleKit JS (pkjs) // Receive data from the watch (rocky) Pebble.on('message', function(event) { if(event.data.command === 'fetch') { // doSomething(); } }); // Send data to the watch (rocky) Pebble.postMessage({ 'temperature': 90, 'condition': 'Hot' }); ``` You can see an example of post message in action in [part 2](https://github.com/pebble-examples/rocky-watchface-tutorial-part2) of the Rocky.js tutorial. ### Memory Pressure The [`memorypressure`](/docs/rockyjs/rocky/#on) event is emitted every time there is a notable change in available system memory. This provides developers with an opportunity to free some memory, in order to prevent their application from being terminated when memory pressure is high. ```javascript rocky.on('memorypressure', function(event) { console.log(event.level); }); ``` A detailed example of the [`memorypressure`](/docs/rockyjs/rocky/#on) event is provided [here](https://github.com/pebble-examples/rocky-memorypressure). ### Content Size The [`contentSize`](/docs/rockyjs/rocky/#UserPreferences) property allows developers to dynamically adapt their watchface design based upon the system `Text Size` preference (*Settings > Notifications > Text Size*). `contentSize` is exposed in Rocky.js via the [`UserPreferences`](/docs/rockyjs/rocky/#UserPreferences) object. ```javascript rocky.on('draw', function(event) { var ctx = event.context; // ... if (rocky.userPreferences.contentSize === 'x-large') { ctx.font = '42px bold numbers Leco-numbers'; } else { ctx.font = '32px bold numbers Leco-numbers'; } // ... }); ``` ## App Configuration [Clay](https://github.com/pebble/clay#) is a JavaScript library that makes it easy to add offline configuration pages to your Pebble apps. Out of the box, Clay is not currently compatible with Rocky.js, but it can be made to work by manually including the clay.js file and overriding the default events. You can find a community Rocky.js project which uses Clay [here](https://github.com/orviwan/rocky-leco-clay). ## Limitations Although Rocky.js is finally out of beta, there are still some limitations and restrictions that you need to be aware of: * No support for custom fonts, images and other resources, yet. * No C code allowed. * No messageKeys. * Pebble Packages are not supported. * There are file size and memory constraints for Rocky.js projects. If you include a large JS library, it probably won't work. ## How to Get Started We created a [2-part tutorial](/tutorials/js-watchface-tutorial/part1/) for getting started with Rocky.js watchfaces. It explains everything you need to know about creating digital and analog watchfaces, plus how to retrieve weather conditions from the internet. If you're looking for more detailed information, check out the [API Documentation](/docs/rockyjs).
{ "source": "google/pebble", "title": "devsite/source/_guides/rocky-js/rocky-js-overview.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/rocky-js/rocky-js-overview.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 11606 }
--- # Copyright 2025 Google LLC # # 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. title: Smartstraps description: | Information on creating and talking to smartstraps. guide_group: smartstraps menu: false permalink: /guides/smartstraps/ generate_toc: false hide_comments: true related_docs: - Smartstrap related_examples: - title: Smartstrap Button Counter url: https://github.com/pebble-examples/smartstrap-button-counter - title: Smartstrap Library Test url: https://github.com/pebble-examples/smartstrap-library-test --- The smart accessory port on the back of Pebble Time, Pebble Time Steel, and Pebble Time Round makes it possible to create accessories with electronics built-in to improve the capabilities of the watch itself. Wrist-mounted pieces of hardware that interface with a Pebble watch are called smartstraps and can potentially host many electronic components from LEDs, to temperature sensors, or even external batteries to boost battery life. This section of the developer guides details everything a developer should need to produce a smartstrap for Pebble; from 3D CAD diagrams, to electrical characteristics, to software API and protocol specification details. ## Contents {% include guides/contents-group.md group=page.group_data %} ## Availablility The ``Smartstrap`` API is available on the following platforms and firmwares. | Platform | Model | Firmware | |----------|-------|----------| | Basalt | Pebble Time/Pebble Time Steel | 3.4+ | | Chalk | Pebble Time Round | 3.6+ | Apps that use smartstraps but run on incompatible platforms can use compile-time defines to provide alternative behavior in this case. Read {% guide_link best-practices/building-for-every-pebble %} for more information on supporting multiple platforms with differing capabilities. ## Video Introduction Watch the video below for a detailed introduction to the Smartstrap API by Brian Gomberg (Firmware team), given at the [PebbleSF Meetup](http://www.meetup.com/PebbleSF/). [EMBED](//www.youtube.com/watch?v=uB9r2lw7Bt8)
{ "source": "google/pebble", "title": "devsite/source/_guides/smartstraps/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/smartstraps/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 2549 }
--- # Copyright 2025 Google LLC # # 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. title: Hardware Specification description: | Details of how to build smartstrap hardware, including 3D printing instructions and electrical characteristics. guide_group: smartstraps order: 0 --- This page describes how to make smartstrap hardware and how to interface it with the watch. The smartstrap connector has four contacts: two for ground, one for power and a one-wire serial bus. The power pin is bi-directional and can be used to power the accessory, or for the strap to charge the watch. The amount of power that can be drawn **must not exceed** 20mA, and will of course impact the battery life of Pebble Time. [Download 3D models of Pebble Time and the DIY Smartstrap >{center,bg-lightblue,fg-white}](https://github.com/pebble/pebble-3d/tree/master/Pebble%20Time) > Note: Due to movement of the user the contacts of the DIY Smartstrap may come > undone from time to time. This should be taken into account when designing > around the accessory and its protocol. ## Electronic Characteristics The table below summarizes the characteristics of the accessory port connection on the back of Pebble Time. | Characteristic | Value | |----------------|-------| | Pin layout (watch face down, left to right) | Ground, data, power in/out, ground. | | Type of data connection | Single wire, open drain serial connection with external pull-up required. | | Data voltage level | 1.8V input logic level with tolerance for up to 5V. | | Baud rate | Configurable between 9600 and 460800 bps. | | Output voltage (power pin) | 3.3V (+/- 10%) | | Maximum output current draw (power pin) | 20mA | | Minimum charging voltage (power pin) | 5V (+/- 5%) | | Maximum charging current draw | 500mA | ## Battery Smartstraps and Chargers If a smartstrap is designed to charge a Pebble smartwatch, simply apply +5V to the power pin and make sure that it can provide up to 500mA of current. This is the maximum power draw of Pebble Time when the screen is on, the battery charging, the radios are on, etc. ## Accessories Drawing Power If the accessory is drawing power from the watch it will need to include a pull-up resistor (10kΩ is recommended) so that the watch can detect that a smartstrap is connected. By default, the smartstrap port is turned off. The app will need to turn on the smartstrap port to actually receive power. Refer to ``smartstrap_subscribe()``. ## Example Circuits ### Single-component Data Interface The simplest interface to the smartstrap connector is just a pull-up resistor between the power and the data pin of the watch. This pull-up is required so that the watch can detect that something is connected. By default the data bus will be at +3.3V and the watch or the smartstrap can force the bus to 0V when sending data. > This is the general principle of an open-drain or open-collector bus. Refer to > an [electronic reference](https://en.wikipedia.org/wiki/Open_collector) for > more information. ![software-serial](/images/guides/hardware/software-serial.png =500x) On the smartstrap side, choose to use one or two pins of the chosen micro-controller: * If using only one pin, the smartstrap will most likely have to implement the serial communication in software because most micro-controllers expect separated TX and RX pins. This is demonstrated in the [ArduinoPebbleSerial](https://github.com/pebble/arduinopebbleserial) project when running in 'software serial' mode. * If using two pins, simply connect the data line to both the TX and RX pins. The designer should make sure that the TX pin is in high-impedance mode when not talking on the bus and that the serial receiver is not active when sending (otherwise it will receive everything sent). This is demonstrated in the [ArduinoPebbleSerial](https://github.com/pebble/arduinopebbleserial) project when running in the 'hardware serial' mode. ### Transistor-based Buffers When connecting the smartstrap to a micro-controller where the above options are not possible then a little bit of hardware can be used to separate the TX and RX signals and emulate a standard serial connection. ![buffer](/images/guides/hardware/buffer.png =500x) ### A More Professional Interface Finally, for production ready smartstraps it is recommended to use a more robust setup that will provide voltage level conversion as well as protect the smartstraps port from over-voltage. The diagram below shows a suggested circuit for interfacing the smartstrap connector (right) to a traditional two-wire serial connection (left) using a [SN74LVC1G07](http://www.ti.com/product/sn74lvc1g07) voltage level converter as an interface with Zener diodes for [ESD](http://en.wikipedia.org/wiki/Electrostatic_discharge) protection. ![strap-adapter](/images/more/strap-adapter.png) ## Smartstrap Connectors Two possible approaches are suggested below, but there are many more potential ways to create smartstrap connectors. The easiest way involves modifying a Pebble Time charging cable, which provides a solid magnetized connection at the cost of wearability. By contrast, 3D printing a connector is a more comfortable approach, but requires a high-precision 3D printer and additional construction materials. ### Hack a Charging Cable The first suggested method to create a smartstrap connector for prototyping hardware is to adapt a Pebble Time charging cable using common hardware hacking tools, such as a knife, soldering iron and jumper cables. The end result is a component that snaps securely to the back of Pebble Time, and connects securely to common male-to-female prototyping wires, such as those sold with Arduino kits. First, cut off the remainder of the cable below the end containing the magnets. Next, use a saw or drill to split the malleable outer casing. ![](/images/guides/hardware/cable-step1.jpg =450x) Pull the inner clear plastic part of the cable out of the outer casing, severing the wires. ![](/images/guides/hardware/cable-step2.jpg =450x) Use the flat blade of a screwdriver to separate the clear plastic from the front plate containing the magnets and pogo pins. ![](/images/guides/hardware/cable-step3.jpg =450x) Using a soldering iron, remove the flex wire attached to the inner pogo pins. Ensure that there is no common electrical connection between any two contacts. In its original state, the two inner pins are connected, and **must** be separated. Next, connect a row of three headers to the two middle pins, and one of the magnets. > Note: Each contact may require tinning in order to make a solid electrical > connection. ![](/images/guides/hardware/cable-step4.jpg =450x) The newly created connector can now be securely attached to the back of Pebble Time. ![](/images/guides/hardware/cable-step5.jpg =450x) With the connector in place, the accessory port pins may be easily interfaced with using male-to-female wires. ![](/images/guides/hardware/cable-step6.jpg =450x) ### 3D Printed Connector An alternate method of creating a compatible connector is to 3D print a connector component and add the electrical connectivity using some additional components listed below. To make a 3D printed smartstrap connector the following components will be required: ![components](/images/more/strap-components.png =400x) * 1x Silicone strap or similar, trimmed to size (See [*Construction*](#construction)). * 1x Quick-release style pin or similar ([Amazon listing](http://www.amazon.com/1-8mm-Release-Spring-Cylindrical-Button/dp/B00Q7XE866)). * 1x 3D printed adapter ([STP file](https://github.com/pebble/pebble-3d/blob/master/Pebble%20Time/Smartstrap-CAD.stp)). * 4x Spring loaded pogo pins ([Mill-Max listing](https://www.mill-max.com/products/pin/0965)). * 4x Lengths of no.24 AWG copper wire. #### Construction For the 3D printed adapter, it is highly recommended that the part is created using a relatively high resolution 3D printer (100-200 microns), such as a [Form 1](http://formlabs.com/products/form-1-plus/) printer. Alternatively there are plenty of websites that 3D print parts, such as [Shapeways](http://www.shapeways.com/). Make sure to use a **non-conductive** material such as ABS, and print a few copies, just to be safe. (A lower resolution printer like a Makerbot may not produce the same results. The 3D part depends on many fine details to work properly). For the strap, it is recommend to use a silicone strap (such as the one included with Pebble Time or a white Pebble Classic), and cut it down. Put the strap along the left and right side of the lug holes, as shown below. > Ensure the strap is cut after receiving the 3D printed part so that it can be > used as a reference. ![cutaway](/images/more/strap-measurements.png =300x) #### Assembly Slide the quick-release pin into the customized silicone strap. ![strap-insert-pin](/images/more/strap-insert-pin.png =300x) Slide the strap and pin into the 3D printed adapter. ![strap-into-adapter](/images/more/strap-into-adapter.png =300x) Insert the copper wire pieces into the back of the 3D printed adapter. ![strap-insert-wires](/images/more/strap-insert-wires.png =300x) Place the pogo pins into their respective holes, then slide them into place away from the strap. ![strap-insert-pogo-pins](/images/more/strap-insert-pogo-pins.png =300x)
{ "source": "google/pebble", "title": "devsite/source/_guides/smartstraps/smartstrap-hardware.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/smartstraps/smartstrap-hardware.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 9883 }
--- # Copyright 2025 Google LLC # # 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. title: Protocol Specification description: | Reference information on the Pebble smartstrap protocol. guide_group: smartstraps order: 1 --- This page describes the protocol used for communication with Pebble smartstraps, intended to gracefully handle bus contention and allow two-way communication. The protocol is error-free and unreliable, meaning datagrams either arrive intact or not at all. ## Communication Model Most smartstrap communication follows a master-slave model with the watch being the master and the smartstrap being the slave. This means that the watch will never receive data from the smartstrap which it isn't expecting. The one exception to the master/slave model is the notification mechanism, which allows the smartstrap to notify the watch of an event it may need to respond to. This is roughly equivalent to an interrupt line on an I2C device, but for smartstraps is done over the single data line (marked 'Data' on diagrams). ## Assumptions The following are assumed to be universally true for the purposes of the smartstrap protocol: 1. Data is sent in [little-endian](https://en.wikipedia.org/wiki/Endianness) byte order. 2. A byte is defined as an octet (8 bits). 3. Any undefined values should be treated as reserved and should not be used. ## Sample Implementation Pebble provides complete working sample implementations for common micro-controllers platforms such as the [Teensy](https://www.pjrc.com/teensy/) and [Arduino Uno](https://www.arduino.cc/en/Main/arduinoBoardUno). This means that when using one of these platforms, it is not necessary to understand all of the details of the low level communications and thus can rely on the provided library. [Arduino Pebble Serial Sample Library >{center,bg-dark-red,fg-white}](https://github.com/pebble/ArduinoPebbleSerial/) Read [*Talking to Pebble*](/guides/smartstraps/talking-to-pebble) for instructions on how to use this library to connect to Pebble. ## Protocol Layers The smartstrap protocol is split up into 3 layers as shown in the table below: | Layer | Function | |-------|----------| | [Profile Layer](#profile-layer) | Determines the format of the high-level message being transmitted. | | [Link Layer](#link-layer) | Provides framing and error detection to allow transmission of datagrams between the watch and the smartstrap. | | [Physical Layer](#physical-layer) | Transmits raw bits over the electrical connection. | ### Physical Layer The physical layer defines the hardware-level protocol that is used to send bits over the single data wire. In the case of the smartstrap interface, there is a single data line, with the two endpoints using open-drain outputs with an external pull-up resistor on the smartstrap side. Frames are transmitted over this data line as half-duplex asynchronous serial (UART). The UART configuration is 8-N-1: eight data bits, no [parity bit](https://en.wikipedia.org/wiki/Parity_bit), and one [stop bit](https://en.wikipedia.org/wiki/Asynchronous_serial_communication). The default baud rate is 9600 bps (bits per second), but can be changed by the higher protocol layers. The smallest data unit in a frame is a byte. **Auto-detection** The physical layer is responsible for providing the smartstrap auto-detection mechanism. Smartstraps are required to have a pull-up resistor on the data line which is always active and not dependent on any initialization (i.e. activating internal pull-ups on microcontroller pins). The value of the pull-up resistor must be low enough that adding a 30kΩ pull-down resistor to the data line will leave the line at >=1.26V (10kΩ is generally recommended). Before communication with the smartstrap is attempted, the watch will check to see if the pull-up is present. If (and only if) it is, the connection will proceed. **Break Character** A break character is defined by the physical layer and used by the [link layer](#link-layer) for the notification mechanism. The physical layer for smartstraps defines a break character as a `0x00` byte with an extra low bit before the stop bit. For example, in 8-N-1 UART, this means the start bit is followed by nine low (`0`) bits and a stop bit. ### Link Layer The link layer is responsible for transmitting frames between the smartstrap and the watch. The goal of the link layer is to detect transmission errors such as flipped bits (including those caused by bus contention) and to provide a framing mechanism to the upper layers. #### Frame Format The structure of the link layer frame is shown below. The fields are transmitted from top to bottom. > Note: This does not include the delimiting flags or bytes inserted for > transparency as described in the [encoding](#encoding) section below. | Field Name | Length | |------------|--------| | `version` | 1 byte | | `flags` | 4 bytes | | `profile` | 2 bytes | | `payload` | Variable length (may be empty) | | `checksum` | 1 byte | **Version** The `version` field contains the current version of the link layer of the smartstrap protocol. | Version | Description | |---------|-------------| | 1 | Initial release version. | **Flags** The `flags` field is four bytes in length and is made up of the following fields. | Bit(s) | Name | Description | |--------|------|-------------| | 0 | `IsRead` | `0`: The smartstrap should not reply to this frame.</br>`1`: This is a read and the smartstrap should reply.</br></br>This field field should only be set by the watch. The smartstrap should always set this field to `0`. | | 1 | `IsMaster` | `0`: This frame was sent by the smartstrap.</br>`1`: This frame was sent by the watch. | | 2 | `IsNotification` | `0`: This is not a notification frame.</br>`1`: This frame was sent by the smartstrap as part of the notification.</br></br>This field should only be set by the smartstrap. The watch should always set this field to `0`. | | 3-31 | `Reserved` | All reserved bits should be set to `0`. | **Profile** The `profile` field determines the specific profile used for communication. The details of each of the profiles are defined in the [Profile Layer](#profile-layer) section. | Number | Value | Name | |--------|-------|------| | 1 | `0x0001` | Link Control Profile | | 2 | `0x0002` | Raw Data Profile | | 3 | `0x0003` | Generic Service Profile | **Payload** The `payload` field contains the profile layer data. The link layer considers an empty frame as being valid, and there is no maximum length. **Checksum** The checksum is an 8-bit [CRC](https://en.wikipedia.org/wiki/Cyclic_redundancy_check) with a polynomial of `x^8 + x^5 + x^3 + x^2 + x + 1`. This is **not** the typical CRC-8 polynomial. An example implementation of this CRC can be found in the [ArduinoPebbleSerial library](https://github.com/pebble/ArduinoPebbleSerial/blob/master/utility/crc.c). **Frame Length** The length of a frame is defined as the number of bytes in the `flags`, `profile`, `checksum`, and `payload` fields of the link layer frame. This does not include the delimiting flags or the bytes inserted for transparency as part of [encoding](#encoding). The smallest valid frame is eight bytes in size: one byte for the version, four for the flags, two for the profile type, one for the checksum, and zero for the empty payload. The protocol is designed to work without the need for fixed buffers. #### Encoding A delimiting flag (i.e.: a byte with value of `0x7e`) is used to delimit frames (indicating the beginning or end of a frame). The byte stream is examined on a byte-by-byte basis for this flag value. Each frame begins and ends with the delimiting flag, although only one delimiting flag is required between two frames. Two consecutive delimiting flags constitute an empty frame, which is silently discarded by the link layer and is not considered an error. **Transparency** A byte-stuffing procedure is used to escape `0x7e` bytes in the frame payload. After checksum computation, the link layer of the transmitter within the smartstrap encodes the entire frame between the two delimiting flags. Any occurrence of `0x7e` or `0x7d` in the frame is escaped with a proceeding `0x7d` byte and logically-XORed with `0x20`. For example: * The byte `0x7d` when escaped is encoded as `0x7d 0x5d`. * The byte `0x7e` when escaped is encoded as `0x7d 0x5e`. On reception, prior to checksum computation, decoding is performed on the byte stream before passing the data to the profile layer. #### Example Frames The images below show some example frames of the smartstrap protocol under two example conditions, including the calculated checksum. Click them to see more detail. **Raw Profile Read Request** <a href="/assets/images/guides/hardware/raw-read.png"><img src="/assets/images/guides/hardware/raw-read.png"></img></a> **Raw Profile Response** <a href="/assets/images/guides/hardware/raw-response.png"><img src="/assets/images/guides/hardware/raw-response.png"></img></a> #### Invalid Frames Frames which are too short, have invalid transparency bytes, or encounter a UART error (such as an invalid stop bit) are silently discarded. #### Timeout If the watch does not receive a response to a message sent with the `IsRead` flag set (a value of `1`) within a certain period of time, a timeout will occur. The amount of time before a timeout occurs is always measured by the watch from the time it starts to send the message to the time it completely reads the response. The amount of time it takes to send a frame (based on the baud rate, maximum size of the data after encoding, and efficiency of the physical layer UART implementation) should be taken into account when determining timeout values. The value itself can be set with ``smartstrap_set_timeout()``, up to a maximum value of 1000ms. > Note: In order to avoid bus contention and potentially corrupting other > frames, the smartstrap should not respond after the timeout has elapsed. Any frame > received after a timeout has occurred will be dropped by the watch. ### Notification Mechanism There are many use-cases where the smartstrap will need to notify the watch of some event. For example, smartstraps may contain input devices which will be used to control the watch. These smartstraps require a low-latency mechanism for notifying the watch upon receiving user-input. The primary goal of this mechanism is to keep the code on the smartstrap as simple as possible. In order to notify the watch, the smartstrap can send a break character (detailed under [*Physical Layer*](#physical-layer)) to the watch. Notifications are handled on a per-profile granularity, so the frame immediately following a break character, called the context frame, is required in order to communicate which profile is responsible for handling the notification. The context frame must have the `IsNotification` flag (detailed under [*Flags*](#flags)) set and have an empty payload. How the watch responds to notifications is dependent on the profile. ### Profile Layer The profile layer defines the format of the payload. Exactly which profile a frame belongs to is determined by the `profile` field in the link layer header. Each profile type defines three things: a set of requirements, the format of all messages of that type, and notification handling. #### Link Control Profile The link control profile is used to establish and manage the connection with the smartstrap. It must be fully implemented by all smartstraps in order to be compatible with the smartstrap protocol as a whole. Any invalid responses or timeouts encountered as part of link control profile communication will cause the smartstrap to be marked as disconnected and powered off unless otherwise specified. The auto-detection mechanism will cause the connection establishment procedure to restart after some time has passed. **Requirements** | Name | Value | |------|-------| | Notifications Allowed? | No | | Message Timeout | 100ms. | | Maximum Payload Length | 6 bytes. | **Payload Format** | Field | Length (bytes) | |-------|----------------| | Version | 1 | | Type | 1 | | Data | Variable length (may be empty) | **Version** The Version field contains the current version of link control profile. | Version | Notes | |---------|-------| | `1` | Initial release version. | **Type** | Type | Value | Data | |------|-------|-------------| | Status | `0x01` | Watch: *Empty*. Smartstrap: Status (see below). | | Profiles | `0x02` | Watch: *Empty*. Smartstrap: Supported profiles (see below). | | Baud rate | `0x03` | Watch: *Empty*. Smartstrap: Baud rate (see below). | **Status** This message type is used to poll the status of the smartstrap and allow it to request a change to the parameters of the connection. The smartstrap should send one of the following status values in its response. | Value | Meaning | Description | |-------|---------|-------------| | `0x00` | OK | This is a simple acknowledgement that the smartstrap is still alive and is not requesting any changes to the connection parameters. | | `0x01` | Baud rate | The smartstrap would like to change the baud rate for the connection. The watch should follow-up with a baud rate message to request the new baud rate. | | `0x02` | Disconnect | The smartstrap would like the watch to mark it as disconnected. | A status message is sent by the watch at a regular interval. If a timeout occurs, the watch will retry after an interval of time. If an invalid response is received or the retry also hits a timeout, the smartstrap will be marked as disconnected. **Profiles** This message is sent to determine which profiles the smartstrap supports. The smartstrap should respond with a series of two byte words representing all the [profiles](#profile) which it supports. There are the following requirements for the response. * All smartstraps must support the link control profile and should not include it in the response. * All smartstraps must support at least one profile other than the link control profile, such as the raw data profile. * If more than one profile is supported, they should be reported in consecutive bytes in any order. > Note: Any profiles which are not supported by the watch are silently ignored. **Baud Rate** This message type is used to allow the smartstrap to request a change in the baud rate. The smartstrap should respond with a pre-defined value corresponding to the preferred baud rate as listed below. Any unlisted value is invalid. In order to conserve power on the watch, the baud rate should be set as high as possible to keep time spent alive and communicating to a minimum. | Value | Baud Rate (bits per second) | |-------|-----------------------------| | `0x00` | 9600 | | `0x01` | 14400 | | `0x02` | 19200 | | `0x03` | 28800 | | `0x04` | 38400 | | `0x05` | 57600 | | `0x06` | 62500 | | `0x07` | 115200 | | `0x08` | 125000 | | `0x09` | 230400 | | `0x0A` | 250000 | | `0x0B` | 460800 | Upon receiving the response from the smartstrap, the watch will change its baud rate and then send another status message. If the smartstrap does not respond to the status message at the new baud rate, it is treated as being disconnected. The watch will revert back to the default baud rate of 9600, and the connection establishment will start over. The default baud rate (9600) must always be the lowest baud rate supported by the smartstrap. **Notification Handling** Notifications are not supported for this profile. #### Raw Data Service The raw data profile provides a mechanism for exchanging raw data with the smartstrap without any additional overhead. It should be used for any messages which do not fit into one of the other profiles. **Requirements** | Name | Value | |------|-------| | Notifications Allowed? | Yes | | Message Timeout | 100ms from sending to complete reception of the response. | | Maximum Payload Length | Not defined. | **Payload Format** There is no defined message format for the raw data profile. The payload may contain any number of bytes (including being empty). | Field | Value | |-------|-------| | `data` | Variable length (may be empty). | **Notification Handling** The handling of notifications is allowed, but not specifically defined for the raw data profile. #### Generic Service Profile The generic service profile is heavily inspired by (but not identical to) the [GATT bluetooth profile](https://developer.bluetooth.org/gatt/Pages/default.aspx). It allows the watch to write to and read from pre-defined attributes on the smartstrap. Similar attributes are grouped together into services. These attributes can be either read or written to, where a read requires the smartstrap to respond with the data from the requested attribute, and a write requiring the smartstrap to set the value of the attribute to the value provided by the watch. All writes require the smartstrap to send a response to acknowledge that it received the request. The data type and size varies by attribute. **Requirements** | Name | Value | |------|-------| | Notifications Allowed? | Yes | | Message Timeout | Not defined. A maximum of 1000ms is supported. | | Maximum Payload Length | Not defined. | **Payload Format** | Field | Length (bytes) | |-------|----------------| | Version | 1 | | Service ID | 2 | | Attribute ID | 2 | | Type | 1 | | Error Code | 1 | | Length | 2 | | Data | Variable length (may be empty) | **Version** The Version field contains the current version of generic service profile. | Version | Notes | |---------|-------| | `1` | Initial release version. | **Service ID** The two byte identifier of the service as defined in the Supported Services and Attributes section below. The available Service IDs are blocked off into five ranges: | Service ID Range (Inclusive) | Service Type | Description | |------------------------------|--------------|-------------| | `0x0000` - `0x00FF` | Reserved | These services are treated as invalid by the watch and should never be used by a smartstrap. The `0x0000` service is currently aliased to the raw data profile by the SDK. | | `0x0100` - `0x0FFF` | Restricted | These services are handled internally in the firmware of the watch and are not available to apps. Smartstraps may (and in the case of the management service, must) support services in this range. | | `0x1000` - `0x1FFF` | Experimentation | These services are for pre-release product experimentation and development and should NOT be used in a commercial product. When a smartstrap is going to be sold commercially, the manufacturer should contact Pebble to request a Service ID in the "Commerical" range. | | `0x2000` - `0x7FFF` | Spec-Defined | These services are defined below under [*Supported Services and Attributes*](#supported-services-and-attributes), and any smartstrap which implements them must strictly follow the spec to ensure compatibility. | | `0x8000` - `0xFFFF` | Commercial | These services are allocated by Pebble to smartstrap manufacturers who will define their own attributes. | **Attribute ID** The two byte identifier of the attribute as defined in the Supported Services and Attributes section below. **Type** One byte representing the type of message being transmitted. When the smartstrap replies, it should preserve this field from the request. | Value | Type | Meaning | |-------|------|---------| | `0` | Read | This is a read request with the watch not sending any data, but expecting to get data back from the smartstrap. | | `1` | Write | This is a write request with the watch sending data to the smartstrap, but not expected to get any data back. | | `2` | WriteRead | This is a write+read request which consists of the watch writing data to the smartstrap **and** expecting to get some data back in response. | **Error Code** The error code is set by the smartstrap to indicate the result of the previous request and must be one of the following values. | Value | Name | Meaning | |-------|------|---------| | `0` | OK | The read or write request has been fulfilled successfully. The watch should always use this value when making a request. | | `1` | Not Supported | The requested attribute is not supported by the smartstrap. | **Length** The length of the data in bytes. #### Supported Services and Attributes **Management Service (Service ID: `0x0101`)** | Attribute ID | Attribute Name | Type | Data Type | Data | |--------------|----------------|------|-----------|------| | `0x0001` | Service Discovery | Read | uint16[1..10] | A list of Service ID values for all of the services supported by the smartstrap. A maximum of 10 (inclusive) services may be reported. In order to support the generic service profile, the management service must be supported and should not be reported in the response. | | `0x0002` | Notification Info | Read | uint16_t[2] | If a read is performed by the watch after the smartstrap issues a notification, the response data should be the IDs of the service and attribute which generated the notification. | **Pebble Control Service (Service ID: `0x0102`)** > Note: This service is not yet implemented. | Attribute ID | Attribute Name | Type | Data Type | Data | |--------------|----------------|------|-----------|------| | `0x0001` | Launch App | Read | uint8[16] | The UUID of the app to launch. | | `0x0002` | Button Event | Read | uint8[2] | This message allows the smartstrap trigger button events on the watch. The smartstrap should send two bytes: the button being acted on and the click type. The possible values are defined below:</br></br>Buttons Values:</br>`0x00`: No Button</br>`0x01`: Back button</br>`0x02`: Up button</br>`0x03`: Select button</br>`0x04`: Down button</br></br>Click Types:</br>`0x00`: No Event</br>`0x01`: Single click</br>`0x02`: Double click</br>`0x03`: Long click</br></br>The smartstrap can specify a button value of `0x00` and a click type of `0x00` to indicate no pending button events. Any other use of the `0x00` values is invalid. | **Location and Navigation Service (Service ID: `0x2001`)** | Attribute ID | Attribute Name | Type | Data Type | Data | |--------------|----------------|------|-----------|------| | `0x0001` | Location | Read | sint32[2] | The current longitude and latitude in degrees with a precision of 1/10^7. The latitude comes before the longitude in the data. For example, Pebble HQ is at (37.4400662, -122.1583808), which would be specified as {374400662, -1221583808}. | | `0x0002` | Location Accuracy | Read | uint16 | The accuracy of the location in meters. | | `0x0003` | Speed | Read | uint16 | The current speed in meters per second with a precision of 1/100. For example, 1.5 m/s would be specified as 150. | | `0x0101` | GPS Satellites | Read | uint8 | The number of GPS satellites (typically reported via NMEA. | | `0x0102` | GPS Fix Quality | Read | uint8 | The quality of the GPS fix (reported via NMEA). The possible values are listed in the [NMEA specification](http://www.gpsinformation.org/dale/nmea.htm#GGA). | **Heart Rate Service (Service ID: `0x2002`)** | Attribute ID | Attribute Name | Type | Data Type | Data | |--------------|----------------|------|-----------|------| | `0x0001` | Measurement Read | uint8 | The current heart rate in beats per minute. | **Battery Service (Service ID: `0x2003`)** | Attribute ID | Attribute Name | Type | Data Type | Data | |--------------|----------------|------|-----------|------| | `0x0001` | Charge Level | Read | uint8 | The percentage of charge left in the smartstrap battery (between 0 and 100). | | `0x0002` | Capacity | Read | uint16 | The total capacity of the smartstrap battery in mAh when fully charged. | **Notification Handling** When a notification is received for this profile, a "Notification Info" message should be sent as described above.
{ "source": "google/pebble", "title": "devsite/source/_guides/smartstraps/smartstrap-protocol.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/smartstraps/smartstrap-protocol.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 24392 }
--- # Copyright 2025 Google LLC # # 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. title: Talking To Pebble description: | Information on how to implement the smartstrap protocol to talk to the Pebble accessory port. guide_group: smartstraps order: 2 related_docs: - Smartstrap related_examples: - title: Smartstrap Button Counter url: https://github.com/pebble-examples/smartstrap-button-counter - title: Smartstrap Library Test url: https://github.com/pebble-examples/smartstrap-library-test --- In order to communicate successfully with Pebble, the smartstrap hardware must correctly implement the smartstrap protocol as defined in {% guide_link smartstraps/smartstrap-protocol %}. ## Arduino Library For developers prototyping with some of the most common Arduino boards (based on the AVR ATmega 32U4, 2560, 328, or 328P chips), the simplest way of doing this is to use the [ArduinoPebbleSerial](https://github.com/pebble/arduinopebbleserial) library. This open-source reference implementation takes care of the smartstrap protocol and allows easy communication with the Pebble accessory port. Download the library as a .zip file. In the Arduino IDE, go to 'Sketch' -> 'Include Library' -> 'Add .ZIP LIbrary...'. Choose the library .zip file. This will import the library into Arduino and add the appropriate include statement at the top of the sketch: ```c++ #include <ArduinoPebbleSerial.h> ``` After including the ArduinoPebbleSerial library, begin the sketch with the standard template functions (these may already exist): ```c++ void setup() { } void loop() { } ``` ## Connecting to Pebble Declare the buffer to be used for transferring data (of type `uint8_t`), and its maximum length. This should be large enough for managing the largest possible request from the watch, but not so large that there is no memory left for the rest of the program: > Note: The buffer **must** be at least 6 bytes in length to handle internal > protocol messages. ```c++ // The buffer for transferring data static uint8_t s_data_buffer[256]; ``` Define which service IDs the strap will support. See {% guide_link smartstraps/smartstrap-protocol#generic-service-profile "Generic Service Profile" %} for details on which values may be used here. An example service ID and attribute ID both of value `0x1001` are shown below: ```c static const uint16_t s_service_ids[] = {(uint16_t)0x1001}; static const uint16_t s_attr_ids[] = {(uint16_t)0x1001}; ``` The last decision to be made before connection is which baud rate will be used. This will be the speed of the connection, chosen as one of the available baud rates from the `Baud` `enum`: ```c typedef enum { Baud9600, Baud14400, Baud19200, Baud28800, Baud38400, Baud57600, Baud62500, Baud115200, Baud125000, Baud230400, Baud250000, Baud460800, } Baud; ``` This should be chosen as the highest rate supported by the board used, to allow the watch to save power by sleeping as much as possible. The recommended value is `Baud57600` for most Arduino-like boards. ### Hardware Serial If using the hardware UART for the chosen board (the `Serial` library), initialize the ArduinoPebbleSerial library in the `setup()` function to prepare for connection: ```c++ // Setup the Pebble smartstrap connection ArduinoPebbleSerial::begin_hardware(s_data_buffer, sizeof(s_data_buffer), Baud57600, s_service_ids, 1); ``` ### Software Serial Alternatively, software serial emulation can be used for any pin on the chosen board that [supports interrupts](https://www.arduino.cc/en/Reference/AttachInterrupt). In this case, initialize the library in the following manner, where `pin` is the compatible pin number. For example, using Arduino Uno pin D8, specify a value of `8`. As with `begin_hardware()`, the baud rate and supported service IDs must also be provided here: ```c++ int pin = 8; // Setup the Pebble smartstrap connection using one wire software serial ArduinoPebbleSerial::begin_software(pin, s_data_buffer, sizeof(s_data_buffer), Baud57600, s_service_ids, 1); ``` ## Checking Connection Status Once the smartstrap has been physically connected to the watch and the connection has been established, calling `ArduinoPebbleSerial::is_connected()` will allow the program to check the status of the connection, and detect disconnection on the smartstrap side. This can be indicated to the wearer using an LED, for example: ```c++ if(ArduinoPebbleSerial::is_connected()) { // Connection is valid, turn LED on digitalWrite(7, HIGH); } else { // Connection is not valid, turn LED off digitalWrite(7, LOW); } ``` ## Processing Commands In each iteration of the `loop()` function, the program must allow the library to process any bytes which have been received over the serial connection using `ArduinoPebbleSerial::feed()`. This function will return `true` if a complete frame has been received, and set the values of the parameters to inform the program of which type of frame was received: ```c++ size_t length; RequestType type; uint16_t service_id; uint16_t attribute_id; // Check to see if a frame was received, and for which service and attribute if(ArduinoPebbleSerial::feed(&service_id, &attribute_id, &length, &type)) { // We got a frame! if((service_id == 0) && (attribute_id == 0)) { // This is a raw data service frame // Null-terminate and display what was received in the Arduino terminal s_data_buffer[min(length_read, sizeof(s_data_buffer))] = `\0`; Serial.println(s_data_buffer); } else { // This may be one of our service IDs, check it. if(service_id == s_service_ids[0] && attribute_id == s_attr_ids[0]) { // This frame is for our supported service! s_data_buffer[min(length_read, sizeof(s_data_buffer))] = `\0`; Serial.print("Write to service ID: "); Serial.print(service_id); Serial.print(" Attribute ID: "); Serial.print(attribute_id); Serial.print(": "); Serial.println(s_data_buffer); } } } ``` If the watch is requesting data, the library also allows the Arduino to respond back using `ArduinoPebbleSerial::write()`. This function accepts parameters to tell the connected watch which service and attribute is responding to the read request, as well is whether or not the read was successful: > Note: A write to the watch **must** occur during processing for a > `RequestType` of `RequestTypeRead` or `RequestTypeWriteRead`. ```c++ if(type == RequestTypeRead || type == RequestTypeWriteRead) { // The watch is requesting data, send a friendly response char *msg = "Hello, Pebble"; // Clear the buffer memset(s_data_buffer, 0, sizeof(s_data_buffer)); // Write the response into the buffer snprintf((char*)s_data_buffer, sizeof(s_data_buffer), "%s", msg); // Send the data to the watch for this service and attribute ArduinoPebbleSerial::write(true, s_data_buffer, strlen((char*)s_data_buffer)+1); } ``` ## Notifying the Watch To save power, it is strongly encouraged to design the communication scheme in such a way that avoids needing the watch to constantly query the status of the smartstrap, allowing it to sleep. To aid in this effort, the ArduinoPebbleSerial library includes the `ArduinoPebbleSerial::notify()` function to cause the watchapp to receive a ``SmartstrapNotifyHandler``. For example, to notify the watch once a second: ```c++ // The last time the watch was notified static unsigned long s_last_notif_time = 0; void loop() { /* other code */ // Notify the watch every second if (millis() - s_last_notif_time > 1000) { // Send notification with our implemented serviceID and attribute ID ArduinoPebbleSerial::notify(s_service_ids[0], s_attr_ids[0]); // Record the time of this notification s_last_notif_time = millis(); } } ```
{ "source": "google/pebble", "title": "devsite/source/_guides/smartstraps/talking-to-pebble.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/smartstraps/talking-to-pebble.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 8425 }
--- # Copyright 2025 Google LLC # # 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. title: Talking To Smartstraps description: | Information on how to use the Pebble C API to talk to a connected smartstrap. guide_group: smartstraps order: 3 platforms: - basalt - chalk - diorite - emery related_docs: - Smartstrap --- To talk to a connected smartstrap, the ``Smartstrap`` API is used to establish a connection and exchange arbitrary data. The exchange protocol is specified in {% guide_link smartstraps/smartstrap-protocol %} and most of it is abstracted by the SDK. This also includes handling of the {% guide_link smartstraps/smartstrap-protocol#link-control-profile "Link Control Profile" %}. Read {% guide_link smartstraps/talking-to-pebble %} to learn how to use an example library for popular Arduino microcontrollers to implement the smartstrap side of the protocol. > Note: Apps running on multiple hardware platforms that may or may not include > a smartstrap connector should use the `PBL_SMARTSTRAP` compile-time define (as > well as checking API return values) to gracefully handle when it is not > available. ## Services and Attributes ### Generic Service Profile The Pebble smartstrap protocol uses the concept of 'services' and 'attributes' to organize the exchange of data between the watch and the smartstrap. Services are identified by a 16-bit number. Some of these service identifiers have a specific meaning; developers should read {% guide_link smartstraps/smartstrap-protocol#supported-services-and-attributes "Supported Services and Attributes" %} for a complete list of reserved service IDs and ranges of service IDs that can be used for experimentation. Attributes are also identified by a 16-bit number. The meaning of attribute values is specific to the service of that attribute. The smartstrap protocol defines the list of attributes for some services, but developers are free to define their own list of attributes in their own services. This abstraction supports read and write operations on any attribute as well as sending notifications from the strap when an attribute value changes. This is called the Generic Service Profile and is the recommended way to exchange data with smartstraps. ### Raw Data Service Developers can also choose to use the Raw Data Service to minimize the overhead associated with transmitting data. To use this profile a Pebble developer will use the same APIs described in this guide with the service ID and attribute ID set to ``SMARTSTRAP_RAW_DATA_SERVICE_ID`` and ``SMARTSTRAP_RAW_DATA_ATTRIBUTE_ID`` SDK constants respectively. ## Manipulating Attributes The ``Smartstrap`` API uses the ``SmartstrapAttribute`` type as a proxy for an attribute on the smartstrap. It includes the service ID of the attribute, the ID of the attribute itself, as well as a data buffer that is used to store the latest read or written value of the attribute. Before you can read or write an attribute, you need to initialize a `SmartstrapAttribute` that will be used as a proxy for the attribute on the smartstrap. The first step developers should take is to decide upon and define their services and attributes: ```c // Define constants for your service ID, attribute ID // and buffer size of your attribute. static const SmartstrapServiceId s_service_id = 0x1001; static const SmartstrapAttributeId s_attribute_id = 0x0001; static const int s_buffer_length = 64; ``` Then, define the attribute globally: ```c // Declare an attribute pointer static SmartstrapAttribute *s_attribute; ``` Lastly create the attribute during app initialization, allocating its buffer: ```c // Create the attribute, and allocate a buffer for its data s_attribute = smartstrap_attribute_create(s_service_id, s_attribute_id, s_buffer_length); ``` Later on, APIs such as ``smartstrap_attribute_get_service_id()`` and ``smartstrap_attribute_get_attribute_id()`` can be used to confirm these values for any ``SmartstrapAttribute`` created previously. This is useful if an app deals with more than one service or attribute. Attributes can also be destroyed when an app is exiting or no longer requires them by using ``smartstrap_attribute_destroy()``: ```c // Destroy this attribute smartstrap_attribute_destroy(s_attribute); ``` ## Connecting to a Smartstrap The first thing a smartstrap-enabled app should do is call ``smartstrap_subscribe()`` to register the handler functions (described below) that will be called when smartstrap-related events occur. Such events can be one of four types. The ``SmartstrapServiceAvailabilityHandler`` handler, used when a smartstrap reports that a service is available, or has become unavailable. ```c static void strap_availability_handler(SmartstrapServiceId service_id, bool is_available) { // A service's availability has changed APP_LOG(APP_LOG_LEVEL_INFO, "Service %d is %s available", (int)service_id, is_available ? "now" : "NOT"); } ``` See below under [*Writing Data*](#writing-data) and [*Reading Data*](#reading-data) for explanations of the other callback types. With all four of these handlers in place, the subscription to the associated events can be registered. ```c // Subscribe to the smartstrap events smartstrap_subscribe((SmartstrapHandlers) { .availability_did_change = strap_availability_handler, .did_read = strap_read_handler, .did_write = strap_write_handler, .notified = strap_notify_handler }); ``` As with the other [`Event Services`](``Event Service``), the subscription can be removed at any time: ```c // Stop getting callbacks smartstrap_unsubscribe(); ``` The availability of a service can be queried at any time: ```c if(smartstrap_service_is_available(s_service_id)) { // Our service is available! } else { // Our service is not currently available, handle gracefully APP_LOG(APP_LOG_LEVEL_ERROR, "Service %d is not available.", (int)s_service_id); } ``` ## Writing Data The smartstrap communication model (detailed under {% guide_link smartstraps/smartstrap-protocol#communication-model "Communication Model" %}) uses the master-slave principle. This one-way relationship means that Pebble can request data from the smartstrap at any time, but the smartstrap cannot. However, the smartstrap may notify the watch that data is waiting to be read so that the watch can read that data at the next opportunity. To send data to a smartstrap an app must call ``smartstrap_attribute_begin_write()`` which will return a buffer to write into. When the app is done preparing the data to be sent in the buffer, it calls ``smartstrap_attribute_end_write()`` to actually send the data. ```c // Pointer to the attribute buffer size_t buff_size; uint8_t *buffer; // Begin the write request, getting the buffer and its length smartstrap_attribute_begin_write(attribute, &buffer, &buff_size); // Store the data to be written to this attribute snprintf((char*)buffer, buff_size, "Hello, smartstrap!"); // End the write request, and send the data, not expecting a response smartstrap_attribute_end_write(attribute, buff_size, false); ``` > Another message cannot be sent until the strap responds (a `did_write` > callback for Write requests, or `did_read` for Read/Write+Read requests) or > the timeout expires. Doing so will cause the API to return > ``SmartstrapResultBusy``. Read > {% guide_link smartstraps/talking-to-smartstraps#timeouts "Timeouts" %} for > more information on smartstrap timeouts. The ``SmartstrapWriteHandler`` will be called when the smartstrap has acknowledged the write operation (if using the Raw Data Service, there is no acknowledgement and the callback will be called when Pebble is done sending the frame to the smartstrap). If a read is requested (with the `request_read` parameter of ``smartstrap_attribute_end_write()``) then the read callback will also be called when the smartstrap sends the attribute value. ```c static void strap_write_handler(SmartstrapAttribute *attribute, SmartstrapResult result) { // A write operation has been attempted if(result != SmartstrapResultOk) { // Handle the failure APP_LOG(APP_LOG_LEVEL_ERROR, "Smartstrap error occured: %s", smartstrap_result_to_string(result)); } } ``` If a timeout occurs on a non-raw-data write request (with the `request_read` parameter set to `false`), ``SmartstrapResultTimeOut`` will be passed to the `did_write` handler on the watch side. ## Reading Data The simplest way to trigger a read request is to call ``smartstrap_attribute_read()``. Another way to trigger a read is to set the `request_read` parameter of ``smartstrap_attribute_end_write()`` to `true`. In both cases, the response will be received asynchronously and the ``SmartstrapReadHandler`` will be called when it is received. ```c static void strap_read_handler(SmartstrapAttribute *attribute, SmartstrapResult result, const uint8_t *data, size_t length) { if(result == SmartstrapResultOk) { // Data has been read into the data buffer provided APP_LOG(APP_LOG_LEVEL_INFO, "Smartstrap sent: %s", (char*)data); } else { // Some error has occured APP_LOG(APP_LOG_LEVEL_ERROR, "Error in read handler: %d", (int)result); } } static void read_attribute() { SmartstrapResult result = smartstrap_attribute_read(attribute); if(result != SmartstrapResultOk) { APP_LOG(APP_LOG_LEVEL_ERROR, "Error reading attribute: %s", smartstrap_result_to_string(result)); } } ``` > Note: ``smartstrap_attribute_begin_write()`` may not be called within a > `did_read` handler (``SmartstrapResultBusy`` will be returned). Similar to write requests, if a timeout occurs when making a read request the `did_read` handler will be called with ``SmartstrapResultTimeOut`` passed in the `result` parameter. ## Receiving Notifications To save as much power as possible, the notification mechanism can be used by the smartstrap to alert the watch when there is data that requires processing. When this happens, the ``SmartstrapNotifyHandler`` handler is called with the appropriate attribute provided. Developers can use this mechanism to allow the watch to sleep until it is time to read data from the smartstrap, or simply as a messsaging mechanism. ```c static void strap_notify_handler(SmartstrapAttribute *attribute) { // The smartstrap has emitted a notification for this attribute APP_LOG(APP_LOG_LEVEL_INFO, "Attribute with ID %d sent notification", (int)smartstrap_attribute_get_attribute_id(attribute)); // Some data is ready, let's read it smartstrap_attribute_read(attribute); } ``` ## Callbacks For Each Type of Request There are a few different scenarios that involve the ``SmartstrapReadHandler`` and ``SmartstrapWriteHandler``, where the callbacks to these ``SmartstrapHandlers`` will change depending on the type of request made by the watch. | Request Type | Callback Sequence | |--------------|-------------------| | Read only | `did_write` when the request is sent. `did_read` when the response arrives or an error (e.g.: a timeout) occurs. | | Write+Read request | `did_write` when the request is sent. `did_read` when the response arrives or an error (e.g.: a timeout) occurs. | | Write (Raw Data Service) | `did_write` when the request is sent. | | Write (any other service) | `did_write` when the write request is acknowledged by the smartstrap. | For Write requests only, `did_write` will be called when the attribute is ready for another request, and for Reads/Write+Read requests `did_read` will be called when the attribute is ready for another request. ## Timeouts Read requests and write requests to an attribute expect a response from the smartstrap and will generate a timeout error if the strap does not respond before the expiry of the timeout. The maximum timeout value supported is 1000ms, with the default value ``SMARTSTRAP_TIMEOUT_DEFAULT`` of 250ms. A smaller or larger value can be specified by the developer: ```c // Set a timeout of 500ms smartstrap_set_timeout(500); ``` ## Smartstrap Results When data is sent to the smartstrap, one of several results is possible. These are returned by various API functions (such as ``smartstrap_attribute_read()``), and are enumerated as follows: | Result | Value | Description | |--------|-------|-------------| | `SmartstrapResultOk` | `0` | No error occured. | | `SmartstrapResultInvalidArgs` | `1` | The arguments provided were invalid. | | `SmartstrapResultNotPresent` | `2` | The Smartstrap port is not present on this watch. | | `SmartstrapResultBusy` | `3` | The connection is currently busy. For example, this can happen if the watch is waiting for a response from the smartstrap. | | `SmartstrapResultServiceUnavailable` | `4` | Either a smartstrap is not connected or the connected smartstrap does not support the specified service. | | `SmartstrapResultAttributeUnsupported` | `5` | The smartstrap reported that it does not support the requested attribute. | | `SmartstrapResultTimeOut` | `6` | A timeout occured during the request. | The function shown below returns a human-readable string for each value, useful for debugging. ```c static char* smartstrap_result_to_string(SmartstrapResult result) { switch(result) { case SmartstrapResultOk: return "SmartstrapResultOk"; case SmartstrapResultInvalidArgs: return "SmartstrapResultInvalidArgs"; case SmartstrapResultNotPresent: return "SmartstrapResultNotPresent"; case SmartstrapResultBusy: return "SmartstrapResultBusy"; case SmartstrapResultServiceUnavailable: return "SmartstrapResultServiceUnavailable"; case SmartstrapResultAttributeUnsupported: return "SmartstrapResultAttributeUnsupported"; case SmartstrapResultTimeOut: return "SmartstrapResultTimeOut"; default: return "Not a SmartstrapResult value!"; } } ```
{ "source": "google/pebble", "title": "devsite/source/_guides/smartstraps/talking-to-smartstraps.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/smartstraps/talking-to-smartstraps.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 14647 }
--- # Copyright 2025 Google LLC # # 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. title: App Metadata description: | Details of the metadata that describes the app, such as its name, resources and capabilities. guide_group: tools-and-resources order: 0 --- {% alert notice %} This page applies only to developers using the SDK on their local machine; CloudPebble allows you to manages this part of development in 'Settings'. {% endalert %} ## Project Defaults After creating a new local SDK Pebble project, additional setup of the project behavior and metadata can be performed in the `package.json` file. By default, the `pebble new-project` command will create a template `package.json` metadata file, which can then be modified as required. The generated `package.json` metadata looks like this: ```js { "name": "example-app", "author": "MakeAwesomeHappen", "version": "1.0.0", "keywords": ["pebble-app"], "private": true, "dependencies": {}, "pebble": { "displayName": "example-app", "uuid": "5e5b3966-60b3-453a-a83b-591a13ae47d5", "sdkVersion": "3", "enableMultiJS": true, "targetPlatforms": [ "aplite", "basalt", "chalk" ], "watchapp": { "watchface": false }, "messageKeys": [ "dummy" ], "resources": { "media": [] } } } ``` {% alert notice %} Older projects might have an `appinfo.json` file instead of a `package.json`. You can run `pebble convert-project` to update these projects. {% endalert %} > Note: The `uuid` (Universally Unique IDentifier) field should be unique (as > the name implies) and always properly generated. To do this on Mac OS X or > Linux, use the `uuidgen` tool or a web service. Due to format requirements, > these should never be manually modified. ## Available Properties Options defined in `package.json` (Required fields shown in **bold**) are listed in the table below: | Property | Type | Default Value |Description | |:---------|:----:|:--------------|:------------| | **`pebble.uuid`** | UUID | Developer-defined | Unique identifier [(UUID v4)](http://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29) for the app. Generated by `pebble new-project`. | | **`name`** | String | Developer-defined | App's short name. This is only used by npm and can't contain any non-URL-safe characters. | | **`pebble.displayName`** | String | Developer-defined | App's long name. This is what the app will appear as on the appstore, phone and watch. | | **`author`** | String | `"MakeAwesomeHappen"` | Name of the app's developer. | | **`version`** | String | `"1.0.0"` | Version label for the app. Must use the format `major.minor.0`. | | **`pebble.sdkVersion`** | String | `"3"` | The major version of the SDK that this app is being written for. | | `pebble.targetPlatforms` | Array of strings | `["aplite", "basalt", "chalk"]` | Specify which platforms to build this app for. Read {% guide_link tools-and-resources/hardware-information %} for a list of available platforms. Defaults to all if omitted. | | `pebble.enableMultiJS` | Boolean | `true` | Enables [use of multiple JS files](/blog/2016/01/29/Multiple-JavaScript-Files/) in a project with a CommonJS-style `require` syntax. | | **`pebble.watchapp`** | Object | N/A | Used to configure the app behavior on the watch. See below for an example object. | | **`.watchface`** | Boolean | `false` | Field of `watchapp`. Set to `false` to behave as a watchapp. | | `.hiddenApp` | Boolean | `false` | Field of `watchapp`. Set to `true` to prevent the app from appearing in the system menu. | | `.onlyShownOnCommunication` | Boolean | `false` | Field of `watchapp`. Set to `true` to hide the app unless communicated with from a companion app. | | `pebble.capabilities` | Array of strings | None | List of capabilities that the app requires. The supported capabilities are `location`, `configurable` (detailed in {% guide_link communication/using-pebblekit-js %}), and `health` (detailed in {% guide_link events-and-services/health %}). | | `pebble.messageKeys` | Object | `["dummy"]` | Keys used for ``AppMessage`` and ``AppSync``. This is either a list of mapping of ``AppMessage`` keys. See {% guide_link communication/using-pebblekit-js %} for more information. | | `pebble.resources.media` | Object | `[]` | Contains an array of all of the media resources to be bundled with the app (Maximum 256 per app). See {% guide_link app-resources %} for more information. | | `pebble.resources.publishedMedia` | Object | | Used for {% guide_link user-interfaces/appglance-c "AppGlance Slices" %} and {% guide_link pebble-timeline/pin-structure "Timeline Pins" %}. See [Published Media](#published-media) for more information. > Note: `hiddenApp` and `onlyShownOnCommunication` are mutually exclusive. > `hiddenApp` will always take preference. ## Hidden Watchapp The example below shows an example `watchapp` object for a watchapp that is hidden until communicated with from a companion app. ```js "watchapp": { "watchface": false, "hiddenApp": false, "onlyShownOnCommunication": true } ``` ## Published Media Introduced in SDK 4.0, `publishedMedia` provides a mechanism for applications to specify image resources which can be used within {% guide_link user-interfaces/appglance-c "AppGlance Slices" %} or {% guide_link pebble-timeline/pin-structure "Timeline Pins" %}. The `publishedMedia` object allows your watchapp, Pebble mobile application and Pebble web services to determine which image resources to use, based on a static ID. Without this lookup table, the components would not be able to establish the correct resources to use after an update to the watchapp. Let's take a look at the structure of `publishedMedia` in more detail. We'll start by declaring some image resources which we can reference in `publishedMedia` later. In this example we have 'hot' and 'cold' icons, in 3 different sizes. ```js "resources": { "media": [ { "name": "WEATHER_HOT_ICON_TINY", "type": "bitmap", "file": "hot_tiny.png" }, { "name": "WEATHER_HOT_ICON_SMALL", "type": "bitmap", "file": "hot_small.png" }, { "name": "WEATHER_HOT_ICON_LARGE", "type": "bitmap", "file": "hot_large.png" }, { "name": "WEATHER_COLD_ICON_TINY", "type": "bitmap", "file": "cold_tiny.png" }, { "name": "WEATHER_COLD_ICON_SMALL", "type": "bitmap", "file": "cold_small.png" }, { "name": "WEATHER_COLD_ICON_LARGE", "type": "bitmap", "file": "cold_large.png" } ] } ``` Next we declare the `publishedMedia`: ```js "resources": { // ..... "publishedMedia": [ { "name": "WEATHER_HOT", "id": 1, "glance": "WEATHER_HOT_ICON_TINY", "timeline": { "tiny": "WEATHER_HOT_ICON_TINY", "small": "WEATHER_HOT_ICON_SMALL", "large": "WEATHER_HOT_ICON_LARGE" } }, { "name": "WEATHER_COLD", "id": 2, "glance": "WEATHER_COLD_ICON_TINY", "timeline": { "tiny": "WEATHER_COLD_ICON_TINY", "small": "WEATHER_COLD_ICON_SMALL", "large": "WEATHER_COLD_ICON_LARGE" } } ] } ``` As you can see above, we can declare multiple entries in `publishedMedia`. Let's look at the properties in more detail: * `name` - This must be a unique alias to reference each entry of the `publishedMedia` object. We use the `name` for the AppGlanceSlice icon or Timeline Pin icon, and the system will load the appropriate resource when required. The naming convention varies depending on where it's being used. For example, the AppGlance C API prefixes the name: `PUBLISHED_ID_WEATHER_HOT` but the other APIs use: `app://images/WEATHER_HOT`. * `id` - This must be a unique number within the set of `publishedMedia`. It must be greater than 0. * `glance` - Optional. This references the `resource` image which will be displayed if this `publishedMedia` is used as the `icon` of an ``AppGlanceSlice``. Size: 25x25. * `timeline` - Optional. This references the `resource` images which will be displayed if this `publishedMedia` is used for the various sizes of a timeline icon. All three sizes must be specified. Sizes: Tiny 25x25, Small 50x50, Large 80x80. > Your `publishedMedia` entry must include either `glance`, `timeline`, or both. > If you specify `glance` and `timeline`, the `glance` must be the same resource > as `timeline.tiny`. > If you remove a `publishedMedia` entry, you must not re-use the ID.
{ "source": "google/pebble", "title": "devsite/source/_guides/tools-and-resources/app-metadata.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/tools-and-resources/app-metadata.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 9041 }
--- # Copyright 2025 Google LLC # # 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. title: CloudPebble description: | How to use CloudPebble to create apps with no installation required. guide_group: tools-and-resources order: 1 --- [CloudPebble]({{ site.data.links.cloudpebble }}) is an online-only IDE (Integrated Development Environment) for easy creation of Pebble apps. It can be used as an alternative to the local SDK on Mac OSX and Linux, and is the recommended app development option for Windows users. Features include: * All-in-one project management, code editing, compilation, and installation. * Intelligent real-time code completion including project symbols. * Browser-based emulators for testing apps and generating screenshots without physical hardware. * Integration with GitHub. To get started, log in with a Pebble Account. This is the same account as is used for the Pebble Forums and the local SDK. Once logged in, a list of projects will be displayed. ## Creating a Project To create a new project, click the 'Create' button. ![create-project](/images/guides/tools-and-resources/create-project.png =480x) Fill out the form including the name of the project, which type of project it is, as well as the SDK version. Optionally begin with a project template. When done, click 'Create'. ## Code Editor The next screen will contain the empty project, unless a template was chosen. This is the code editor screen, with the main area on the right being used to write source files. ![empty-project](/images/guides/tools-and-resources/empty-project.png) The left-hand menu contains links to other useful screens: * Settings - Manage the metadata and behavior of the project as an analogue to the local SDK's `package.json` file. * Timeline - Test inserting and deleting {% guide_link pebble-timeline "Pebble timeline" %} pins. * Compilation - Compile and install the project, view app logs and screenshots. This screen also contains the emulator. * GitHub - Configure GitHub integration for this project. In addition, the 'Source Files' and 'Resources' sections will list the respective files as they are added to the project. As code is written, automatic code completion will suggest completed symbols as appropriate. ## Writing Some Code To begin an app from a blank project, click 'Add New' next to 'Source Files'. Choose an appropriate name for the first file (such as `main.c`), leave the target as 'App/Watchface', and click 'Create'. The main area of the code editor will now display the code in the new file, which begins with the standard include statement for the Pebble SDK: ```c #include <pebble.h> ``` To begin a runnable Pebble app, simply add the bare bones functions for initialization, the event loop, and deinitialization. From here everything else can be constructed: ```c void init() { } void deinit() { } int main() { init(); app_event_loop(); deinit(); } ``` The right-hand side of the code editor screen contains convenient buttons for use during development. | Button | Description | |:------:|:------------| | ![](/images/guides/tools-and-resources/icon-play.png) | Build and run the app as configured on the 'Compilation' screen. By default this will be the Basalt emulator. | | ![](/images/guides/tools-and-resources/icon-save.png) | Save the currently open file. | | ![](/images/guides/tools-and-resources/icon-reload.png) | Reload the currently open file. | | ![](/images/guides/tools-and-resources/icon-rename.png) | Rename the currently open file. | | ![](/images/guides/tools-and-resources/icon-delete.png) | Delete the currently open file. | ## Adding Project Resources Adding a resource (such as a bitmap or font) can be done in a similar manner as a new code file, by clicking 'Add New' next to 'Resources' in the left-hand pane. Choose the appropriate 'Resource Type' and choose an 'Identifier', which will be available in code, prefixed with `RESOURCE_ID_`. Depending on the chosen 'Resource Type', the remaining fields will vary: * If a bitmap, the options pertaining to storage and optimization will be displayed. It is recommended to use the 'Best' settings, but more information on specific optimization options can be found in the [*Bitmap Resources*](/blog/2015/12/02/Bitmap-Resources/#quot-bitmap-quot-to-the-rescue) blog post. * If a font, the specific characters to include (in regex form) and tracking adjust options are available to adjust the font, as well as a compatibility option that is best left to 'Latest'. * If a raw resource, no extra options are available, save the 'Target Platforms' option. Once the new resource has been configured, browse the the file itself and upload it by clicking 'Save'. ## Installing and Running Apps The app under development can be compiled and run using the 'play' button on the right-hand side of the code editor screen. If the compilation was successful, the app will be run as configured. If not, the 'Compilation' screen will be opened and the reason for failure can be seen by clicking 'Build Log' next to the appropriate item in the build log. The 'Compilation' screen can be thought of a comprehensive view of what the 'play' buttons does, with more control. Once all code errors have been fixed, clicking 'Run Build' will do just that. When the build is complete, options to install and run the app are presented. Clicking one of the hardware platform buttons will run the app on an emulator of that platform, while choosing 'Phone' and 'Install and Run' will install and run the app on a physical watch connected to any phone logged in with the same Pebble account. In addition to running apps, the 'Compilation' screen also offers the ability to view app log output and capture screenshots with the appropriate buttons. Lastly, the `.pbw` bundle can also be obtained for testing and distribution in the [Developer Portal](https://dev-portal.getpebble.com/). ### Interacting with the Emulator Once an app is installed and running in the emulator, button input can be simulated using the highlighted regions of the emulator view decoration. There are also additional options available under the 'gear' button. ![](/images/guides/tools-and-resources/gear-options.png) From this panel, muliple forms of input can be simulated: * Adjust the charge level of the emulated battery with the 'Battery' slider. * Set whether the emulated battery is in the charging state with the 'Charging' checkbox. * Set whether the Bluetooth connection is connected with the 'Bluetooth' checkbox. * Set whether the emulated watch is set to use 24- or 12-hour time format with the '24-hour' checkbox. * Open the app's configuration page (if applicable) with the 'App Config' button. This will use the URL passed to `Pebble.openURL()`. See {% guide_link user-interfaces/app-configuration %} for more information. * Emulate live input of the accelerometer and compass using a mobile device by clicking the 'Sensors' button and following the instructions. * Shut down the emulated watch with the 'Shut Down' button. ## UI Editor In addition to adding new code files and resources, it is also possible to create ``Window`` layouts using a GUI interface with the UI editor. To use this feature, create a new code file by clicking 'Add New' next to 'Source Files' and set the 'File Type' to 'Window Layout'. Choose a name for the window and click 'Create'. The main UI Editor screen will be displayed. This includes a preview of the window's layout, as well as details about the current element and a toolkit of new elements. This is shown in the image below: ![ui-editor](/images/guides/publishing-tools/ui-editor.png) Since the only UI element that exists at the moment is the window itself, the editor shows the options available for customizing this element's properties, e.g. its background color and whether or not it is fullscreen. ### Adding More UI Add a new UI element to the window by clicking on 'Toolkit', which contains a set of standard UI elements. Choose a ``TextLayer`` element, and all the available properties of the ``Layer`` to change its appearence and position will be displayed: ![ui-editor-textlayer](/images/guides/publishing-tools/ui-editor-textlayer.png) In addition to manually typing in the ``Layer``'s dimensions, use the anchor points on the preview of the ``Layer`` on the left of the editor to click and drag the size and position of the ``TextLayer``. ![ui-editor-drag](/images/guides/publishing-tools/ui-editor-drag.gif =148x) When satisfied with the new ``TextLayer``'s configuration, use the 'UI Editor' button on the right-hand side of the screen to switch back to the normal code editor screen, where the C code that represents the ``Layer`` just set up visually can be seen. An example of this generated code is shown below, along with the preview of that layout. ```c // BEGIN AUTO-GENERATED UI CODE; DO NOT MODIFY static Window *s_window; static GFont s_res_gothic_24_bold; static TextLayer *s_textlayer_1; static void initialise_ui(void) { s_window = window_create(); window_set_fullscreen(s_window, false); s_res_gothic_24_bold = fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD); // s_textlayer_1 s_textlayer_1 = text_layer_create(GRect(0, 0, 144, 40)); text_layer_set_text(s_textlayer_1, "Hello, CloudPebble!"); text_layer_set_text_alignment(s_textlayer_1, GTextAlignmentCenter); text_layer_set_font(s_textlayer_1, s_res_gothic_24_bold); layer_add_child(window_get_root_layer(s_window), (Layer *)s_textlayer_1); } static void destroy_ui(void) { window_destroy(s_window); text_layer_destroy(s_textlayer_1); } // END AUTO-GENERATED UI CODE ``` ![ui-editor-preview](/images/guides/publishing-tools/ui-editor-preview.png =148x) > Note: As marked above, the automatically generated code should **not** be > modified, otherwise it will not be possible to continue editing it with the > CloudPebble UI Editor. ### Using the New Window After using the UI Editor to create the ``Window``'s layout, use the two functions provided in the generated `.h` file to include it in the app: `main_window.h` ```c void show_main_window(void); void hide_main_window(void); ``` For example, call the `show_` function as part of the app's initialization procedure and the `hide_` function as part of its deinitialization. Be sure to include the new header file after `pebble.h`: ```c #include <pebble.h> #include "main_window.h" void init() { show_main_window(); } void deinit() { hide_main_window(); } int main(void) { init(); app_event_loop(); deinit(); } ```
{ "source": "google/pebble", "title": "devsite/source/_guides/tools-and-resources/cloudpebble.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/tools-and-resources/cloudpebble.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 11136 }
--- # Copyright 2025 Google LLC # # 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. title: Developer Connection description: | How to enable and use the Pebble Developer Connection to install and debug apps directly from a computer. guide_group: tools-and-resources order: 3 --- In order to install apps from the local SDK using the `pebble` tool or from [CloudPebble]({{ site.links.cloudpebble }}), the Pebble Android or iOS app must be set up to allow a connection from the computer to the watch. This enables viewing logs and installing apps directly from the development environment, speeding up development. Follow the steps illustrated below to get started. ## Android Instructions In the Pebble mobile app: * Open the overflow menu by tapping the three dot icon at the top right and tap *Settings*. ![](/images/guides/publishing-tools/enable-dev-android-1.png =300x) * Enable the *Developer Mode* option. ![](/images/guides/publishing-tools/enable-dev-android-2.png =300x) * Tap *Developer Connection* and enable the developer connection using the toggle at the top right. ![](/images/guides/publishing-tools/enable-dev-android-4.png =300x) * If using the `pebble` tool, make note of the 'Server IP'. If using CloudPebble, this will be handled automatically. ## iOS Instructions In the Pebble mobile app: * Open the left-hand menu and tap the *Settings* item. ![](/images/guides/publishing-tools/enable-dev-ios-1.png =300x) * Enable the Developer Mode using the toggle. ![](/images/guides/publishing-tools/enable-dev-ios-2.png =300x) * Return to the menu, then tap the *Developer* item. Enable the Developer Connection using the toggle at the top-right. ![](/images/guides/publishing-tools/enable-dev-ios-3.png =300x) * If using the `pebble` tool, make note of the phone's 'Listening on' IP address. If using CloudPebble, this will be handled automatically.
{ "source": "google/pebble", "title": "devsite/source/_guides/tools-and-resources/developer-connection.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/tools-and-resources/developer-connection.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 2427 }
--- # Copyright 2025 Google LLC # # 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. title: Hardware Information description: | Details of the the capabilities of the various Pebble hardware platforms. guide_group: tools-and-resources order: 4 --- The Pebble watch family comprises of multiple generations of hardware, each with unique sets of features and capabilities. Developers wishing to reach the maximum number of users will want to account for these differences when developing their apps. The table below details the differences between hardware platforms: {% include hardware-platforms.html %} See {% guide_link best-practices/building-for-every-pebble#available-defines-and-macros "Available Defines and Macros" %} for a complete list of compile-time defines available. **NOTE:** We'll be updating the "Building for Every Pebble Guide" and "Available Defines and Macros" list when we release the first preview version of SDK 4.0.
{ "source": "google/pebble", "title": "devsite/source/_guides/tools-and-resources/hardware-information.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/tools-and-resources/hardware-information.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 1441 }
--- # Copyright 2025 Google LLC # # 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. title: Tools and Resources description: | Information on all the software tools available when writing Pebble apps, as well as other resources. guide_group: tools-and-resources menu: false permalink: /guides/tools-and-resources/ generate_toc: false hide_comments: true --- This section of the developer guides contains information and resources surrounding management of SDK projects themselves, as well as additional information on using the Pebble emulator, CloudPebble, and the local SDK command-line utility. Developers looking to add internationalization support can also find information and tools for that purpose here. ## Contents {% include guides/contents-group.md group=page.group_data %}
{ "source": "google/pebble", "title": "devsite/source/_guides/tools-and-resources/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/tools-and-resources/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 1286 }
--- # Copyright 2025 Google LLC # # 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. title: Internationalization description: | How to localize an app to multiple languages. guide_group: tools-and-resources order: 5 --- When distributing an app in the Pebble appstore, it can be downloaded by Pebble users all over the world. Depending on the app, this means that developers may want to internationalize their apps for a varierty of different locales. The locale is the region in the world in which the user may be using an app. The strings used in the app to convey information should be available as translations in locales where the app is used by speakers of a different language. This is the process of localization. For example, users in France may prefer to see an app in French, if the translation is available. ## Internationalization on Pebble The Pebble SDK allows an app to be localized with the ``Internationalization`` API. Developers can use this to adjust how their app displays and behaves to cater for users in non-English speaking countries. By default all apps are assumed to be in English. Choose the user selected locale using ``i18n_get_system_locale()`` or to force one using ``setlocale()``. > Note: The app's locale also affects ``strftime()``, which will output > different strings for different languages. Bear in mind that these strings may > be different lengths and use different character sets, so the app's layout > should scale accordingly. ## Locales Supported By Pebble This is the set of locales that are currently supported: | Language | Region | Value returned by ``i18n_get_system_locale()`` | |----------|--------|------------------------------------------------| | English | United States | `"en_US"` | | French | France | `"fr_FR"` | | German | Germany | `"de_DE"` | | Spanish | Spain | `"es_ES"` | | Italian | Italy | `"it_IT"` | | Portuguese | Portugal | `"pt_PT"` | | Chinese | China | `"en_CN"` | | Chinese | Taiwan | `"en_TW"` | When the user's preferred language is set using the Pebble Time mobile app, the required characters will be loaded onto Pebble and will be used by the compatible system fonts. **This means that any custom fonts used should include the necessary locale-specific characters in order to display correctly.** ## Translating an App By calling `setlocale(LC_ALL, "")`, the app can tell the system that it supports internationalization. Use the value returned by ``setlocale()`` to translate any app strings. The implementation follows the [libc convention](https://www.gnu.org/software/libc/manual/html_node/Setting-the-Locale.html#Setting-the-Locale). Users may expect text strings, images, time display formats, and numbers to change if they use an app in a certain language. Below is a simple approach to providing a translation: ```c // Use selocale() to obtain the system locale for translation char *sys_locale = setlocale(LC_ALL, ""); // Set the TextLayer's contents depending on locale if (strcmp("fr_FR", sys_locale) == 0) { text_layer_set_text(s_output_layer, "Bonjour tout le monde!"); } else if ( /* Next locale string comparison */ ) { /* other language cases... */ } else { // Fall back to English text_layer_set_text(s_output_layer, "Hello, world!"); } ``` The above method is most suitable for a few strings in a small number of languages, but may become unwieldly if an app uses many strings. A more streamlined approach for these situations is given below in [*Using Locale Dictionaries*](#using-locale-dictionaries). ## Using the Locale in JavaScript Determine the language used by the user's phone in PebbleKit JS using the standard [`navigator`](http://www.w3schools.com/jsref/prop_nav_language.asp) property: ```js console.log('Phone language is ' + navigator.language); ``` ``` [INFO ] js-i18n-example__1.0/index.js:19 Phone language is en-US ``` This will reflect the user's choice of 'Language & Input' -> 'Language' on Android and 'General' -> 'Language & Region' -> 'i[Pod or Phone] Language' on iOS. > Note: Changing the language on these platforms will require a force close of > the Pebble app or device restart before changes take effect. ## Choosing the App's Locale It is also possible to explicitly set an app's locale using ``setlocale()``. This is useful for providing a language selection option for users who wish to do so. This function takes two arguments; the `category` and the `locale` string. To set localization **only** for the current time, use `LC_TIME` as the `category`, else use `LC_ALL`. The `locale` argument accepts the ISO locale code, such as `"fr_FR"`. Alternatively, set `locale` to `NULL` to query the current locale or `""` (an empty string) to set the app's locale to the system default. ```c // Force the app's locale to French setlocale(LC_ALL, "fr_FR"); ``` To adapt the way an application displays time, call `setlocale(LC_TIME, "")`. This will change the locale used to display time and dates in ``strftime()`` without translating any strings. ## Effect of Setting a Locale Besides returning the value of the current system locale, calling ``setlocale()`` will have a few other effects: * Translate month and day names returned by ``strftime()`` `%a`, `%A`, `%b`, and `%B`. * Translate the date and time representation returned by ``strftime()`` `%c`. * Translate the date representation returned by ``strftime()`` `%x`. Note that currently the SDK will not change the decimal separator added by the `printf()` family of functions when the locale changes; it will always be a `.` regardless of the currently selected locale. ## Using Locale Dictionaries A more advanced method to include multiple translations of strings in an app (without needing a large number of `if`, `else` statements) is to use the [Locale Framework](https://github.com/pebble-hacks/locale_framework). This framework works by wrapping every string in the project's `src` directory in the `_()` and replacing it with with a hashed value, which is then used with the current locale to look up the translated string from a binary resource file for that language. Instructions for using this framework are as follows: * Add `hash.h`, `localize.h` and `localize.c` to the project. This will be the `src` directory in the native SDK. * Include `localize.h` in any file to be localized: ```c #include "localize.h" ``` * Initalize the framework at the start of the app's execution: ```c int main(void) { // Init locale framework locale_init(); /** Other app setup code **/ } ``` * For every string in each source file to be translated, wrap it in `_()`: ```c text_layer_set_text(some_layer, _("Meal application")); ``` * Save all source files (this will require downloading and extracting the project from 'Settings' on CloudPebble), then run `get_dict.py` from the project root directory to get a JSON file containing the hashed strings to be translated. This file will look like the one below: ``` { "1204784839": "Breakfast Time", "1383429240": "Meal application", "1426781285": "A fine meal with family", "1674248270": "Lunch Time", "1753964326": "Healthy in a hurry", "1879903262": "Start your day right", "2100983732": "Dinner Time" } ``` * Create a copy of the JSON file and perform translation of each string, keeping the equivalent hash values the same. Name the file according to the language, such as `locale_french.json`. * Convert both JSON files into app binary resource files: ``` $ python dict2bin.py locale_english.json $ python dict2bin.py locale_french.json ``` * Add the output binary files as project resources as described in {% guide_link app-resources/raw-data-files %}. When the app is compiled and run, the `_()` macro will be replaced with calls to `locale_str()`, which will use the app's locale to load the translated string out of the binary resource files. > Note: If the translation lookup fails, the framework will fall back to the > English binary resource file. ## Publishing Localized Apps The appstore does not yet support localizing an app's resources (such as name, description, images etc), so use this guide to prepare the app itself. To cater for users viewing appstore listings in a different locale, include a list of supported languages in the listing description, which itself can be written in multiple languages. The format for a multi-lingual appstore description should display the supported languages at the top and a include a copy in each language, as shown in the example below: > Now supports - French, German and Spanish. > > This compass app allows you to navigate in any directions from your wrist! > Simply open the app and tilt to show the layout you prefer. > > Français > > Cette application de la boussole vous permet de naviguer dans toutes les > directions à partir de votre poignet! Il suffit d'ouvrir l'application et de > l'inclinaison pour montrer la disposition que vous préférez. > > Deutsch > > Dieser Kompass App ermöglicht es Ihnen, in jeder Richtung vom Handgelenk zu > navigieren! Öffnen Sie einfach die App und kippen, um das Layout Sie > bevorzugen zu zeigen. > > Español > > Esta aplicación brújula le permite navegar en cualquier dirección de la muñeca > ! Basta con abrir la aplicación y la inclinación para mostrar el diseño que > prefiera.
{ "source": "google/pebble", "title": "devsite/source/_guides/tools-and-resources/internationalization.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/tools-and-resources/internationalization.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 9829 }
--- # Copyright 2025 Google LLC # # 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. title: Command Line Tool description: | How to use the Pebble command line tool to build, debug, and emulate apps. guide_group: tools-and-resources order: 2 toc_max_depth: 2 --- {% alert notice %} This page applies only to developers using the SDK on their local machine; CloudPebble allows you to use many of these features in 'Compilation'. {% endalert %} The Pebble SDK includes a command line tool called `pebble`. This tool allows developers to create new projects, build projects, install apps on a watch and debug them. This tool is part of the SDK, but many of these functions are made available on [CloudPebble]({{ site.links.cloudpebble }}). ## Enabling the Developer Connection Most `pebble` commands allow interaction with a Pebble watch. This relies on a communication channel opened between the `pebble` tool on a computer and the Pebble mobile application on the phone. The `pebble` tool requires two configuration steps: 1. Enable the {% guide_link tools-and-resources/developer-connection %} in the Pebble mobile application. 2. Give the phone IP address to the `pebble` tool as shown below to communicate with a watch. This is not required when using the emulator or connecting via CloudPebble. ## Connecting to a Pebble There are four connection types possible with the command line tool. These can be used with any command that involves a watch, for example `install`. Connect to a physical watch connected to a phone on the same Wi-Fi network with `IP` [IP address](#enabling-the-developer-connection): ```nc|text $ pebble install --phone IP ``` Connect to an already running QEMU instance available on the `HOST` and `PORT` provided: ```nc|text $ pebble install --qemu HOST:PORT ``` Connect directly to a watch using a local Bluetooth connection, where `SERIAL` is the path to the device file. On OS X, this is similar to `/dev/cu.PebbleTimeXXXX-SerialPo` or `/dev/cu.PebbleXXXX-SerialPortSe`: > Note: Replace 'XXXX' with the actual value for the watch in question. ```nc|text $ pebble install --serial SERIAL ``` Alternatively, connect to a watch connected to the phone via the CloudPebble proxy, instead of local Wi-Fi. This removes the need for local inter-device communication, but still requires an internet connection on both devices: ```nc|text $ pebble install --cloudpebble ``` ## Configure the Pebble Tool Save the IP address of the phone in an environment variable: ```text $ export PEBBLE_PHONE=192.168.1.42 ``` Save the default choice of emulator platform: ```text $ export PEBBLE_EMULATOR=aplite ``` Save the default instance of QEMU: ```text $ export PEBBLE_QEMU=localhost:12344 ``` {% comment %} Always use the CloudPebble proxy: ```text $ export PEBBLE_CLOUDPEBBLE ``` {% endcomment %} ## Debugging Output Get up to four levels of `pebble` tool log verbosity. This is available for all commands: ```nc|text # Minimum level of verbosity $ pebble install -v # Maximum logging verbosity $ pebble install -vvvv ``` ## Installing Watchapps In addition to interacting with a physical Pebble watch, the Pebble emulator included in the local SDK (as well as on CloudPebble) can be used to run and debug apps without any physical hardware. Build an app, then use `pebble install` with the `--emulator` flag to choose between an emulator platform with `aplite`, `basalt`, or `chalk`. This allows developers to test out apps on all platforms before publishing to the Pebble appstore. For example, to emulate Pebble Time or Pebble Time Steel: ```nc|text $ pebble install --emulator basalt ``` > Note: If no `--emulator` parameter is specified, the running emulator will > be used. With a suitable color app installed, the emulator will load and display it: ![](/images/guides/publishing-tools/emulator.png) The Pebble physical buttons are emulated with the following mapping: * Back - Left arrow key * Up - Up arrow key * Select - Right arrow key * Down - Down arrow key ## Pebble Timeline in the Emulator With the emulator, it is also possible to view any past and future pins on the Pebble timeline by pressing Up or Down from the main watchface screen: <table> <tr> <td><img src="/assets/images/guides/publishing-tools/timeline-past.png"/></td> <td><img src="/assets/images/guides/publishing-tools/timeline-future.png"/></td> </tr> <tr style="text-align: center;"> <td>Timeline, past view</td><td>Timeline, future view</td> </tr> </table> ## Commands This section summarizes the available commands that can be used in conjunction with the `pebble` tool, on the applicable SDK versions. Most are designed to interact with a watch with `--phone` or the emulator with `--emulator`. ### Project Management #### new-project ```nc|text $ pebble new-project [--simple] [--javascript] [--worker] [--rocky] NAME ``` Create a new project called `NAME`. This will create a directory in the location the command is used, containing all essential project files. There are also a number of optional parameters that allow developers to choose features of the generated project to be created automatically: * `--simple` - Initializes the main `.c` file with a minimal app template. * `--javascript` - Creates a new application including a `./src/pkjs/index.js` file to quickly start an app with a PebbleKit JS component. Read {% guide_link communication/using-pebblekit-js %} for more information. * `--worker` - Creates a new application including a ` ./worker_src/NAME_worker.c` file to quickly start an app with a background worker. Read {% guide_link events-and-services/background-worker %} for more information. * `--rocky` - Creates a new Rocky.js application. Do not use any other optional parameters with this command. Read [Rocky.js documentation](/docs/rockyjs/) for more information. #### build ```nc|text $ pebble build ``` Compile and build the project into a `.pbw` file that can be installed on a watch or the emulator. #### install ```nc|text $ pebble install [FILE] ``` Install the current project to the watch connected to the phone with the given `IP` address, or to the emulator on the `PLATFORM`. See {% guide_link tools-and-resources/hardware-information %} for a list of available platforms. For example, the Aplite platform is specified as follows: ```nc|text $ pebble install --emulator aplite ``` It is also possible to use this command to install a pre-compiled `.pbw` `FILE`. In this case, the specified file will be installed instead of the current project. > Note: A `FILE` parameter is not required if running `pebble install` from > inside a buildable project directory. In this case, the `.pbw` package is > found automatically in `./build`. #### clean ```nc|text $ pebble clean ``` Delete all build files in `./build` to prepare for a clean build, which can resolve some state inconsistencies that may prevent the project from building. #### convert-project ```nc|text $ pebble convert-project ``` Convert an existing Pebble project to the current SDK. > Note: This will only convert the project, the source code will still have to > updated to match any new APIs. ### Pebble Interaction #### logs ```nc|text $ pebble logs ``` Continuously display app logs from the watch connected to the phone with the given `IP` address, or from a running emulator. App log output is colorized according to log level. This behavior can be forced on or off by specifying `--color` or `--no-color` respectively. #### screenshot ```nc|text $ pebble screenshot [FILENAME] ``` Take a screenshot of the watch connected to the phone with the given `IP` address, or from any running emulator. If provided, the output is saved to `FILENAME`. Color correction may be disabled by specifying `--no-correction`. The auto-opening of screenshots may also be disabled by specifying `--no-open`. #### ping ```nc|text $ pebble ping ``` Send a `ping` to the watch connected to the phone with the given `IP` address, or to any running emulator. #### repl ```nc|text $ pebble repl ``` Launch an interactive python shell with a `pebble` object to execute methods on, using the watch connected to the phone with the given `IP` address, or to any running emulator. #### data-logging ##### list ```nc|text $ pebble data-logging list ``` List the current data logging sessions on the watch. ##### download ```nc|text $ pebble data-logging download --session-id SESSION-ID FILENAME ``` Downloads the contents of the data logging session with the given ID (as given by `pebble data-logging list`) to the given filename. ##### disable-sends ```nc|text pebble data-logging disable-sends ``` Disables automatically sending data logging to the phone. This enables downloading data logging information without the phone's interference. It will also suspend any other app depending on data logging, which includes some firmware functionality. You should remember to enable it once you are done testing. ##### enable-sends ```nc|text pebble data-logging enable-sends ``` Re-enables automatically sending data logging information to the phone. ##### get-sends-enabled ```nc|text pebble data-logging get-sends-enabled ``` Indicates whether data logging is automatically sent to the phone. Change state with `enable-sends` and `disable-sends`. ### Emulator Interaction #### gdb ```nc|text $ pebble gdb ``` Use [GDB](https://www.gnu.org/software/gdb/) to step through and debug an app running in an emulator. Some useful commands are displayed in a cheat sheet when run with `--help` and summarized in the table below: > Note: Emulator commands that rely on interaction with the emulator (e.g. > `emu-app-config`) will not work while execution is paused with GDB. | Command | Description | |---------|-------------| | ctrl-C | Pause app execution. | | `continue` or `c` | Continue app execution. The app is paused while a `(gdb)` prompt is available. | | ctrl-D or `quit` | Quit gdb. | | `break` or `b` | Set a breakpoint. This can be either a symbol or a position: <br/>- `b function_name` to break when entering a function.<br/>- `b file_name.c:45` to break on line 45 of `file_name.c`. | | `step` or `s` | Step forward one line. | | `next` or `n` | Step *over* the current line, avoiding stopping for any functions it calls into. | | `finish` | Run forward until exiting the current stack frame. | | `backtrace` or `bt` | Print out the current call stack. | | `p [expression]` | Print the result of evaluating the given `expression`. | | `info args` | Show the values of arguments to the current function. | | `info locals` | Show local variables in the current frame. | | `bt full` | Show all local variables in all stack frames. | | `info break` | List break points (#1 is `<app_crashed>`, and is inserted by the `pebble` tool). | | `delete [n]` | Delete breakpoint #n. | Read {% guide_link debugging/debugging-with-gdb %} for help on using GDB to debug app. #### emu-control ```nc|text $ pebble emu-control [--port PORT] ``` Send near real-time accelerometer and compass readings from a phone, tablet, or computer to the emulator. When run, a QR code will be displayed in the terminal containing the IP address the device should connect to. Scanning the code will open this address in the device's browser. The IP address itself is also printed in the terminal for manual entry. `PORT` may be specified in order to make bookmarking the page easier. ![qr-code](/images/guides/publishing-tools/qr-code.png =450x) After connecting, the device's browser will display a UI with two modes of operation. ![accel-ui](/images/guides/publishing-tools/accel-ui.png =300x) The default mode will transmit sensor readings to the emulator as they are recorded. By unchecking the 'Use built-in sensors?' checkbox, manual values for the compass bearing and each of the accelerometer axes can be transmitted to the emulator by manipulating the compass rose or axis sliders. Using these UI elements will automatically uncheck the aforementioned checkbox. The values shown in bold are the Pebble SDK values, scaled relative to ``TRIG_MAX_ANGLE`` in the case of the compass bearing value, and in the range of +/-4000 (+/- 4g) for the accelerometer values. The physical measurements with associated units are shown beside in parentheses. #### emu-app-config ```nc|text $ pebble emu-app-config [--file FILE] ``` Open the app configuration page associated with the running app, if any. Uses the HTML configuration `FILE` if provided. See {% guide_link user-interfaces/app-configuration %} to learn about emulator- specific configuration behavior. #### emu-tap ```nc|text $ pebble emu-tap [--direction DIRECTION] ``` Send an accelerometer tap event to any running emulator. `DIRECTION` can be one of `x+`, `x-`, `y+`, `y-`, `z+`, or `z-`. #### emu-bt-connection ```nc|text $ pebble emu-bt-connection --connected STATE ``` Send a Bluetooth connection event to any running emulator. `STATE` can be either `yes` or `no` for connected and disconnected events respectively. > Note: The disconnected event may take a few seconds to occur. #### emu-compass ```nc|text $ pebble emu-compass --heading BEARING [--uncalibrated | --calibrating | --calibrated] ``` Send a compass update event to any running emulator. `BEARING` must be a number between `0` and `360` to be the desired compass bearing. Use any of `--uncalibrated`, `--calibrating`, or `--calibrated` to set the calibration state. #### emu-battery ```nc|text $ pebble emu-battery [--percent LEVEL] [--charging] ``` Send a battery update event to any running emulator. `LEVEL` must be a number between `0` and `100` to represent the new battery level. The presence of `--charging` will determine whether the charging cable is plugged in. #### emu-accel ```nc|text $ pebble emu-accel DIRECTION [--file FILE] ``` Send accelerometer data events to any running emulator. `DIRECTION` can be any of `tilt_left`, `tilt_right`, `tilt_forward`, `tilt_back`, `gravity+x`, `gravity-x`, `gravity+y`, `gravity-y`, `gravity+z`, `gravity-z` , and `custom`. If `custom` is selected, specify a `FILE` of comma-separated x, y, and z readings. #### transcribe ```nc|text $ pebble transcribe [message] [--error {connectivity,disabled,no-speech-detected}] ``` Run a server that will act as a transcription service. Run it before invoking the ``Dictation`` service in an app. If `message` is provided, the dictation will be successful and that message will be provided. If `--error` is provided, the dictation will fail with the given error. `--error` and `message` are mutually exclusive. ```nc|text $ pebble transcribe "Hello, Pebble!" ``` #### kill ```nc|text $ pebble kill ``` Kill both the Pebble emulator and phone simulator. #### emu-time-format ```nc|text pebble emu-time-format --format FORMAT ``` Set the time format of the emulator to either 12-hour or 24-hour format, with a `FORMAT` value of `12h` or `24h` respectively. #### emu-set-timeline-quick-view ```nc|text $ pebble emu-set-timeline-quick-view STATE ``` Show or hide the Timeline Quick View system overlay. STATE can be `on` or `off`. #### wipe ```nc|text $ pebble wipe ``` Wipe data stored for the Pebble emulator, but not the logged in Pebble account. To wipe **all** data, specify `--everything` when running this command. ### Pebble Account Management #### login ```nc|text $ pebble login ``` Launces a browser to log into a Pebble account, enabling use of `pebble` tool features such as pushing timeline pins. #### logout ```nc|text $ pebble logout ``` Logs out the currently logged in Pebble account from this instance of the command line tool. ### Pebble Timeline Interaction #### insert-pin ```nc|text $ pebble insert-pin FILE [--id ID] ``` Push a JSON pin `FILE` to the Pebble timeline. Specify the pin `id` in the `FILE` as `ID`. #### delete-pin ```nc|text $ pebble delete-pin FILE [--id ID] ``` Delete a pin previously pushed with `insert-pin`, specifying the same pin `ID`. ## Data Collection for Analytics When first run, the `pebble` tool will ask for permission to collect usage information such as which tools are used and the most common errors. Nothing personally identifiable is collected. This information will help us improve the SDK and is extremely useful for us, allowing us to focus our time on the most important parts of the SDK as discovered through these analytics. To disable analytics collection, run the following command to stop sending information: ```text # Mac OSX $ touch ~/Library/Application\ Support/Pebble\ SDK/NO_TRACKING # Other platforms $ touch ~/.pebble-sdk/NO_TRACKING ```
{ "source": "google/pebble", "title": "devsite/source/_guides/tools-and-resources/pebble-tool.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/tools-and-resources/pebble-tool.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 17239 }
--- # Copyright 2025 Google LLC # # 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. title: App Configuration (manual setup) description: | How to allow users to customize an app with a static configuration page. guide_group: order: 0 platform_choice: true --- > This guide provides the steps to manually create an app configuration page. > The preferred approach is to use > {% guide_link user-interfaces/app-configuration "Clay for Pebble" %} instead. Many watchfaces and apps in the Pebble appstore include the ability to customize their behavior or appearance through the use of a configuration page. This mechanism consists of an HTML form that passes the user's chosen configuration data to PebbleKit JS, which in turn relays it to the watchface or watchapp. The HTML page created needs to be hosted online, so that it is accessible to users via the Pebble application. If you do not want to host your own HTML page, you should follow the {% guide_link user-interfaces/app-configuration "Clay guide" %} to create a local config page. App configuration pages are powered by PebbleKit JS. To find out more about PebbleKit JS, {% guide_link communication/using-pebblekit-js "read the guide" %}. ## Adding Configuration ^LC^ For an app to be configurable, it must marked as 'configurable' in the app's {% guide_link tools-and-resources/app-metadata "`package.json`" %} `capabilities` array. The presence of this value tells the mobile app to display a gear icon next to the app, allowing users to access the configuration page. <div class="platform-specific" data-sdk-platform="local"> {% markdown %} ```js "capabilities": [ "configurable" ] ``` {% endmarkdown %} </div> ^CP^ For an app to be configurable, it must include the 'configurable' item in 'Settings'. The presence of this value tells the mobile app to display the gear icon that is associated with the ability to launch the config page. ## Choosing Key Values ^LC^ Since the config page must transmit the user's preferred options to the watchapp, the first step is to decide upon the ``AppMessage`` keys defined in `package.json` that will be used to represent the chosen value for each option on the config page: <div class="platform-specific" data-sdk-platform="local"> {% markdown %} ```js "messageKeys": [ "BackgroundColor", "ForegroundColor", "SecondTick", "Animations" ] ``` {% endmarkdown %} </div> ^CP^ Since the config page must transmit the user's preferred options to the watchapp, the first step is to decide upon the ``AppMessage`` keys defined in 'Settings' that will be used to represent each option on the config page. An example set is shown below: <div class="platform-specific" data-sdk-platform="cloudpebble"> {% markdown %} * `BackgroundColor` * `ForegroundColor` * `SecondTick` * `Animations` {% endmarkdown %} </div> These keys will automatically be available both in C on the watch and in PebbleKit JS on the phone. Each of these keys will apply to the appropriate input element on the config page, with the user's chosen value transmitted to the watchapp's ``AppMessageInboxReceived`` handler once the page is submitted. ## Showing the Config Page Once an app is marked as `configurable`, the PebbleKit JS component must implement `Pebble.openURL()` in the `showConfiguration` event handler in `index.js` to present the developer's HTML page when the user wants to configure the app: ```js Pebble.addEventListener('showConfiguration', function() { var url = 'http://example.com/config.html'; Pebble.openURL(url); }); ``` ## Creating the Config Page The basic structure of an HTML config page begins with a template HTML file: > Note: This page will be plain and unstyled. CSS styling must be performed > separately, and is not covered here. ```html <!DOCTYPE html> <html> <head> <title>Example Configuration</title> </head> <body> <p>This is an example HTML forms configuration page.</p> </body> </html> ``` The various UI elements the user will interact with to choose their preferences must be placed within the `body` tag, and will most likely take the form of HTML `input` elements. For example, a text input field for each of the example color options will look like the following: ```html <input id='background_color_input' type='text' value='#000000'> Background Color </input> <input id='foreground_color_input' type='text' value='#000000'> Foreground Color </input> ``` Other components include checkboxes, such as the two shown below for each of the example boolean options: ```html <input id='second_tick_checkbox' type='checkbox'> Enable Second Ticks </input> <input id='animations_checkbox' type='checkbox'> Show Animations </input> ``` The final element should be the 'Save' button, used to trigger the sending of the user's preferences back to PebbleKit JS. ```html <input id='submit_button' type='button' value='Save'> ``` ## Submitting Config Data Once the 'Save' button is pressed, the values of all the input elements should be encoded and included in the return URL as shown below: ```html <script> // Get a handle to the button's HTML element var submitButton = document.getElementById('submit_button'); // Add a 'click' listener submitButton.addEventListener('click', function() { // Get the config data from the UI elements var backgroundColor = document.getElementById('background_color_input'); var foregroundColor = document.getElementById('foreground_color_input'); var secondTickCheckbox = document.getElementById('second_tick_checkbox'); var animationsCheckbox = document.getElementById('animations_checkbox'); // Make a data object to be sent, coercing value types to integers var options = { 'background_color': parseInt(backgroundColor.value, 16), 'foreground_color': parseInt(foregroundColor.value, 16), 'second_ticks': secondTickCheckbox.checked == 'true' ? 1 : 0, 'animations': animationsCheckbox.checked == 'true' ? 1 : 0 }; // Determine the correct return URL (emulator vs real watch) function getQueryParam(variable, defaultValue) { var query = location.search.substring(1); var vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); if (pair[0] === variable) { return decodeURIComponent(pair[1]); } } return defaultValue || false; } var return_to = getQueryParam('return_to', 'pebblejs://close#'); // Encode and send the data when the page closes document.location = return_to + encodeURIComponent(JSON.stringify(options)); }); </script> ``` > Note: Remember to use `encodeURIComponent()` and `decodeURIComponent()` to > ensure the JSON data object is transmitted without error. ## Hosting the Config Page In order for users to access your configuration page, it needs to be hosted online somewhere. One potential free service to host your configuration page is Github Pages: [Github Pages](https://pages.github.com/) allow you to host your HTML, CSS and JavaScript files and directly access them from a special branch within your Github repo. This also has the added advantage of encouraging the use of version control. ## Relaying Data through PebbleKit JS When the user submits the HTML form, the page will close and the result is passed to the `webviewclosed` event handler in the PebbleKit JS `index.js` file: ```js Pebble.addEventListener('webviewclosed', function(e) { // Decode the user's preferences var configData = JSON.parse(decodeURIComponent(e.response)); } ``` The data from the config page should be converted to the appropriate keys and value types expected by the watchapp, and sent via ``AppMessage``: ```js // Send to the watchapp via AppMessage var dict = { 'BackgroundColor': configData.background_color, 'ForegroundColor': configData.foreground_color, 'SecondTick': configData.second_ticks, 'Animations': configData.animations }; // Send to the watchapp Pebble.sendAppMessage(dict, function() { console.log('Config data sent successfully!'); }, function(e) { console.log('Error sending config data!'); }); ``` ## Receiving Config Data Once the watchapp has called ``app_message_open()`` and registered an ``AppMessageInboxReceived`` handler, that handler will be called once the data has arrived on the watch. This occurs once the user has pressed the submit button. To obtain the example keys and values shown in this guide, simply look for and read the keys as ``Tuple`` objects using the ``DictionaryIterator`` provided: ```c static void inbox_received_handler(DictionaryIterator *iter, void *context) { // Read color preferences Tuple *bg_color_t = dict_find(iter, MESSAGE_KEY_BackgroundColor); if(bg_color_t) { GColor bg_color = GColorFromHEX(bg_color_t->value->int32); } Tuple *fg_color_t = dict_find(iter, MESSAGE_KEY_ForegroundColor); if(fg_color_t) { GColor fg_color = GColorFromHEX(fg_color_t->value->int32); } // Read boolean preferences Tuple *second_tick_t = dict_find(iter, MESSAGE_KEY_SecondTick); if(second_tick_t) { bool second_ticks = second_tick_t->value->int32 == 1; } Tuple *animations_t = dict_find(iter, MESSAGE_KEY_Animations); if(animations_t) { bool animations = animations_t->value->int32 == 1; } // App should now update to take the user's preferences into account reload_config(); } ``` Read the {% guide_link communication %} guides for more information about using the ``AppMessage`` API. If you're looking for a simpler option, we recommend using {% guide_link user-interfaces/app-configuration "Clay for Pebble" %} instead.
{ "source": "google/pebble", "title": "devsite/source/_guides/user-interfaces/app-configuration-static.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/user-interfaces/app-configuration-static.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 10168 }
--- # Copyright 2025 Google LLC # # 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. title: App Configuration description: | How to allow users to customize an app with a configuration page. guide_group: user-interfaces order: 0 platform_choice: true related_examples: - title: Clay Example url: https://github.com/pebble-examples/clay-example --- Many watchfaces and watchapps in the Pebble appstore include the ability to customize their behavior or appearance through the use of a configuration page. [Clay for Pebble](https://github.com/pebble/clay) is the recommended approach for creating configuration pages, and is what will be covered in this guide. If you need to host your own configuration pages, please follow our {% guide_link user-interfaces/app-configuration-static "Manual Setup" %} guide. ![Clay Sample](/images/guides/user-interfaces/app-configuration/clay-sample.png =200) Clay for Pebble dramatically simplifies the process of creating a configuration page, by allowing developers to define their application settings using a simple [JSON](https://en.wikipedia.org/wiki/JSON) file. Clay processes the JSON file and then dynamically generates a configuration page which matches the existing style of the Pebble mobile application, and it even works without an Internet connection. ## Enabling Configuration ^LC^ For an app to be configurable, it must include the 'configurable' item in `package.json`. <div class="platform-specific" data-sdk-platform="local"> {% markdown %} ```js "capabilities": [ "configurable" ] ``` {% endmarkdown %} </div> ^CP^ For an app to be configurable, it must include the 'configurable' item in 'Settings'. The presence of this value tells the mobile app to display the gear icon that is associated with the ability to launch the config page next to the app itself. ## Installing Clay Clay is available as a {% guide_link pebble-packages "Pebble Package" %}, so it takes minimal effort to install. ^LC^ Within your project folder, just type: <div class="platform-specific" data-sdk-platform="local"> {% markdown %} ```nc|text $ pebble package install pebble-clay ``` {% endmarkdown %} </div> ^CP^ Go to the 'Dependencies' tab, type 'pebble-clay' into the search box and press 'Enter' to add the dependency. ## Choosing messageKeys When passing data between the configuration page and the watch application, we define `messageKeys` to help us easily identify the different values. In this example, we're going to allow users to control the background color, foreground color, whether the watchface ticks on seconds and whether any animations are displayed. ^LC^ We define `messageKeys` in the `package.json` file for each configuration setting in our application: <div class="platform-specific" data-sdk-platform="local"> {% markdown %} ```js "messageKeys": [ "BackgroundColor", "ForegroundColor", "SecondTick", "Animations" ] ``` {% endmarkdown %} </div> ^CP^ We define `messageKeys` in the 'Settings' tab for each configuration setting in our application. The 'Message Key Assignment Kind' should be set to 'Automatic Assignment', then just enter each key name: <div class="platform-specific" data-sdk-platform="cloudpebble"> {% markdown %} ![CloudPebble Settings](/images/guides/user-interfaces/app-configuration/message-keys.png =400) {% endmarkdown %} </div> ## Creating the Clay Configuration ^LC^ The Clay configuration file (`config.js`) should be created in your `src/pkjs/` folder. It allows the easy definition of each type of HTML form entity that is required. These types include: ^CP^ The Clay configuration file (`config.js`) needs to be added to your project by adding a new 'Javascript' source file. It allows the easy definition of each type of HTML form entity that is required. These types include: * [Section](https://github.com/pebble/clay#section) * [Heading](https://github.com/pebble/clay#heading) * [Text](https://github.com/pebble/clay#text) * [Input](https://github.com/pebble/clay#input) * [Toggle](https://github.com/pebble/clay#toggle) * [Select](https://github.com/pebble/clay#select) * [Color Picker](https://github.com/pebble/clay#color-picker) * [Radio Group](https://github.com/pebble/clay#radio-group) * [Checkbox Group](https://github.com/pebble/clay#checkbox-group) * [Generic Button](https://github.com/pebble/clay#generic-button) * [Range Slider](https://github.com/pebble/clay#range-slider) * [Submit Button](https://github.com/pebble/clay#submit) In our example configuration page, we will add some introductory text, and group our fields into two sections. All configuration pages must have a submit button at the end, which is used to send the JSON data back to the watch. ![Clay](/images/guides/user-interfaces/app-configuration/clay-actual.png =200) Now start populating the configuration file with the sections you require, then add the required elements to each section. Be sure to assign the correct `messageKey` to each field. ```js module.exports = [ { "type": "heading", "defaultValue": "App Configuration" }, { "type": "text", "defaultValue": "Here is some introductory text." }, { "type": "section", "items": [ { "type": "heading", "defaultValue": "Colors" }, { "type": "color", "messageKey": "BackgroundColor", "defaultValue": "0x000000", "label": "Background Color" }, { "type": "color", "messageKey": "ForegroundColor", "defaultValue": "0xFFFFFF", "label": "Foreground Color" } ] }, { "type": "section", "items": [ { "type": "heading", "defaultValue": "More Settings" }, { "type": "toggle", "messageKey": "SecondTick", "label": "Enable Seconds", "defaultValue": false }, { "type": "toggle", "messageKey": "Animations", "label": "Enable Animations", "defaultValue": false } ] }, { "type": "submit", "defaultValue": "Save Settings" } ]; ``` ## Initializing Clay To initialize Clay, all you need to do is add the following JavaScript into your `index.js` file. ```js // Import the Clay package var Clay = require('pebble-clay'); // Load our Clay configuration file var clayConfig = require('./config'); // Initialize Clay var clay = new Clay(clayConfig); ``` <div class="platform-specific" data-sdk-platform="local"> {% markdown %} > When using the local SDK, it is possible to use a pure JSON > configuration file (`config.json`). If this is the case, you must not include > the `module.exports = []` in your configuration file, and you need to > `var clayConfig = require('./config.json');` {% endmarkdown %} </div> ## Receiving Config Data Within our watchapp we need to open a connection with ``AppMessage`` to begin listening for data from Clay, and also provide a handler to process the data once it has been received. ```c void prv_init(void) { // ... // Open AppMessage connection app_message_register_inbox_received(prv_inbox_received_handler); app_message_open(128, 128); // ... } ``` Once triggered, our handler will receive a ``DictionaryIterator`` containing ``Tuple`` objects for each `messageKey`. Note that the key names need to be prefixed with `MESSAGE_KEY_`. ```c static void prv_inbox_received_handler(DictionaryIterator *iter, void *context) { // Read color preferences Tuple *bg_color_t = dict_find(iter, MESSAGE_KEY_BackgroundColor); if(bg_color_t) { GColor bg_color = GColorFromHEX(bg_color_t->value->int32); } Tuple *fg_color_t = dict_find(iter, MESSAGE_KEY_ForegroundColor); if(fg_color_t) { GColor fg_color = GColorFromHEX(fg_color_t->value->int32); } // Read boolean preferences Tuple *second_tick_t = dict_find(iter, MESSAGE_KEY_SecondTick); if(second_tick_t) { bool second_ticks = second_tick_t->value->int32 == 1; } Tuple *animations_t = dict_find(iter, MESSAGE_KEY_Animations); if(animations_t) { bool animations = animations_t->value->int32 == 1; } } ``` ## Persisting Settings By default, Clay will persist your settings in localStorage within the mobile application. It is common practice to also save settings within the persistent storage on the watch. This creates a seemless experience for users launching your application, as their settings can be applied on startup. This means there isn't an initial delay while the settings are loaded from the phone. You could save each individual value within the persistent storage, or you could create a struct to hold all of your settings, and save that entire object. This has the benefit of simplicity, and because writing to persistent storage is slow, it also provides improved performance. ```c // Persistent storage key #define SETTINGS_KEY 1 // Define our settings struct typedef struct ClaySettings { GColor BackgroundColor; GColor ForegroundColor; bool SecondTick; bool Animations; } ClaySettings; // An instance of the struct static ClaySettings settings; // AppMessage receive handler static void prv_inbox_received_handler(DictionaryIterator *iter, void *context) { // Assign the values to our struct Tuple *bg_color_t = dict_find(iter, MESSAGE_KEY_BackgroundColor); if (bg_color_t) { settings.BackgroundColor = GColorFromHEX(bg_color_t->value->int32); } // ... prv_save_settings(); } // Save the settings to persistent storage static void prv_save_settings() { persist_write_data(SETTINGS_KEY, &settings, sizeof(settings)); } ``` You can see a complete implementation of persisting a settings struct in the [Pebble Clay Example]({{ site.links.examples_org }}/clay-example). ## What's Next If you're thinking that Clay won't be as flexible as hand crafting your own configuration pages, you're mistaken. Developers can extend the functionality of Clay in a number of ways: * Define a [custom function](https://github.com/pebble/clay#custom-function) to enhance the interactivity of the page. * [Override events](https://github.com/pebble/clay#handling-the-showconfiguration-and-webviewclosed-events-manually) and transform the format of the data before it's transferred to the watch. * Create and share your own [custom components](https://github.com/pebble/clay#custom-components). Why not find out more about [Clay for Pebble](https://github.com/pebble/clay) and perhaps even [contribute](https://github.com/pebble/clay/blob/master/CONTRIBUTING.md) to the project, it's open source!
{ "source": "google/pebble", "title": "devsite/source/_guides/user-interfaces/app-configuration.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/user-interfaces/app-configuration.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 11030 }
--- # Copyright 2025 Google LLC # # 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. title: App Exit Reason description: | Details on how to use the AppExitReason API guide_group: user-interfaces order: 1 related_docs: - AppExitReason --- Introduced in SDK v4.0, the ``AppExitReason`` API allows developers to provide a reason when terminating their application. The system uses these reasons to determine where the user should be sent when the current application terminates. At present there are only 2 ``AppExitReason`` states when exiting an application, but this may change in future updates. ### APP_EXIT_NOT_SPECIFIED This is the default state and when the current watchapp terminates. The user is returned to their previous location. If you do not specify an ``AppExitReason``, this state will be used automatically. ```c static void prv_deinit() { // Optional, default behavior // App will exit to the previous location in the system app_exit_reason_set(APP_EXIT_NOT_SPECIFIED); } ``` ### APP_EXIT_ACTION_PERFORMED_SUCCESSFULLY This state is primarily provided for developers who are creating one click action applications. When the current watchapp terminates, the user is returned to the default watchface. ```c static void prv_deinit() { // App will exit to default watchface app_exit_reason_set(APP_EXIT_ACTION_PERFORMED_SUCCESSFULLY); } ```
{ "source": "google/pebble", "title": "devsite/source/_guides/user-interfaces/app-exit-reason.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/user-interfaces/app-exit-reason.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 1880 }
--- # Copyright 2025 Google LLC # # 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. title: AppGlance C API description: | How to programatically update an app's app glance. guide_group: user-interfaces order: 2 related_docs: - AppGlanceSlice related_examples: - title: Hello World url: https://github.com/pebble-examples/app-glance-hello-world - title: Virtual Pet url: https://github.com/pebble-examples/app-glance-virtual-pet --- ## Overview An app's "glance" is the visual representation of a watchapp in the launcher and provides glanceable information to the user. The ``App Glance`` API, added in SDK 4.0, enables developers to programmatically set the icon and subtitle that appears alongside their app in the launcher. > The ``App Glance`` API is only applicable to watchapps, it is not supported by watchfaces. ## Glances and AppGlanceSlices An app's glance can change over time, and is defined by zero or more ``AppGlanceSlice`` each consisting of a layout (including a subtitle and icon), as well as an expiration time. AppGlanceSlices are displayed in the order they were added, and will persist until their expiration time, or another call to ``app_glance_reload()``. > To create an ``AppGlanceSlice`` with no expiration time, use > ``APP_GLANCE_SLICE_NO_EXPIRATION`` Developers can change their watchapp’s glance by calling the ``app_glance_reload()`` method, which first clears any existing app glance slices, and then loads zero or more ``AppGlanceSlice`` as specified by the developer. The ``app_glance_reload()`` method is invoked with two parameters: a pointer to an ``AppGlanceReloadCallback`` that will be invoked after the existing app glance slices have been cleared, and a pointer to context data. Developers can add new ``AppGlanceSlice`` to their app's glance in the ``AppGlanceReloadCallback``. ```c // ... // app_glance_reload callback static void prv_update_app_glance(AppGlanceReloadSession *session, size_t limit, void *context) { // Create and add app glance slices... } static void prv_deinit() { // deinit code // ... // Reload the watchapp's app glance app_glance_reload(prv_update_app_glance, NULL); } ``` ## The app_glance_reload Callback The ``app_glance_reload()`` is invoked with 3 parameters, a pointer to an ``AppGlanceReloadSession`` (which is used when invoking ``app_glance_add_slice()``) , the maximum number of slices you are able to add (as determined by the system at run time), and a pointer to the context data that was passed into ``app_glance_reload()``. The context data should contain all the information required to build the ``AppGlanceSlice``, and is typically cast to a specific type before being used. > The `limit` is currently set to 8 app glance slices per watchapp, though there > is no guarantee that this value will remain static, and developers should > always ensure they are not adding more slices than the limit. ![Hello World >{pebble-screenshot,pebble-screenshot--time-black}](/images/guides/appglance-c/hello-world-app-glance.png) In this example, we’re passing the string we would like to set as the subtitle, by using the context parameter. The full code for this example can be found in the [AppGlance-Hello-World](https://github.com/pebble-examples/app-glance-hello-world) repository. ```c static void prv_update_app_glance(AppGlanceReloadSession *session, size_t limit, void *context) { // This should never happen, but developers should always ensure they are // not adding more slices than are available if (limit < 1) return; // Cast the context object to a string const char *message = context; // Create the AppGlanceSlice // NOTE: When .icon is not set, the app's default icon is used const AppGlanceSlice entry = (AppGlanceSlice) { .layout = { .icon = APP_GLANCE_SLICE_DEFAULT_ICON, .subtitle_template_string = message }, .expiration_time = APP_GLANCE_SLICE_NO_EXPIRATION }; // Add the slice, and check the result const AppGlanceResult result = app_glance_add_slice(session, entry); if (result != APP_GLANCE_RESULT_SUCCESS) { APP_LOG(APP_LOG_LEVEL_ERROR, "AppGlance Error: %d", result); } } ``` > **NOTE:** When an ``AppGlanceSlice`` is loaded with the > ``app_glance_add_slice()`` method, the slice's > `layout.subtitle_template_string` is copied to the app's glance, meaning the > string does not need to persist after the call to ``app_glance_add_slice()`` > is made. ## Using Custom Icons In order to use custom icons within an ``AppGlanceSlice``, you need to use the new `publishedMedia` entry in the `package.json` file. * Create your images as 25px x 25px PNG files. * Add your images as media resources in the `package.json`. * Then add the `publishedMedia` declaration. You should end up with something like this: ```js "resources": { "media": [ { "name": "WEATHER_HOT_ICON_TINY", "type": "bitmap", "file": "hot_tiny.png" } ], "publishedMedia": [ { "name": "WEATHER_HOT", "id": 1, "glance": "WEATHER_HOT_ICON_TINY" } ] } ``` Then you can reference the `icon` by `name` in your ``AppGlanceSlice``. You must use the prefix `PUBLISHED_ID_`. E.g. `PUBLISHED_ID_WEATHER_HOT`. ## Subtitle Template Strings The `subtitle_template_string` field provides developers with a string formatting language for app glance subtitles. Developers can create a single app glance slice which updates automatically based upon a timestamp. For example, the template can be used to create a countdown until a timestamp (`time_until`), or the duration since a timestamp (`time_since`). The result from the timestamp evaluation can be output in various different time-format's, such as: * It's 50 days until New Year * Your Uber will arrive in 5 minutes * You are 15515 days old ### Template Structure The template string has the following structure: <code>{<strong><em>evaluation</em></strong>(<strong><em>timestamp</em></strong>)|format(<strong><em>parameters</em></strong>)}</code> Let's take a look at a simple countdown example: `Your Uber will arrive in 1 hr 10 min 4 sec` In this example, we need to know the time until our timestamp: `time_until(1467834606)`, then output the duration using an abbreviated time-format: `%aT`. `Your Uber will arrive in {time_until(1467834606)|format('%aT')}` ### Format Parameters Each format parameter is comprised of an optional predicate, and a time-format, separated by a colon. The time-format parameter is only output if the predicate evaluates to true. If a predicate is not supplied, the time-format is output by default. <code>format(<strong><em>predicate</em></strong>:'<strong><em>time-format</em></strong>')</code> #### Predicate The predicates are composed of a comparator and time value. For example, the difference between `now` and the timestamp evaluation is: * `>1d` Greater than 1 day * `<12m` Less than 12 months * `>=6m` Greater than or equal to 6 months * `<=1d12h` Less than or equal to 1 day, 12 hours. The supported time units are: * `d` (Day) * `H` (Hour) * `M` (Minute) * `S` (Second) #### Time Format The time-format is a single quoted string, comprised of a percent sign and an optional format flag, followed by a time unit. For example: `'%aT'` Abbreviated time. e.g. 1 hr 10 min 4 sec The optional format flags are: * `a` Adds abbreviated units (translated and with proper pluralization) (overrides 'u' flag) * `u` Adds units (translated and with proper pluralization) (overrides 'a' flag) * `-` Negates the input for this format specifier * `0` Pad value to the "expected" number of digits with zeros * `f` Do not modulus the value The following table demonstrates sample output for each time unit, and the effects of the format flags. |<small>Time Unit</small>|<small>No flag</small>|<small>'u' flag</small>|<small>'a' flag</small>|<small>'0' flag</small>|<small>'f' flag</small>| | --- | --- | --- | --- | --- | --- | | <small>**y**</small> | <small>&lt;year&gt;</small> | <small>&lt;year&gt; year(s)</small> | <small>&lt;year&gt; yr(s)</small> | <small>&lt;year, pad to 2&gt;</small> | <small>&lt;year, no modulus&gt;</small> | | <small>output:</small> | <small>4</small> | <small>4 years</small> | <small>4 yr</small> | <small>04</small> | <small>4</small> | | <small>**m**</small> | <small>&lt;month&gt;</small> | <small>&lt;month&gt; month(s)</small> | <small>&lt;month&gt; mo(s)</small> | <small>&lt;month, pad to 2&gt;</small> | <small>&lt;month, no modulus&gt;</small> | | <small>output:</small> | <small>8</small> | <small>8 months</small> | <small>8 mo</small> | <small>08</small> | <small>16</small> | | <small>**d**</small> | <small>&lt;day&gt;</small> | <small>&lt;day&gt; days</small> | <small>&lt;day&gt; d</small> | <small>&lt;day, pad to 2&gt;</small> | <small>&lt;day, no modulus&gt;</small> | | <small>output:</small> | <small>7</small> | <small>7 days</small> | <small>7 d</small> | <small>07</small> | <small>38</small> | | <small>**H**</small> | <small>&lt;hour&gt;</small> | <small>&lt;hour&gt; hour(s)</small> | <small>&lt;hour&gt; hr</small> | <small>&lt;hour, pad to 2&gt;</small> | <small>&lt;hour, no modulus&gt;</small> | | <small>output:</small> | <small>1</small> | <small>1 hour</small> | <small>1 hr</small> | <small>01</small> | <small>25</small> | | <small>**M**</small> | <small>&lt;minute&gt;</small> | <small>&lt;minute&gt; minute(s)</small> | <small>&lt;minute&gt; min</small> | <small>&lt;minute, pad to 2&gt;</small> | <small>&lt;minute, no modulus&gt;</small> | | <small>output:</small> | <small>22</small> | <small>22 minutes</small> | <small>22 min</small> | <small>22</small> | <small>82</small> | | <small>**S**</small> | <small>&lt;second&gt;</small> | <small>&lt;second&gt; second(s)</small> | <small>&lt;second&gt; sec</small> | <small>&lt;second, pad to 2&gt;</small> | <small>&lt;second, no modulus&gt;</small> | | <small>output:</small> | <small>5</small> | <small>5 seconds</small> | <small>5 sec</small> | <small>05</small> | <small>65</small> | | <small>**T**</small> | <small>%H:%0M:%0S (if &gt;= 1hr)<hr />%M:%0S (if &gt;= 1m)<hr />%S (otherwise)</small> | <small>%uH, %uM, and %uS<hr />%uM, and %uS<hr />%uS</small> | <small>%aH %aM %aS<hr />%aM %aS<hr />%aS</small> | <small>%0H:%0M:%0S (always)</small> | <small>%fH:%0M:%0S<hr />%M:%0S<hr />%S</small> | | <small>output:</small> | <small>1:53:20<hr />53:20<hr />20</small> | <small>1 hour, 53 minutes, and 20 seconds<hr />53 minutes, and 20 seconds<hr />20 seconds</small> | <small>1 hr 53 min 20 sec<hr />53 min 20 sec<hr />20 sec</small> | <small>01:53:20<hr />00:53:20<hr />00:00:20</small> | <small>25:53:20<hr />53:20<hr />20</small> | | <small>**R**</small> | <small>%H:%0M (if &gt;= 1hr)<hr />%M (otherwise)</small> | <small>%uH, and %uM<hr />%uM</small> | <small>%aH %aM<hr />%aM</small> | <small>%0H:%0M (always)</small> | <small>%fH:%0M<hr />%M</small> | | <small>output:</small> | <small>23:04<hr />15</small> | <small>23 hours, and 4 minutes<hr />15 minutes</small> | <small>23 hr 4 min<hr />15 min</small> | <small>23:04<hr />00:15</small> | <small>47:04<hr />15</small> | > Note: The time units listed above are not all available for use as predicates, but can be used with format flags. #### Advanced Usage We've seen how to use a single parameter to generate our output, but for more advanced cases, we can chain multiple parameters together. This allows for a single app glance slice to produce different output as each parameter evaluates successfully, from left to right. <code>format(<strong><em>predicate</em></strong>:'<strong><em>time-format</em></strong>', <strong><em>predicate</em></strong>:'<strong><em>time-format</em></strong>', <strong><em>predicate</em></strong>:'<strong><em>time-format</em></strong>')</code> For example, we can generate a countdown which displays different output before, during and after the event: * 100 days left * 10 hr 5 min 20 sec left * It's New Year! * 10 days since New Year To produce this output we could use the following template: `{time_until(1483228800)|format(>=1d:'%ud left',>0S:'%aT left',>-1d:\"It's New Year!\", '%-ud since New Year')}` ## Adding Multiple Slices An app's glance can change over time, with the slices being displayed in the order they were added, and removed after the `expiration_time`. In order to add multiple app glance slices, we simply need to create and add multiple ``AppGlanceSlice`` instances, with increasing expiration times. ![Virtual Pet >{pebble-screenshot,pebble-screenshot--time-black}](/images/guides/appglance-c/virtual-pet-app-glance.png) In the following example, we create a basic virtual pet that needs to be fed (by opening the app) every 12 hours, or else it runs away. When the app closes, we update the app glance to display a new message and icon every 3 hours until the virtual pet runs away. The full code for this example can be found in the [AppGlance-Virtual-Pet](https://github.com/pebble-examples/app-glance-virtual-pet) repository. ```c // How often pet needs to be fed (12 hrs) #define PET_FEEDING_FREQUENCY 3600*12 // Number of states to show in the launcher #define NUM_STATES 4 // Icons associated with each state const uint32_t icons[NUM_STATES] = { PUBLISHED_ID_ICON_FROG_HAPPY, PUBLISHED_ID_ICON_FROG_HUNGRY, PUBLISHED_ID_ICON_FROG_VERY_HUNGRY, PUBLISHED_ID_ICON_FROG_MISSING }; // Message associated with each state const char *messages[NUM_STATES] = { "Mmm, that was delicious!!", "I'm getting hungry..", "I'm so hungry!! Please feed me soon..", "Your pet ran away :(" }; static void prv_update_app_glance(AppGlanceReloadSession *session, size_t limit, void *context) { // Ensure we have sufficient slices if (limit < NUM_STATES) { APP_LOG(APP_LOG_LEVEL_DEBUG, "Error: app needs %d slices (%zu available)", NUM_STATES, limit); } time_t expiration_time = time(NULL); // Build and add NUM_STATES slices for (int i = 0; i < NUM_STATES; i++) { // Increment the expiration_time of the slice on each pass expiration_time += PET_FEEDING_FREQUENCY / NUM_STATES; // Set it so the last slice never expires if (i == (NUM_STATES - 1)) expiration_time = APP_GLANCE_SLICE_NO_EXPIRATION; // Create the slice const AppGlanceSlice slice = { .layout = { .icon = icons[i], .subtitle_template_string = messages[i] }, .expiration_time = expiration_time }; // add the slice, and check the result AppGlanceResult result = app_glance_add_slice(session, slice); if (result != APP_GLANCE_RESULT_SUCCESS) { APP_LOG(APP_LOG_LEVEL_ERROR, "Error adding AppGlanceSlice: %d", result); } } } static void prv_deinit() { app_glance_reload(prv_update_app_glance, NULL); } void main() { app_event_loop(); prv_deinit(); } ```
{ "source": "google/pebble", "title": "devsite/source/_guides/user-interfaces/appglance-c.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/user-interfaces/appglance-c.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 15487 }
--- # Copyright 2025 Google LLC # # 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. title: AppGlance in PebbleKit JS description: | How to update an app's glance using PebbleKit JS. guide_group: user-interfaces order: 2 related_docs: - AppGlanceSlice related_examples: - title: PebbleKit JS Example url: https://github.com/pebble-examples/app-glance-pebblekit-js-example --- ## Overview This guide explains how to manage your app's glances via PebbleKit JS. The ``App Glance`` API was added in SDK 4.0 and enables developers to programmatically set the icon and subtitle that appears alongside their app in the launcher. If you want to learn more about ``App Glance``, please read the {% guide_link user-interfaces/appglance-c %} guide. #### Creating Slices To create a slice, call `Pebble.appGlanceReload()`. The first parameter is an array of AppGlance slices, followed by a callback for success and one for failure. ```javascript // Construct the app glance slice object var appGlanceSlices = [{ "layout": { "icon": "system://images/HOTEL_RESERVATION", "subtitleTemplateString": "Nice Slice!" } }]; function appGlanceSuccess(appGlanceSlices, appGlanceReloadResult) { console.log('SUCCESS!'); }; function appGlanceFailure(appGlanceSlices, appGlanceReloadResult) { console.log('FAILURE!'); }; // Trigger a reload of the slices in the app glance Pebble.appGlanceReload(appGlanceSlices, appGlanceSuccess, appGlanceFailure); ``` #### Slice Icons There are two types of resources which can be used for AppGlance icons. * You can use system images. E.g. `system://images/HOTEL_RESERVATION` * You can use custom images by utilizing the {% guide_link tools-and-resources/app-metadata#published-media "Published Media" %} `name`. E.g. `app://images/*name*` #### Subtitle Template Strings The `subtitle_template_string` field provides developers with a string formatting language for app glance subtitles. Read more in the {% guide_link user-interfaces/appglance-c#subtitle-template-strings "AppGlance C guide" %}. #### Expiring Slices When you want your slice to expire automatically, just provide an `expirationTime` in [ISO date-time](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) format and the system will automatically remove it upon expiry. ```javascript var appGlanceSlices = [{ "layout": { "icon": "system://images/HOTEL_RESERVATION", "subtitleTemplateString": "Nice Slice!" }, "expirationTime": "2016-12-31T23:59:59.000Z" }]; ``` #### Creating Multiple Slices Because `appGlanceSlices` is an array, we can pass multiple slices within a single function call. The system is responsible for displaying the correct entries based on the `expirationTime` provided in each slice. ```javascript var appGlanceSlices = [{ "layout": { "icon": "system://images/DINNER_RESERVATION", "subtitleTemplateString": "Lunchtime!" }, "expirationTime": "2017-01-01T12:00:00.000Z" }, { "layout": { "icon": "system://images/RESULT_MUTE", "subtitleTemplateString": "Nap Time!" }, "expirationTime": "2017-01-01T14:00:00.000Z" }]; ``` #### Updating Slices There isn't a concept of updating an AppGlance slice, just call `Pebble.appGlanceReload()` with the new slices and any existing slices will be replaced. #### Deleting Slices All you need to do is pass an empty slices array and any existing slices will be removed. ```javascript Pebble.appGlanceReload([], appGlanceSuccess, appGlanceFailure); ```
{ "source": "google/pebble", "title": "devsite/source/_guides/user-interfaces/appglance-pebblekit-js.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/user-interfaces/appglance-pebblekit-js.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 4090 }
--- # Copyright 2025 Google LLC # # 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. title: AppGlance REST API description: | How to update an app's app glance using the REST API. guide_group: user-interfaces order: 2 related_docs: - AppGlanceSlice related_examples: - title: Node.js Example url: https://github.com/pebble-examples/app-glance-rest-example --- <div class="alert alert--fg-white alert--bg-purple"> {% markdown %} **Important Note** This API requires the forthcoming v4.1 of the Pebble mobile application in order to display App Glances on the connected watch. {% endmarkdown %} </div> ## Overview This guide explains how to use the AppGlance REST API. The ``App Glance`` API was added in SDK 4.0 and enables developers to programmatically set the icon and subtitle that appears alongside their app in the launcher. If you want to learn more about ``App Glance``, please read the {% guide_link user-interfaces/appglance-c %} guide. ## The REST API The AppGlance REST API shares many similarities with the existing {% guide_link pebble-timeline/timeline-public "timeline API" %}. Developers can push slices to the their app's glance using their own backend servers. Slices are created using HTTPS requests to the Pebble AppGlance REST API. #### Creating Slices To create a slice, send a `PUT` request to the following URL scheme: ```text PUT https://timeline-api.getpebble.com/v1/user/glance ``` Use the following headers, where `X-User-Token` is the user's timeline token (read {% guide_link pebble-timeline/timeline-js#get-a-timeline-token "Get a Timeline Token" %} to learn how to get a token): ```text Content-Type: application/json X-User-Token: a70b23d3820e9ee640aeb590fdf03a56 ``` Include the JSON object as the request body from a file such as `glance.json`. A sample of an object is shown below: ```json { "slices": [ { "layout": { "icon": "system://images/GENERIC_CONFIRMATION", "subtitleTemplateString": "Success!" } } ] } ``` #### Curl Example ```bash $ curl -X PUT https://timeline-api.getpebble.com/v1/user/glance \ --header "Content-Type: application/json" \ --header "X-User-Token: a70b23d3820e9ee640aeb590fdf03a56" \ -d @glance.json OK ``` #### Slice Icons There are two types of resources which can be used for AppGlance icons. * You can use system images. E.g. `system://images/HOTEL_RESERVATION` * You can use custom images by utilizing the {% guide_link tools-and-resources/app-metadata#published-media "Published Media" %} `name`. E.g. `app://images/*name*` #### Subtitle Template Strings The `subtitle_template_string` field provides developers with a string formatting language for app glance subtitles. Read more in the {% guide_link user-interfaces/appglance-c#subtitle-template-strings "AppGlance C guide" %}. #### Expiring Slices When you want your slice to expire automatically, just provide an `expirationTime` in [ISO date-time](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) format and the system will automatically remove it upon expiry. ```json { "slices": [ { "layout": { "icon": "system://images/GENERIC_CONFIRMATION", "subtitleTemplateString": "Success!" }, "expirationTime": "2016-12-31T23:59:59.000Z" } ] } ``` #### Creating Multiple Slices Because `slices` is an array, you can send multiple slices within a single request. The system is responsible for displaying the correct entries based on the `expirationTime` provided in each slice. ```json { "slices": [ { "layout": { "icon": "system://images/DINNER_RESERVATION", "subtitleTemplateString": "Lunchtime!" }, "expirationTime": "2017-01-01T12:00:00.000Z" }, { "layout": { "icon": "system://images/RESULT_MUTE", "subtitleTemplateString": "Nap Time!" }, "expirationTime": "2017-01-01T14:00:00.000Z" } ] } ``` #### Updating Slices There isn't a concept of updating an AppGlance slice, just send a request to the REST API with new slices and any existing slices will be replaced. #### Deleting Slices All you need to do is send an empty slices array to the REST API and any existing slices will be removed. ```json { "slices": [] } ``` ### Additional Notes We will not display App Glance slices for SDK 3.0 applications under any circumstances. Your watchapp needs to be compiled with SDK 4.0 in order to support App Glances.
{ "source": "google/pebble", "title": "devsite/source/_guides/user-interfaces/appglance-rest.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/user-interfaces/appglance-rest.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 5022 }
--- # Copyright 2025 Google LLC # # 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. title: Content Size description: | Details on how to use the ContentSize API to adapt your watchface layout based on user text size preferences. guide_group: user-interfaces order: 6 related_docs: - ContentSize - UnobstructedArea related_examples: - title: Simple Example url: https://github.com/pebble-examples/feature-content-size --- {% alert notice %} The ContentSize API is currently only available in SDK 4.2-BETA. {% endalert %} The [ContentSize](/docs/c/preview/User_Interface/Preferences/#preferred_content_size) API, added in SDK 4.2, allows developers to dynamically adapt their watchface and watchapp design based upon the system `Text Size` preference (*Settings > Notifications > Text Size*). While this allows developers to create highly accessible designs, it also serves to provide a mechanism for creating designs which are less focused upon screen size, and more focused upon content size. ![ContentSize >{pebble-screenshot,pebble-screenshot--time-red}](/images/guides/content-size/anim.gif) The `Text Size` setting displays the following options on all platforms: * Small * Medium * Large Whereas, the [ContentSize](/docs/c/preview/User_Interface/Preferences/#preferred_content_size) API will return different content sizes based on the `Text Size` setting, varying by platform. The list of content sizes is: * Small * Medium * Large * Extra Large An example of the varying content sizes: * `Text Size`: `small` on `Basalt` is `ContentSize`: `small` * `Text Size`: `small` on `Emery` is `ContentSize`: `medium` The following table describes the relationship between `Text Size`, `Platform` and `ContentSize`: Platform | Text Size: Small | Text Size: Medium | Text Size: Large ---------|------------------|-------------------|----------------- Aplite, Basalt, Chalk, Diorite | ContentSize: Small | ContentSize: Medium | ContentSize: Large Emery | ContentSize: Medium | ContentSize: Large | ContentSize: Extra Large > *At present the Text Size setting only affects notifications and some system UI components, but other system UI components will be updated to support ContentSize in future versions.* We highly recommend that developers begin to build and update their applications with consideration for [ContentSize](/docs/c/preview/User_Interface/Preferences/#preferred_content_size) to provide the best experience to users. ## Detecting ContentSize In order to detect the current [ContentSize](/docs/c/preview/User_Interface/Preferences/#preferred_content_size) developers can use the ``preferred_content_size()`` function. The [ContentSize](/docs/c/preview/User_Interface/Preferences/#preferred_content_size) will never change during runtime, so it's perfectly acceptable to check this once during `init()`. ```c static PreferredContentSize s_content_size; void init() { s_content_size = preferred_content_size(); // ... } ``` ## Adapting Layouts There are a number of different approaches to adapting the screen layout based upon content size. You could change font sizes, show or hide design elements, or even present an entirely different UI. In the following example, we will change font sizes based on the [ContentSize](/docs/c/preview/User_Interface/Preferences/#preferred_content_size) ```c static TextLayer *s_text_layer; static PreferredContentSize s_content_size; void init() { s_content_size = preferred_content_size(); // ... switch (s_content_size) { case PreferredContentSizeMedium: // Use a medium font text_layer_set_font(s_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD)); break; case PreferredContentSizeLarge: case PreferredContentSizeExtraLarge: // Use a large font text_layer_set_font(s_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD)); break; default: // Use a small font text_layer_set_font(s_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14_BOLD)); break; } // ... } ``` ## Additional Considerations When developing an application which dynamically adjusts based on the [ContentSize](/docs/c/preview/User_Interface/Preferences/#preferred_content_size) setting, try to avoid using fixed widths and heights. Calculate coordinates and dimensions based upon the size of the root layer, ``UnobstructedArea`` and [ContentSize](/docs/c/preview/User_Interface/Preferences/#preferred_content_size)
{ "source": "google/pebble", "title": "devsite/source/_guides/user-interfaces/content-size.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/user-interfaces/content-size.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 4968 }
--- # Copyright 2025 Google LLC # # 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. title: User Interfaces description: | How to build app user interfaces. Includes information on events, persistent storage, background worker, wakeups and app configuration. guide_group: user-interfaces menu: false permalink: /guides/user-interfaces/ generate_toc: false hide_comments: true --- The User Intefaces section of the developer guide contains information on using other the Pebble SDK elements that contribute to interface with the user in some way, shape, or form. For example, ``Layer`` objects form the foundation of all app user interfaces, while a configuration page asks a user for their input in terms of preferences. Graphics-specific UI elements and resources are discussed in the {% guide_link graphics-and-animations %} and {% guide_link app-resources %} sections. ## Contents {% include guides/contents-group.md group=page.group_data %}
{ "source": "google/pebble", "title": "devsite/source/_guides/user-interfaces/index.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/user-interfaces/index.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 1448 }
--- # Copyright 2025 Google LLC # # 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. title: Layers description: | How to use standard Layer components to build an app's UI. guide_group: user-interfaces order: 3 related_docs: - Layer - LayerUpdateProc - Window - TextLayer - BitmapLayer - MenuLayer - ScrollLayer --- The ``Layer`` and associated subclasses (such as ``TextLayer`` and ``BitmapLayer``) form the foundation of the UI for every Pebble watchapp or watchface, and are added to a ``Window`` to construct the UI's design. Each ``Layer`` type contains at least three basic elements: * Frame - contains the position and dimensions of the ``Layer``, relative to the parent object. * Bounds - contains the drawable bounding box within the frame. This allows only a portion of the layer to be visible, and is relative to the ``Layer`` frame. * Update procedure - the function that performs the drawing whenever the ``Layer`` is rendered. The subclasses implement a convenience update procedure with additional data to achieve their specialization. ## Layer Heirachy Every app must consist of at least one ``Window`` in order to successfully launch. Mutiple ``Layer`` objects are added as children of the ``Window``, which itself contains a ``Layer`` known as the 'root layer'. When the ``Window`` is rendered, each child ``Layer`` is rendered in the order in which they were added. For example: ```c static Window *s_main_window; static BitmapLayer *s_background_layer; static TextLayer *s_time_layer; ``` ```c // Get the Window's root layer Layer *root_layer = window_get_root_layer(s_main_window); /* set up BitmapLayer and TextLayer */ // Add the background layer first, so that it is drawn behind the time layer_add_child(root_layer, bitmap_layer_get_layer(s_background_layer)); // Add the time layer second layer_add_child(root_layer, text_layer_get_layer(s_time_layer)); ``` Once added to a ``Window``, the ordering of each ``Layer`` cannot be modified, but one can be placed at the front by removing and re-adding it to the heirachy: ```c // Bring a layer to the front layer_remove_from_parent(s_some_layer); layer_add_child(root_layer, s_some_layer); ``` ## Update Procedures For creating custom drawing implementations, the basic ``Layer`` update procedure can be reassigned to one created by a developer. This takes the form of a ``LayerUpdateProc``, and provides a [`GContext`](``Graphics Context``) object which can be used for drawing primitive shapes, paths, text, and images. > Note: See {% guide_link graphics-and-animations %} for more information on > drawing with the graphics context. ```c static void layer_update_proc(Layer *layer, GContext *ctx) { // Custom drawing happens here } ``` This function must then be assigned to the ``Layer`` that will be drawn with it: ```c // Set this Layer's update procedure layer_set_update_proc(s_some_layer, layer_update_proc); ``` The update procedure will be called every time the ``Layer`` must be redrawn. This is typically when any other ``Layer`` requests a redraw, the ``Window`` is shown/hidden, the heirarchy changes, or a modal (such as a notification) appears. The ``Layer`` can also be manually marked as 'dirty', and will be redrawn at the next opportunity (usually immediately): ```c // Request a redraw layer_mark_dirty(s_some_layer); ``` ## Layer Subclasses For convenience, there are multiple subclasses of ``Layer`` included in the Pebble SDK to allow developers to easily construct their app's UI. Each should be created when the ``Window`` is loading (using the `.load` ``WindowHandler``) and destroyed when it is unloading (using `.the unload` ``WindowHandler``). These are briefly outlined below, alongside a simple usage example split into three code snippets - the element declarations, the setup procedure, and the teardown procedure. ### TextLayer The ``TextLayer`` is the most commonly used subclass of ``Layer``, and allows apps to render text using any available font, with built-in behavior to handle text color, line wrapping, alignment, etc. ```c static TextLayer *s_text_layer; ``` ```c // Create a TextLayer s_text_layer = text_layer_create(bounds); // Set some properties text_layer_set_text_color(s_text_layer, GColorWhite); text_layer_set_background_color(s_text_layer, GColorBlack); text_layer_set_overflow_mode(s_text_layer, GTextOverflowModeWordWrap); text_layer_set_alignment(s_text_layer, GTextAlignmentCenter); // Set the text shown text_layer_set_text(s_text_layer, "Hello, World!"); // Add to the Window layer_add_child(root_layer, text_layer_get_layer(s_text_layer)); ``` ```c // Destroy the TextLayer text_layer_destroy(s_text_layer); ``` ### BitmapLayer The ``BitmapLayer`` provides an easy way to show images loaded into ``GBitmap`` objects from an image resource. Images shown using a ``BitmapLayer`` are automatically centered within the bounds provided to ``bitmap_layer_create()``. Read {% guide_link app-resources/images %} to learn more about using image resources in apps. > Note: PNG images with transparency should use `bitmap` resource type, and use > the ``GCompOpSet`` compositing mode when being displayed, as shown below. ```c static BitmapLayer *s_bitmap_layer; static GBitmap *s_bitmap; ``` ```c // Load the image s_bitmap = gbitmap_create_with_resource(RESOURCE_ID_EXAMPLE_IMAGE); // Create a BitmapLayer s_bitmap_layer = bitmap_layer_create(bounds); // Set the bitmap and compositing mode bitmap_layer_set_bitmap(s_bitmap_layer, s_bitmap); bitmap_layer_set_compositing_mode(s_bitmap_layer, GCompOpSet); // Add to the Window layer_add_child(root_layer, bitmap_layer_get_layer(s_bitmap_layer)); ``` ```c // Destroy the BitmapLayer bitmap_layer_destroy(s_bitmap_layer); ``` ### StatusBarLayer If a user needs to see the current time inside an app (instead of exiting to the watchface), the ``StatusBarLayer`` component can be used to display this information at the top of the ``Window``. Colors and separator display style can be customized. ```c static StatusBarLayer *s_status_bar; ``` ```c // Create the StatusBarLayer s_status_bar = status_bar_layer_create(); // Set properties status_bar_layer_set_colors(s_status_bar, GColorBlack, GColorBlueMoon); status_bar_layer_set_separator_mode(s_status_bar, StatusBarLayerSeparatorModeDotted); // Add to Window layer_add_child(root_layer, status_bar_layer_get_layer(s_status_bar)); ``` ```c // Destroy the StatusBarLayer status_bar_layer_destroy(s_status_bar); ``` ### MenuLayer The ``MenuLayer`` allows the user to scroll a list of options using the Up and Down buttons, and select an option to trigger an action using the Select button. It differs from the other ``Layer`` subclasses in that it makes use of a number of ``MenuLayerCallbacks`` to allow the developer to fully control how it renders and behaves. Some minimum example callbacks are shown below: ```c static MenuLayer *s_menu_layer; ``` ```c static uint16_t get_num_rows_callback(MenuLayer *menu_layer, uint16_t section_index, void *context) { const uint16_t num_rows = 5; return num_rows; } static void draw_row_callback(GContext *ctx, const Layer *cell_layer, MenuIndex *cell_index, void *context) { static char s_buff[16]; snprintf(s_buff, sizeof(s_buff), "Row %d", (int)cell_index->row); // Draw this row's index menu_cell_basic_draw(ctx, cell_layer, s_buff, NULL, NULL); } static int16_t get_cell_height_callback(struct MenuLayer *menu_layer, MenuIndex *cell_index, void *context) { const int16_t cell_height = 44; return cell_height; } static void select_callback(struct MenuLayer *menu_layer, MenuIndex *cell_index, void *context) { // Do something in response to the button press } ``` ```c // Create the MenuLayer s_menu_layer = menu_layer_create(bounds); // Let it receive click events menu_layer_set_click_config_onto_window(s_menu_layer, window); // Set the callbacks for behavior and rendering menu_layer_set_callbacks(s_menu_layer, NULL, (MenuLayerCallbacks) { .get_num_rows = get_num_rows_callback, .draw_row = draw_row_callback, .get_cell_height = get_cell_height_callback, .select_click = select_callback, }); // Add to the Window layer_add_child(root_layer, menu_layer_get_layer(s_menu_layer)); ``` ```c // Destroy the MenuLayer menu_layer_destroy(s_menu_layer); ``` ### ScrollLayer The ``ScrollLayer`` provides an easy way to use the Up and Down buttons to scroll large content that does not all fit onto the screen at the same time. The usage of this type differs from the others in that the ``Layer`` objects that are scrolled are added as children of the ``ScrollLayer``, which is then in turn added as a child of the ``Window``. The ``ScrollLayer`` frame is the size of the 'viewport', while the content size determines how far the user can scroll in each direction. The example below shows a ``ScrollLayer`` scrolling some long text, the total size of which is calculated with ``graphics_text_layout_get_content_size()`` and used as the ``ScrollLayer`` content size. > Note: The scrolled ``TextLayer`` frame is relative to that of its parent, the > ``ScrollLayer``. ```c static TextLayer *s_text_layer; static ScrollLayer *s_scroll_layer; ``` ```c GFont font = fonts_get_system_font(FONT_KEY_GOTHIC_28_BOLD); // Find the bounds of the scrolling text GRect shrinking_rect = GRect(0, 0, bounds.size.w, 2000); char *text = "Example text that is really really really really really \ really really really really really really long"; GSize text_size = graphics_text_layout_get_content_size(text, font, shrinking_rect, GTextOverflowModeWordWrap, GTextAlignmentLeft); GRect text_bounds = bounds; text_bounds.size.h = text_size.h; // Create the TextLayer s_text_layer = text_layer_create(text_bounds); text_layer_set_overflow_mode(s_text_layer, GTextOverflowModeWordWrap); text_layer_set_font(s_text_layer, font); text_layer_set_text(s_text_layer, text); // Create the ScrollLayer s_scroll_layer = scroll_layer_create(bounds); // Set the scrolling content size scroll_layer_set_content_size(s_scroll_layer, text_size); // Let the ScrollLayer receive click events scroll_layer_set_click_config_onto_window(s_scroll_layer, window); // Add the TextLayer as a child of the ScrollLayer scroll_layer_add_child(s_scroll_layer, text_layer_get_layer(s_text_layer)); // Add the ScrollLayer as a child of the Window layer_add_child(root_layer, scroll_layer_get_layer(s_scroll_layer)); ``` ```c // Destroy the ScrollLayer and TextLayer scroll_layer_destroy(s_scroll_layer); text_layer_destroy(s_text_layer); ``` ### ActionBarLayer The ``ActionBarLayer`` allows apps to use the familiar black right-hand bar, featuring icons denoting the action that will occur when each button on the right hand side is pressed. For example, 'previous track', 'more actions', and 'next track' in the built-in Music app. For three or fewer actions, the ``ActionBarLayer`` can be more appropriate than a ``MenuLayer`` for presenting the user with a list of actionable options. Each action's icon must also be loaded into a ``GBitmap`` object from app resources. The example below demonstrates show to set up an ``ActionBarLayer`` showing an up, down, and checkmark icon for each of the buttons. ```c static ActionBarLayer *s_action_bar; static GBitmap *s_up_bitmap, *s_down_bitmap, *s_check_bitmap; ``` ```c // Load icon bitmaps s_up_bitmap = gbitmap_create_with_resource(RESOURCE_ID_UP_ICON); s_down_bitmap = gbitmap_create_with_resource(RESOURCE_ID_DOWN_ICON); s_check_bitmap = gbitmap_create_with_resource(RESOURCE_ID_CHECK_ICON); // Create ActionBarLayer s_action_bar = action_bar_layer_create(); action_bar_layer_set_click_config_provider(s_action_bar, click_config_provider); // Set the icons action_bar_layer_set_icon(s_action_bar, BUTTON_ID_UP, s_up_bitmap); action_bar_layer_set_icon(s_action_bar, BUTTON_ID_DOWN, s_down_bitmap); action_bar_layer_set_icon(s_action_bar, BUTTON_ID_SELECT, s_check_bitmap); // Add to Window action_bar_layer_add_to_window(s_action_bar, window); ``` ```c // Destroy the ActionBarLayer action_bar_layer_destroy(s_action_bar); // Destroy the icon GBitmaps gbitmap_destroy(s_up_bitmap); gbitmap_destroy(s_down_bitmap); gbitmap_destroy(s_check_bitmap); ```
{ "source": "google/pebble", "title": "devsite/source/_guides/user-interfaces/layers.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/user-interfaces/layers.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 13020 }
--- # Copyright 2025 Google LLC # # 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. title: Round App UI description: | Details on how to use the Pebble SDK to create layouts specifically for round displays. guide_group: user-interfaces order: 4 related_docs: - Graphics - LayerUpdateProc related_examples: - title: Time Dots url: https://github.com/pebble-examples/time-dots/ - title: Text Flow Techniques url: https://github.com/pebble-examples/text-flow-techniques platforms: - chalk --- > This guide is about creating round apps in code. For advice on designing a > round app, read {% guide_link design-and-interaction/in-the-round %}. With the addition of Pebble Time Round (the Chalk platform) to the Pebble family, developers face a new challenge - circular apps! With this display shape, traditional layouts will not display properly due to the obscuring of the corners. Another potential issue is the increased display resolution. Any UI elements that were not previously centered correctly (or drawn with hardcoded coordinates) will also display incorrectly. However, the Pebble SDK provides additions and functionality to help developers cope with this way of thinking. In many cases, a round display can be an aesthetic advantage. An example of this is the traditional circular dial watchface, which has been emulated on Pebble many times, but also wastes corner space. With a round display, these watchfaces can look better than ever. ![time-dots >{pebble-screenshot,pebble-screenshot--time-round-silver-20}](/images/guides/pebble-apps/display-animations/time-dots.png) ## Detecting Display Shape The first step for any app wishing to correctly support both display shapes is to use the available compiler directives to conditionally create the UI. This can be done as shown below: ```c #if defined(PBL_RECT) printf("This code is run on a rectangular display!"); /* Rectangular UI code */ #elif defined(PBL_ROUND) printf("This code is run on a round display!"); /* Round UI code */ #endif ``` Another approach for single value selection is the ``PBL_IF_RECT_ELSE()`` and ``PBL_IF_ROUND_ELSE()`` macros, which accept two parameters for each of the respective round and rectangular cases. For example, ``PBL_IF_RECT_ELSE()`` will compile the first parameter on a rectangular display, and the second one otherwise: ```c // Conditionally print out the shape of the display printf("This is a %s display!", PBL_IF_RECT_ELSE("rectangular", "round")); ``` ## Circular Drawing In addition to the older ``graphics_draw_circle()`` and ``graphics_fill_circle()`` functions, the Pebble SDK for the chalk platform contains additional functions to help draw shapes better suited for a round display. These include: * ``graphics_draw_arc()`` - Draws a line arc clockwise between two angles within a given ``GRect`` area, where 0° is the top of the circle. * ``graphics_fill_radial()`` - Fills a circle clockwise between two angles within a given ``GRect`` area, with adjustable inner inset radius allowing the creation of 'doughnut-esque' shapes. * ``gpoint_from_polar()`` - Returns a ``GPoint`` object describing a point given by a specified angle within a centered ``GRect``. In the Pebble SDK angles between `0` and `360` degrees are specified as values scaled between `0` and ``TRIG_MAX_ANGLE`` to preserve accuracy and avoid floating point math. These are most commonly used when dealing with drawing circles. To help with this conversion, developers can use the ``DEG_TO_TRIGANGLE()`` macro. An example function to draw the letter 'C' in a yellow color is shown below for use in a ``LayerUpdateProc``. ```c static void draw_letter_c(GRect bounds, GContext *ctx) { GRect frame = grect_inset(bounds, GEdgeInsets(30)); graphics_context_set_fill_color(ctx, GColorYellow); graphics_fill_radial(ctx, frame, GOvalScaleModeFitCircle, 30, DEG_TO_TRIGANGLE(-225), DEG_TO_TRIGANGLE(45)); } ``` This produces the expected result, drawn with a smooth antialiased filled circle arc between the specified angles. ![letter-c >{pebble-screenshot,pebble-screenshot--time-round-silver-20}](/images/guides/pebble-apps/display-animations/letter-c.png) ## Adaptive Layouts With not only a difference in display shape, but also in resolution, it is very important that an app's layout not be created using hardcoded coordinates. Consider the examples below, designed to create a child ``Layer`` to fill the size of the parent layer. ```c // Bad - only works on Aplite and Basalt rectangular displays Layer *layer = layer_create(GRect(0, 0, 144, 168)); // Better - uses the native display size GRect bounds = layer_get_bounds(parent_layer); Layer *layer = layer_create(bounds); ``` Using this style, the child layer will always fill the parent layer, regardless of its actual dimensions. In a similar vein, when working with the Pebble Time Round display it can be important that the layout is centered correctly. A set of layout values that are in the center of the classic 144 x 168 pixel display will not be centered when displayed on a 180 x 180 display. The undesirable effect of this can be seen in the example shown below: ![cut-corners >{pebble-screenshot,pebble-screenshot--time-round-silver-20}](/images/guides/pebble-apps/display-animations/cut-corners.png) By using the technique described above, the layout's ``GRect`` objects can specify their `origin` and `size` as a function of the dimensions of the layer they are drawn into, solving this problem. ![centered >{pebble-screenshot,pebble-screenshot--time-round-silver-20}](/images/guides/pebble-apps/display-animations/centered.png) ## Text Flow and Pagination A chief concern when working with a circular display is the rendering of large amounts of text. As demonstrated by an animation in {% guide_link design-and-interaction/in-the-round#pagination %}, continuous reflowing of text makes it much harder to read. A solution to this problem is to render text while flowing within the constraints of the shape of the display, and to scroll/animate it one page at a time. There are three approaches to this available to developers, which are detailed below. For full examples of each, see the [`text-flow-techniques`](https://github.com/pebble-examples/text-flow-techniques) example app. ### Using TextLayer Additions to the ``TextLayer`` API allow text rendered within it to be automatically flowed according to the curve of the display, and paged correctly when the layer is moved or animated further. After a ``TextLayer`` is created in the usual way, text flow can then be enabled: ```c // Create TextLayer TextLayer *s_text_layer = text_layer_create(bounds); /* other properties set up */ // Add to parent Window layer_add_child(window_layer, text_layer_get_layer(s_text_layer)); // Enable paging and text flow with an inset of 5 pixels text_layer_enable_screen_text_flow_and_paging(s_text_layer, 5); ``` > Note: The ``text_layer_enable_screen_text_flow_and_paging()`` function must be > called **after** the ``TextLayer`` is added to the view heirachy (i.e.: after > using ``layer_add_child()``), or else it will have no effect. An example of two ``TextLayer`` elements flowing their text within the constraints of the display shape is shown below: ![text-flow >{pebble-screenshot,pebble-screenshot--time-round-silver-20}](/images/guides/pebble-apps/display-animations/text-flow.png) ### Using ScrollLayer The ``ScrollLayer`` UI component also contains round-friendly functionality, allowing it to scroll its child ``Layer`` elements in pages of the same height as its frame (usually the size of the parent ``Window``). This allows consuming long content to be a more consistent experience, whether it is text, images, or some other kind of information. ```c // Enable ScrollLayer paging scroll_layer_set_paging(s_scroll_layer, true); ``` When combined with a ``TextLayer`` as the main child layer, it becomes easy to display long pieces of textual content on a round display. The ``TextLayer`` can be set up to handle the reflowing of text to follow the display shape, and the ``ScrollLayer`` handles the paginated scrolling. ```c // Add the TextLayer and ScrollLayer to the view heirachy scroll_layer_add_child(s_scroll_layer, text_layer_get_layer(s_text_layer)); layer_add_child(window_layer, scroll_layer_get_layer(s_scroll_layer)); // Set the ScrollLayer's content size to the total size of the text scroll_layer_set_content_size(s_scroll_layer, text_layer_get_content_size(s_text_layer)); // Enable TextLayer text flow and paging const int inset_size = 2; text_layer_enable_screen_text_flow_and_paging(s_text_layer, inset_size); // Enable ScrollLayer paging scroll_layer_set_paging(s_scroll_layer, true); ``` ### Manual Text Drawing The drawing of text into a [`Graphics Context`](``Drawing Text``) can also be performed with awareness of text flow and paging preferences. This can be used to emulate the behavior of the two previous approaches, but with more flexibility. This approach involves the use of the ``GTextAttributes`` object, which is given to the Graphics API to allow it to flow text and paginate when being animated. When initializing the ``Window`` that will do the drawing: ```c // Create the attributes object used for text rendering GTextAttributes *s_attributes = graphics_text_attributes_create(); // Enable text flow with an inset of 5 pixels graphics_text_attributes_enable_screen_text_flow(s_attributes, 5); // Enable pagination with a fixed reference point and bounds, used for animating graphics_text_attributes_enable_paging(s_attributes, bounds.origin, bounds); ``` When drawing some text in a ``LayerUpdateProc``: ```c static void update_proc(Layer *layer, GContext *ctx) { GRect bounds = layer_get_bounds(layer); // Calculate size of the text to be drawn with current attribute settings GSize text_size = graphics_text_layout_get_content_size_with_attributes( s_sample_text, fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD), bounds, GTextOverflowModeWordWrap, GTextAlignmentCenter, s_attributes ); // Draw the text in this box with the current attribute settings graphics_context_set_text_color(ctx, GColorBlack); graphics_draw_text(ctx, s_sample_text, fonts_get_system_font(FONT_KEY_GOTHIC_24_BOLD), GRect(bounds.origin.x, bounds.origin.y, text_size.w, text_size.h), GTextOverflowModeWordWrap, GTextAlignmentCenter, s_attributes ); } ``` Once this setup is complete, the text will display correctly when moved or scrolled via a ``PropertyAnimation``, such as one that moves the ``Layer`` that draws the text upwards, and at the same time extending its height to display subsequent pages. An example animation is shown below: ```c GRect window_bounds = layer_get_bounds(window_get_root_layer(s_main_window)); const int duration_ms = 1000; // Animate the Layer upwards, lengthening it to allow the next page to be drawn GRect start = layer_get_frame(s_layer); GRect finish = GRect(start.origin.x, start.origin.y - window_bounds.size.h, start.size.w, start.size.h * 2); // Create and scedule the PropertyAnimation PropertyAnimation *prop_anim = property_animation_create_layer_frame( s_layer, &start, &finish); Animation *animation = property_animation_get_animation(prop_anim); animation_set_duration(animation, duration_ms); animation_schedule(animation); ``` ## Working With a Circular Framebuffer The traditional rectangular Pebble app framebuffer is a single continuous memory segment that developers could access with ``gbitmap_get_data()``. With a round display, Pebble saves memory by clipping sections of each line of difference between the display area and the rectangle it occupies. The resulting masking pattern looks like this: ![mask](/images/guides/pebble-apps/display-animations/mask.png) > Download this mask by saving the PNG image above, or get it as a > [Photoshop PSD layer](/assets/images/guides/pebble-apps/display-animations/round-mask-layer.psd). This has an important implication - the memory segment of the framebuffer can no longer be accessed using classic `y * row_width + x` formulae. Instead, developers should use the ``gbitmap_get_data_row_info()`` API. When used with a given y coordinate, this will return a ``GBitmapDataRowInfo`` object containing a pointer to the row's data, as well as values for the minumum and maximum visible values of x coordinate on that row. For example: ```c static void round_update_proc(Layer *layer, GContext *ctx) { // Get framebuffer GBitmap *fb = graphics_capture_frame_buffer(ctx); GRect bounds = layer_get_bounds(layer); // Write a value to all visible pixels for(int y = 0; y < bounds.size.h; y++) { // Get the min and max x values for this row GBitmapDataRowInfo info = gbitmap_get_data_row_info(fb, y); // Iterate over visible pixels in that row for(int x = info.min_x; x < info.max_x; x++) { // Set the pixel to black memset(&info.data[x], GColorBlack.argb, 1); } } // Release framebuffer graphics_release_frame_buffer(ctx, fb); } ``` ## Displaying More Content When more content is available than fits on the screen at any one time, the user should be made aware using visual clues. The best way to do this is to use the ``ContentIndicator`` UI component. ![content-indicator >{pebble-screenshot,pebble-screenshot--time-round-silver-20}](/images/guides/design-and-interaction/content-indicator.png) A ``ContentIndicator`` can be obtained in two ways. It can be created from scratch with ``content_indicator_create()`` and manually managed to determine when the arrows should be shown, or a built-in instance can be obtained from a ``ScrollLayer``, as shown below: ```c // Get the ContentIndicator from the ScrollLayer s_indicator = scroll_layer_get_content_indicator(s_scroll_layer); ``` In order to draw the arrows indicating more information in each direction, the ``ContentIndicator`` must be supplied with two new ``Layer`` elements that will be used to do the drawing. These should also be added as children to the main ``Window`` root ``Layer`` such that they are visible on top of all other ``Layer`` elements: ```c static void window_load(Window *window) { Layer *window_layer = window_get_root_layer(window); GRect bounds = layer_get_bounds(window_layer); /* ... */ // Create two Layers to draw the arrows s_indicator_up_layer = layer_create( GRect(0, 0, bounds.size.w, STATUS_BAR_LAYER_HEIGHT)); s_indicator_down_layer = layer_create( GRect(0, bounds.size.h - STATUS_BAR_LAYER_HEIGHT, bounds.size.w, STATUS_BAR_LAYER_HEIGHT)); /* ... */ // Add these Layers as children after all other components to appear below layer_add_child(window_layer, s_indicator_up_layer); layer_add_child(window_layer, s_indicator_down_layer); } ``` Once the indicator ``Layer`` elements have been created, each of the up and down directions for conventional vertical scrolling must be configured with data to control its behavior. Aspects such as the color of the arrows and background, whether or not the arrows time out after being brought into view, and the alignment of the drawn arrow within the ``Layer`` itself are configured with a `const` ``ContentIndicatorConfig`` object when each direction is being configured: ```c // Configure the properties of each indicator const ContentIndicatorConfig up_config = (ContentIndicatorConfig) { .layer = s_indicator_up_layer, .times_out = false, .alignment = GAlignCenter, .colors = { .foreground = GColorBlack, .background = GColorWhite } }; content_indicator_configure_direction(s_indicator, ContentIndicatorDirectionUp, &up_config); const ContentIndicatorConfig down_config = (ContentIndicatorConfig) { .layer = s_indicator_down_layer, .times_out = false, .alignment = GAlignCenter, .colors = { .foreground = GColorBlack, .background = GColorWhite } }; content_indicator_configure_direction(s_indicator, ContentIndicatorDirectionDown, &down_config); ``` Unless the ``ContentIndicator`` has been retrieved from another ``Layer`` type that includes an instance, it should be destroyed along with its parent ``Window``: ```c // Destroy a manually created ContentIndicator content_indicator_destroy(s_indicator); ``` For layouts that use the ``StatusBarLayer``, the ``ContentIndicatorDirectionUp`` `.layer` in the ``ContentIndicatorConfig`` object can be given the status bar's ``Layer`` with ``status_bar_layer_get_layer()``, and the drawing routines for each will be managed automatically.
{ "source": "google/pebble", "title": "devsite/source/_guides/user-interfaces/round-app-ui.md", "url": "https://github.com/google/pebble/blob/main/devsite/source/_guides/user-interfaces/round-app-ui.md", "date": "2025-01-21T21:11:59", "stars": 4407, "description": "This is the latest version of the internal repository from Pebble Technology providing the software to run on Pebble watches. Proprietary source code has been removed from this repository and it will not compile as-is. This is for information only.", "file_size": 17357 }