Определение высоты и текущих координат в API Connect IQ

Высота

Для определения высоты API Connect IQ предоставляет целых три объекта, содержащих необходимые данные:

При этом любой из них может возвращать null. А также неясен приоритет и точность этих данных.

Изначально для определения высоты использовался только объект Toybox::Position::Info. Однако, это приводило к крашам на Garmin tactix Charlie. Спасибо Darko Vojinovic за помощь в локализации ошибки.

Затем определение высоты было вынесено в отдельную функцию:

function altitude() {
    var alt = 0,
        curAlt;

    if (Activity has :getActivityInfo) {
        curAlt = Activity.getActivityInfo().altitude;
        if (null != curAlt) {
            if (!RUN_BG) {
                Application.getApp().setProperty(ALTDATA, curAlt);
            }
            return curAlt;
        }
    }

    if (Position has :getInfo) {
        var positionInfo = Position.getInfo();

        if ((positionInfo has :accuracy) &&
            (positionInfo.accuracy != Position.QUALITY_NOT_AVAILABLE) &&
            (positionInfo has :altitude) &&
            (positionInfo.altitude != null)
        ) {
            curAlt = positionInfo.altitude.toFloat();
            if (!RUN_BG) {
                Application.getApp().setProperty(ALTDATA, curAlt);
            }
            return curAlt;
        }
    }

    curAlt = Application.getApp().getProperty(ALTDATA);
    if (null != curAlt) {
        return curAlt;
    }

    return alt;
}

Приоритетность получения данных следующая:

Данные с сенсоров недоступны для WatchFace, хотя для виджетов и приложений вполне себе можно использовать:

The Sensor.Info class contains all of the information provided by enabled sensors.

Sensor.Info can be retrieved on every call of onUpdate() or it can be obtained on demand. Fields in this class may return null so should be checked for null values prior to use.

Вроде бы его можно вызывать каждую секунду, но он может ничего не вернуть.

То есть первоначально, обращение идет к текущей активности.

The Activity module provides a way to retrieve available info for the current activity.

Activity Info is automatically provided by the compute() method in Data Fields. The getActivityInfo() method is available for use within apps or in other cases, such as data field initialization.

The Activity.Info class contains information about the current activity.

This information can be retrieved with the getActivityInfo() method. Fields in this class may return null so should be checked for null values prior to use.

И только после этого обращение идет к Position.Info:

The Position module provides an interface for location information and positioning sensors.

The Position.Info class contains all of the information provided by the positioning system.

Position Info can be retrieved on every call of onUpdate() or it can be obtained on demand. Fields in this class may return null so should be checked for null values prior to use.

В случае успешного получения данных, данные сохраняются в свойствах приложения. И возвращаются как результат функции.

И, если ни один из объектов недоступен или не возвращает данных, но данные есть в сохраненных свойствах, то возвращаются они.

Ну и если уж совсем ничего нигде не сохранено, функция вернет 0.

Координаты

Для определения текущего местоположения доступны два объекта:

Логика та же.

function location() {
     var loc = [0, 0],
         curLoc;
     if (Activity has :getActivityInfo) {
         curLoc = Activity.getActivityInfo().currentLocation;
         if (curLoc != null) {
             if (!RUN_BG) {
                 Application.getApp().setProperty(LOCDATA, curLoc);
             }
             return curLoc;
         }
     }
     if (Position has :getInfo) {
         var positionInfo = Position.getInfo();
         if (positionInfo has :position && positionInfo.position != null) {
             curLoc = positionInfo.position.toDegrees();
             if (null != curLoc) {
                 if (!RUN_BG) {
                     Application.getApp().setProperty(LOCDATA, curLoc);
                 }
                 return curLoc;
             }
         }
     }
     curLoc = Application.getApp().getProperty(LOCDATA);
     if (null != curLoc) {
         return curLoc;
     }
     return loc;
 }

Сначала берется текущую активность:

The current location.

This member will always provide a null value unless the Positioning Permission is enabled.

Затем берутся данные сенсоров позиционирования:

The Position.Info class contains all of the information provided by the positioning system.

Position Info can be retrieved on every call of onUpdate() or it can be obtained on demand. Fields in this class may return null so should be checked for null values prior to use.

The latitude and longitude of the position.

If no GPS is available or is between GPS fix intervals (typically 1 second), the position is propagated (i.e. dead-reckoned) using the last known heading and last known speed. After a short period of time, the position will cease to be propagated to avoid excessive accumulation of position errors.

The Location object represents a specific position.

Location objects provide methods for retrieving position coordinates in various formats.

При успешном определении координат они сохраняются в свойствах приложения.

При неуспешном берутся сохраненные значения.

Или возвращается точка с координатами [0, 0].

То есть если в часах не работает GPS то они будут показывать вам, что вы плаваете на поверхности Атлантического океана в Гвинейском заливе где-то недалеко от Африки в точке с координатами 0,0.

Изменения опубликованы в опубликованных версиях Thin:

1.3.8 Улучшен алгоритм получения текущего положения и высоты для большей совместимости

1.3.7 Исправление ошибок (местоположение)

Добавить комментарий

Ваш адрес email не будет опубликован.