1 // Copyright 2015 The Weave Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "src/notification/pull_channel.h"
6 
7 #include <base/bind.h>
8 #include <base/location.h>
9 #include <weave/provider/task_runner.h>
10 
11 #include "src/notification/notification_delegate.h"
12 
13 namespace weave {
14 
15 const char kPullChannelName[] = "pull";
16 
PullChannel(base::TimeDelta pull_interval,provider::TaskRunner * task_runner)17 PullChannel::PullChannel(base::TimeDelta pull_interval,
18                          provider::TaskRunner* task_runner)
19     : pull_interval_{pull_interval}, task_runner_{task_runner} {}
20 
GetName() const21 std::string PullChannel::GetName() const {
22   return kPullChannelName;
23 }
24 
IsConnected() const25 bool PullChannel::IsConnected() const {
26   return true;
27 }
28 
AddChannelParameters(base::DictionaryValue * channel_json)29 void PullChannel::AddChannelParameters(base::DictionaryValue* channel_json) {
30   // No extra parameters needed for "Pull" channel.
31 }
32 
Start(NotificationDelegate * delegate)33 void PullChannel::Start(NotificationDelegate* delegate) {
34   CHECK(delegate);
35   delegate_ = delegate;
36   RePost();
37 }
38 
RePost()39 void PullChannel::RePost() {
40   CHECK(delegate_);
41   weak_ptr_factory_.InvalidateWeakPtrs();
42   task_runner_->PostDelayedTask(
43       FROM_HERE,
44       base::Bind(&PullChannel::OnTimer, weak_ptr_factory_.GetWeakPtr()),
45       pull_interval_);
46 }
47 
Stop()48 void PullChannel::Stop() {
49   weak_ptr_factory_.InvalidateWeakPtrs();
50   delegate_ = nullptr;
51 }
52 
UpdatePullInterval(base::TimeDelta pull_interval)53 void PullChannel::UpdatePullInterval(base::TimeDelta pull_interval) {
54   pull_interval_ = pull_interval;
55   if (delegate_)
56     RePost();
57 }
58 
OnTimer()59 void PullChannel::OnTimer() {
60   // Repost before delegate notification to give it a chance to stop channel.
61   RePost();
62   base::DictionaryValue empty_dict;
63   delegate_->OnCommandCreated(empty_dict, GetName());
64 }
65 
66 }  // namespace weave
67