Pebble: How to load random string from resource

There’s no doubt that Firefly is a greatest TV series in the history of all creation. That is why when I was learning resource handling in Pebble SDK I have decided to create a watchface that would display a random quote from Firefly. And thanks to Bill Hatcher of http://cubemonkey.net/quotes/ I obtained a plain TXT file with almost 500 quotes.

The file is in the format "quote1%quote2%quote3..." e.g. there is a “%” separator between the quotes, so I quickly wrote a small script that gives me a position of each percentage sign within the file, so I can create an array of the positions in my C code for Pebble:

#define NO_OF_QUOTES 472
int aQuotePointers[NO_OF_QUOTES] = {0, 206, 354, 417, 480, 554, 662, 695,... 88825}

which basically gave me position of each quote in the file and which I prepended with 0 and appended with filesize. Then I added the resource to my project (in CloudPeble environment it’s as easy as loading a BLOB resource and giving it a name). A Pebble watchface or watchapp can handle resources of up to 96K, fortunately file with quotes was less, otherwise some kind of string compression would have to be implemented.

After that it’s a trivial matter to generate random position, retrieve quote from that position and display it on a text layer:

// determining number of quote (that will give us address of begining and end)
srand(time(NULL));
int number_of_quote = rand() % NO_OF_QUOTES;
  
//determining size of quote and allocating memory
int size_of_quote = aQuotePointers[number_of_quote + 1] - aQuotePointers[number_of_quote] - 1;
uint8_t *quote = malloc(size_of_quote);

//loading quote, displaying and freeing memory
ResHandle rh = resource_get_handle(RESOURCE_ID_FIREFLY_QUOTES);
resource_load_byte_range(rh, aQuotePointers[number_of_quote] + 1, quote, size_of_quote);
quote[size_of_quote] = 0; //null terminating string
text_layer_set_text(s_textlayer_quote, (char *)quote);

Lines 2-3 generate random index for the array of quote pointers
Lines 6-7 calculate size of the quote (based on position of current and next quote) and allocate memory for the quote
Lines 10-11 load range from the resource based on index and size
Lines 12-13 0-terminate the loaded range and display data on the text layer.

It’s all pretty straightforward and works like a magic and the result you can see in published watchface: Blue Sun Quotes.

Some useful links:

Next time I will describe how I handled situation when loaded quote is too long to display on a text layer

2 replies on “Pebble: How to load random string from resource”

  1. There’s no doubt that Babylon 5 is the greatest TV series in the history of all creation.

  2. @Ron, I do concur that the plot span by Shadows and Vorlons is very interesting and JMS is my hero too.
    Damn, now I am torn between the two 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *