Связь со страницей конфигурации Pebble не отвечает

Я создаю свой первый циферблат, для которого требуется страница конфигурации, на которой можно хранить две строки (заголовок и сообщение).

Я не слишком знаком со всеми коммуникативными вещами, потому что на самом деле нет полных примеров, но я попытался сделать это как можно дальше.

Вот соответствующий код для всех моих мест

main.c

static void inbox_received_callback(DictionaryIterator *iterator, void *context) {
              APP_LOG(APP_LOG_LEVEL_INFO, "Message received!");

              // Get the first pair
              Tuple *t = dict_read_first(iterator);

              //Long lived buffers
              static char title_buffer[64];
              static char message_buffer[124];

              // Process all pairs present
              while(t != NULL) {
                // Process this pair's key
                switch (t->key) {
                  case TITLE_DATA:
                    snprintf(title_buffer, sizeof(title_buffer), "%s", t->value->cstring);
                    text_layer_set_text(title_layer, title_buffer);
                    APP_LOG(APP_LOG_LEVEL_INFO, "TITLE_DATA received with value %d", (int)t->value->int32);
                    break;
                  case MESSAGE_DATA:
                    snprintf(message_buffer, sizeof(message_buffer), "%s", t->value->cstring);
                    text_layer_set_text(message_layer, message_buffer);
                    APP_LOG(APP_LOG_LEVEL_INFO, "MESSAGE_DATA received with value %d", (int)t->value->int32);
                    break;
                }

                // Get next pair, if any
                t = dict_read_next(iterator);
              }
            }

pebbleScript.js

var title = localStorage.getItem('title') ? localStorage.getItem('title') : 'Title',
        message = localStorage.getItem('message') ? localStorage.getItem('message') : "Message that can be changed in watchface 'Settings'";

        Pebble.addEventListener('showConfiguration', function(e) {
          console.log("Showing configuration");
          // Show config page
          Pebble.openURL('https://dl.dropboxusercontent.com/s/kzl44khedt5e22d/config.html?dl=0');
        });

        Pebble.addEventListener('webviewclosed', function(e) {
          var options = JSON.parse(decodeURIComponent(e.response));
          title = encodeURIComponent(options.title);
          message = encodeURIComponent(options.message);

          if(title == 'undefined') {
            title = 'Title';
          } if (message == 'undefined') {
            message = "Message that can be changed in watchface 'Settings'";
          }

          localStorage.setItem('title', title);
          localStorage.setItem('message', message);

          console.log("Configuration window returned: ", JSON.stringify(options));
        });

        Pebble.addEventListener('ready', function(e) {
          console.log("PebbleKit JS Ready!");

          //Construct a dictionary
          var

 dict = {
            'TITLE_DATA' : title,
            'MESSAGE_DATA' : message
          };

      //Send a string to Pebble
      Pebble.sendAppMessage(dict, function(e) {
        console.log("Send successful.");
      }, function(e) {
        console.log("Send failed!");
      });
    });

config.html

<h3>Title:</h3>
        <input type="text" name="title" id="title"></input>
        <h3>Message:</h3>
        <input type="text" name="message" id="message"></input>  
        <br>        
        <input type="submit" id="cancelButton" value="Cancel">
        <input type="submit" id="saveButton" value="Save">

    <script>
        $('#cancelButton').click(function() {
            location.href = 'pebblejs://close';
        });

        $('#saveButton').click(function() {
            var options = {
                title: $('title').val(),
                message: $('#message').val()
            }

            location.href = 'pebblejs://close#' + encodeURIComponent(JSON.stringify(options));
        });

        function getURLVariable(name)  {
            name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
            var regexS = "[\\?&]"+name+"=([^&#]*)",
                regex = new RegExp(regexS),
                results = regex.exec(window.location.href);
            if (results == null) return "";
            else return results[1];
        }
        $(document).ready(function() {
            var priorTitle = getURLVariable('title');
            priorTitle = decodeURI(priorTitle);

            if (priorTitle) {
                $('#title').html(priorTitle);
            }

            var priorMessage = getURLVariable('message');
            priorMessage = decodeURI(priorTitle);

            if (priorMessage) {
                $('#message').html(priorMessage);
            }
        });
    </script>

Если кто-нибудь может понять, почему это не работает должным образом, я был бы очень признателен за помощь :) Пожалуйста, дайте мне знать, есть ли какие-либо другие детали, которые я должен включить.

Я использую CloudPebble для разработки. Я сделал ключи заголовка и сообщения в настройках и определил их в моем main.c, так что это не так.

Следует отметить, что в журнале приложения отображается «TITLE_DATA получено со значением…», но не «MESSAGE_DATA получено…». Так что проблема может заключаться где-то там.


person Barry Michael Doyle    schedule 16.04.2015    source источник


Ответы (1)


Вы объявляете свои «долгоживущие буферы» внутри функции:

static void inbox_received_callback(DictionaryIterator *iterator, void *context) {
    ...
    //Long lived buffers
    static char title_buffer[64];
    static char message_buffer[124];
    ...
}

Если вы хотите, чтобы они оставались в области действия (сохранялись), вам нужно объявить их вместе с другими глобальными переменными:

static Window *s_main_window;
static char title_buffer[64];
static char message_buffer[124];
person nclarkclt    schedule 20.04.2015
comment
Спасибо, я исправил это на днях и забыл, что разместил вопрос об этом, но это была проблема :) - person Barry Michael Doyle; 21.04.2015