summaryrefslogtreecommitdiff
path: root/src/ledflasher/ledflasher.cpp
blob: 269c5be9443a319cf6ab060cdb2767bac31ea0f7 (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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/*
 * Copyright 2015 The Android Open Source Project
 *
 * 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.
 */

#include <string>
#include <sysexits.h>

#include <base/bind.h>
#include <base/command_line.h>
#include <base/macros.h>
#include <base/memory/weak_ptr.h>
#include <binderwrapper/binder_wrapper.h>
#include <brillo/binder_watcher.h>
#include <brillo/daemons/daemon.h>
#include <brillo/syslog_logging.h>
#include <libweaved/service.h>

#include "animation.h"
#include "binder_constants.h"
#include "brillo/examples/ledflasher/ILEDService.h"

namespace {
const char kWeaveComponent[] = "ledflasher";
const char kWeaveTrait[] = "_ledflasher";
const char kBaseComponent[] = "base";
const char kBaseTrait[] = "base";
}  // anonymous namespace

using brillo::examples::ledflasher::ILEDService;

class Daemon final : public brillo::Daemon {
 public:
  Daemon() = default;

 protected:
  int OnInit() override;

 private:
  void OnWeaveServiceConnected(const std::weak_ptr<weaved::Service>& service);
  void ConnectToLEDService();
  void OnLEDServiceDisconnected();
  void OnPairingInfoChanged(const weaved::Service::PairingInfo* pairing_info);

  // Particular command handlers for various commands.
  void OnSet(std::unique_ptr<weaved::Command> command);
  void OnToggle(std::unique_ptr<weaved::Command> command);
  void OnAnimate(std::unique_ptr<weaved::Command> command);
  void OnIdentify(std::unique_ptr<weaved::Command> command);

  // Helper methods to propagate device state changes to Buffet and hence to
  // the cloud server or local clients.
  void UpdateDeviceState();

  void StartAnimation(const std::string& type, base::TimeDelta duration);
  void StopAnimation();

  std::weak_ptr<weaved::Service> weave_service_;

  // Device state variables.
  std::string status_{"idle"};

  // LED service interface.
  android::sp<ILEDService> led_service_;

  // Current animation;
  std::unique_ptr<Animation> animation_;

  brillo::BinderWatcher binder_watcher_;
  std::unique_ptr<weaved::Service::Subscription> weave_service_subscription_;

  base::WeakPtrFactory<Daemon> weak_ptr_factory_{this};
  DISALLOW_COPY_AND_ASSIGN(Daemon);
};

int Daemon::OnInit() {
  int return_code = brillo::Daemon::OnInit();
  if (return_code != EX_OK)
    return return_code;

  android::BinderWrapper::Create();
  if (!binder_watcher_.Init())
    return EX_OSERR;

  weave_service_subscription_ = weaved::Service::Connect(
      brillo::MessageLoop::current(),
      base::Bind(&Daemon::OnWeaveServiceConnected,
                 weak_ptr_factory_.GetWeakPtr()));
  ConnectToLEDService();

  LOG(INFO) << "Waiting for commands...";
  return EX_OK;
}

void Daemon::OnWeaveServiceConnected(
    const std::weak_ptr<weaved::Service>& service) {
  LOG(INFO) << "Daemon::OnWeaveServiceConnected";
  weave_service_ = service;
  auto weave_service = weave_service_.lock();
  if (!weave_service)
    return;

  weave_service->AddComponent(kWeaveComponent, {kWeaveTrait}, nullptr);
  weave_service->AddCommandHandler(
      kWeaveComponent, kWeaveTrait, "set",
      base::Bind(&Daemon::OnSet, weak_ptr_factory_.GetWeakPtr()));
  weave_service->AddCommandHandler(
      kWeaveComponent, kWeaveTrait, "toggle",
      base::Bind(&Daemon::OnToggle, weak_ptr_factory_.GetWeakPtr()));
  weave_service->AddCommandHandler(
      kWeaveComponent, kWeaveTrait, "animate",
      base::Bind(&Daemon::OnAnimate, weak_ptr_factory_.GetWeakPtr()));
  weave_service->AddCommandHandler(
      kBaseComponent, kBaseTrait, "identify",
      base::Bind(&Daemon::OnIdentify, weak_ptr_factory_.GetWeakPtr()));

  weave_service->SetPairingInfoListener(
      base::Bind(&Daemon::OnPairingInfoChanged,
                 weak_ptr_factory_.GetWeakPtr()));

  UpdateDeviceState();
}

void Daemon::ConnectToLEDService() {
  android::BinderWrapper* binder_wrapper = android::BinderWrapper::Get();
  auto binder = binder_wrapper->GetService(ledservice::kBinderServiceName);
  if (!binder.get()) {
    brillo::MessageLoop::current()->PostDelayedTask(
        base::Bind(&Daemon::ConnectToLEDService,
                   weak_ptr_factory_.GetWeakPtr()),
        base::TimeDelta::FromSeconds(1));
    return;
  }
  binder_wrapper->RegisterForDeathNotifications(
      binder,
      base::Bind(&Daemon::OnLEDServiceDisconnected,
                 weak_ptr_factory_.GetWeakPtr()));
  led_service_ = android::interface_cast<ILEDService>(binder);
  UpdateDeviceState();
}

void Daemon::OnLEDServiceDisconnected() {
  animation_.reset();
  led_service_ = nullptr;
  ConnectToLEDService();
}

void Daemon::OnSet(std::unique_ptr<weaved::Command> command) {
  if (!led_service_.get()) {
    command->Abort("_system_error", "ledservice unavailable", nullptr);
    return;
  }

  int index = command->GetParameter<int>("led");
  if(index < 1 || index > 4) {
    command->Abort("_invalid_parameter", "Invalid parameter value", nullptr);
    return;
  }
  bool on = command->GetParameter<bool>("on");
  android::binder::Status status = led_service_->setLED(index - 1, on);
  if (!status.isOk()) {
    command->AbortWithCustomError(status, nullptr);
    return;
  }
  animation_.reset();
  status_ = "idle";
  UpdateDeviceState();
  command->Complete({}, nullptr);
}

void Daemon::OnToggle(std::unique_ptr<weaved::Command> command) {
  if (!led_service_.get()) {
    command->Abort("_system_error", "ledservice unavailable", nullptr);
    return;
  }

  int index = command->GetParameter<int>("led");
  if(index < 1 || index > 4) {
    command->Abort("_invalid_parameter", "Invalid parameter value", nullptr);
    return;
  }
  index--;
  bool on = false;
  android::binder::Status status = led_service_->getLED(index, &on);
  if (status.isOk())
    status = led_service_->setLED(index, !on);
  if(!status.isOk()) {
    command->AbortWithCustomError(status, nullptr);
    return;
  }
  animation_.reset();
  status_ = "idle";
  UpdateDeviceState();
  command->Complete({}, nullptr);
}

void Daemon::OnAnimate(std::unique_ptr<weaved::Command> command) {
  if (!led_service_.get()) {
    command->Abort("_system_error", "ledservice unavailable", nullptr);
    return;
  }

  double duration = command->GetParameter<double>("duration");
  if(duration <= 0.0) {
    command->Abort("_invalid_parameter", "Invalid parameter value", nullptr);
    return;
  }
  std::string type = command->GetParameter<std::string>("type");
  StartAnimation(type, base::TimeDelta::FromSecondsD(duration));
  command->Complete({}, nullptr);
}

void Daemon::OnIdentify(std::unique_ptr<weaved::Command> command) {
  if (!led_service_.get()) {
    command->Abort("_system_error", "ledservice unavailable", nullptr);
    return;
  }
  StartAnimation("blink", base::TimeDelta::FromMilliseconds(500));
  command->Complete({}, nullptr);

  brillo::MessageLoop::current()->PostDelayedTask(
      base::Bind(&Daemon::StopAnimation, weak_ptr_factory_.GetWeakPtr()),
      base::TimeDelta::FromSeconds(2));
}

void Daemon::OnPairingInfoChanged(
    const weaved::Service::PairingInfo* pairing_info) {
  LOG(INFO) << "Daemon::OnPairingInfoChanged: " << pairing_info;
  if (!pairing_info)
    return StopAnimation();
  StartAnimation("blink", base::TimeDelta::FromMilliseconds(500));
}

void Daemon::StartAnimation(const std::string& type, base::TimeDelta duration) {
  animation_ = Animation::Create(led_service_, type, duration);
  if (animation_) {
    status_ = "animating";
    animation_->Start();
  } else {
    status_ = "idle";
  }
  UpdateDeviceState();
}

void Daemon::StopAnimation() {
  if (!animation_)
    return;

  animation_.reset();
  status_ = "idle";
  UpdateDeviceState();
}

void Daemon::UpdateDeviceState() {
  if (!led_service_.get())
    return;

  std::vector<bool> leds;
  if (!led_service_->getAllLEDs(&leds).isOk())
    return;

  auto weave_service = weave_service_.lock();
  if (!weave_service)
    return;

  brillo::VariantDictionary state_change{
    {"_ledflasher.status", status_},
    {"_ledflasher.leds", leds},
  };
  weave_service->SetStateProperties(kWeaveComponent, state_change, nullptr);
}

int main(int argc, char* argv[]) {
  base::CommandLine::Init(argc, argv);
  brillo::InitLog(brillo::kLogToSyslog | brillo::kLogHeader);
  Daemon daemon;
  return daemon.Run();
}