summaryrefslogtreecommitdiff
path: root/src/components/ble/weather/WeatherService.cpp
blob: 006fc6c122144fabc539c9d6a382cdc205a03a57 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
/*  Copyright (C) 2021 Avamander

    This file is part of InfiniTime.

    InfiniTime is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    InfiniTime is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
*/
#include <qcbor/qcbor_spiffy_decode.h>
#include "WeatherService.h"
#include "libs/QCBOR/inc/qcbor/qcbor.h"
#include "systemtask/SystemTask.h"

int WeatherCallback(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt* ctxt, void* arg) {
  return static_cast<Pinetime::Controllers::WeatherService*>(arg)->OnCommand(conn_handle, attr_handle, ctxt);
}

namespace Pinetime {
  namespace Controllers {
    WeatherService::WeatherService(System::SystemTask& system, DateTime& dateTimeController)
      : system(system), dateTimeController(dateTimeController) {
    }

    void WeatherService::Init() {
      uint8_t res = 0;
      res = ble_gatts_count_cfg(serviceDefinition);
      ASSERT(res == 0)

      res = ble_gatts_add_svcs(serviceDefinition);
      ASSERT(res == 0);
    }

    int WeatherService::OnCommand(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt* ctxt) {
      if (ctxt->op == BLE_GATT_ACCESS_OP_WRITE_CHR) {
        getCurrentPressure();
        tidyTimeline();
        getTimelineLength();
        const auto packetLen = OS_MBUF_PKTLEN(ctxt->om);
        if (packetLen <= 0) {
          return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN;
        }
        // Decode
        QCBORDecodeContext decodeContext;
        UsefulBufC EncodedCBOR;
        // TODO: Check uninit fine
        QCBORDecode_Init(&decodeContext, EncodedCBOR, QCBOR_DECODE_MODE_NORMAL);
        QCBORDecode_EnterMap(&decodeContext, nullptr);
        WeatherData::timelineheader timelineHeader {};
        // Always encodes to the smallest number of bytes based on the value
        QCBORDecode_GetInt64InMapSZ(&decodeContext, "Timestamp", reinterpret_cast<int64_t*>(&(timelineHeader.timestamp)));
        QCBORDecode_GetInt64InMapSZ(&decodeContext, "Expires", reinterpret_cast<int64_t*>(&(timelineHeader.expires)));
        QCBORDecode_GetInt64InMapSZ(&decodeContext, "EventType", reinterpret_cast<int64_t*>(&(timelineHeader.eventType)));
        switch (timelineHeader.eventType) {
            // TODO: Populate
          case WeatherData::eventtype::AirQuality: {
            break;
          }
          case WeatherData::eventtype::Obscuration: {
            break;
          }
          case WeatherData::eventtype::Precipitation: {
            break;
          }
          case WeatherData::eventtype::Wind: {
            break;
          }
          case WeatherData::eventtype::Temperature: {
            break;
          }
          case WeatherData::eventtype::Special: {
            break;
          }
          case WeatherData::eventtype::Pressure: {
            break;
          }
          case WeatherData::eventtype::Location: {
            break;
          }
          case WeatherData::eventtype::Clouds: {
            break;
          }
          default: {
            break;
          }
        }
        QCBORDecode_ExitMap(&decodeContext);

        auto uErr = QCBORDecode_Finish(&decodeContext);
        if (uErr != 0) {
          return BLE_ATT_ERR_INSUFFICIENT_RES;
        }
      } else if (ctxt->op == BLE_GATT_ACCESS_OP_READ_CHR) {
        // TODO: Detect control messages

        // Encode
        uint8_t buffer[64];
        QCBOREncodeContext encodeContext;
        QCBOREncode_Init(&encodeContext, UsefulBuf_FROM_BYTE_ARRAY(buffer));
        QCBOREncode_OpenMap(&encodeContext);
        QCBOREncode_AddTextToMap(&encodeContext, "test", UsefulBuf_FROM_SZ_LITERAL("test"));
        QCBOREncode_AddInt64ToMap(&encodeContext, "test", 1ul);
        QCBOREncode_CloseMap(&encodeContext);

        UsefulBufC encodedEvent;
        auto uErr = QCBOREncode_Finish(&encodeContext, &encodedEvent);
        if (uErr != 0) {
          return BLE_ATT_ERR_INSUFFICIENT_RES;
        }
        auto res = os_mbuf_append(ctxt->om, &buffer, sizeof(buffer));
        if (res == 0) {
          return BLE_ATT_ERR_INSUFFICIENT_RES;
        }

        return 0;
      }
      return 0;
    }

    WeatherData::location WeatherService::getCurrentLocation() const {
      return WeatherData::location();
    }
    WeatherData::clouds WeatherService::getCurrentClouds() const {
      return WeatherData::clouds();
    }
    WeatherData::obscuration WeatherService::getCurrentObscuration() const {
      return WeatherData::obscuration();
    }
    WeatherData::precipitation WeatherService::getCurrentPrecipitation() const {
      return WeatherData::precipitation();
    }
    WeatherData::wind WeatherService::getCurrentWind() const {
      return WeatherData::wind();
    }
    WeatherData::temperature WeatherService::getCurrentTemperature() const {
      return WeatherData::temperature();
    }
    WeatherData::humidity WeatherService::getCurrentHumidity() const {
      return WeatherData::humidity();
    }
    WeatherData::pressure WeatherService::getCurrentPressure() const {
      uint64_t currentTimestamp = getCurrentUNIXTimestamp();
      for (auto&& header : timeline) {
        if (header->eventType == WeatherData::eventtype::Pressure && header->timestamp + header->expires <= currentTimestamp) {
          return WeatherData::pressure();
        }
      }
      return WeatherData::pressure();
    }

    WeatherData::airquality WeatherService::getCurrentQuality() const {
      return WeatherData::airquality();
    }

    size_t WeatherService::getTimelineLength() const {
      return timeline.size();
    }

    bool WeatherService::addEventToTimeline(std::unique_ptr<WeatherData::timelineheader> event) {
      if (timeline.size() == timeline.max_size()) {
        return false;
      }

      timeline.push_back(std::move(event));
      return true;
    }

    bool WeatherService::hasTimelineEventOfType(const WeatherData::eventtype type) const {
      uint64_t currentTimestamp = getCurrentUNIXTimestamp();
      for (auto&& header : timeline) {
        if (header->eventType == type && header->timestamp + header->expires <= currentTimestamp) {
          // TODO: Check if its currently valid
          return true;
        }
      }
      return false;
    }

    void WeatherService::tidyTimeline() {
      uint64_t timeCurrent = 0;
      timeline.erase(std::remove_if(std::begin(timeline),
                                    std::end(timeline),
                                    [&](std::unique_ptr<WeatherData::timelineheader> const& header) {
                                      return header->timestamp + header->expires > timeCurrent;
                                    }),
                     std::end(timeline));

      std::sort(std::begin(timeline), std::end(timeline), compareTimelineEvents);
    }

    bool WeatherService::compareTimelineEvents(const std::unique_ptr<WeatherData::timelineheader>& first,
                                               const std::unique_ptr<WeatherData::timelineheader>& second) {
      return first->timestamp > second->timestamp;
    }

    uint64_t WeatherService::getCurrentUNIXTimestamp() const {
      return std::chrono::duration_cast<std::chrono::seconds>(dateTimeController.CurrentDateTime().time_since_epoch()).count();
    }
  }
}