1 // Copyright 2015 The Chromium 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 "components/cast_channel/keep_alive_delegate.h"
6 
7 #include <string>
8 #include <utility>
9 
10 #include "base/bind.h"
11 #include "components/cast_channel/cast_channel_enum.h"
12 #include "components/cast_channel/cast_socket.h"
13 #include "components/cast_channel/logger.h"
14 #include "net/base/net_errors.h"
15 #include "net/traffic_annotation/network_traffic_annotation.h"
16 #include "third_party/openscreen/src/cast/common/channel/proto/cast_channel.pb.h"
17 
18 namespace cast_channel {
19 
KeepAliveDelegate(CastSocket * socket,scoped_refptr<Logger> logger,std::unique_ptr<CastTransport::Delegate> inner_delegate,base::TimeDelta ping_interval,base::TimeDelta liveness_timeout)20 KeepAliveDelegate::KeepAliveDelegate(
21     CastSocket* socket,
22     scoped_refptr<Logger> logger,
23     std::unique_ptr<CastTransport::Delegate> inner_delegate,
24     base::TimeDelta ping_interval,
25     base::TimeDelta liveness_timeout)
26     : inner_delegate_(std::move(inner_delegate)),
27       handler_(socket,
28                std::move(logger),
29                ping_interval,
30                liveness_timeout,
31                base::BindRepeating(&KeepAliveDelegate::OnError,
32                                    base::Unretained(this))) {
33   DCHECK(inner_delegate_);
34 }
35 
36 KeepAliveDelegate::~KeepAliveDelegate() = default;
37 
SetTimersForTest(std::unique_ptr<base::RetainingOneShotTimer> injected_ping_timer,std::unique_ptr<base::RetainingOneShotTimer> injected_liveness_timer)38 void KeepAliveDelegate::SetTimersForTest(
39     std::unique_ptr<base::RetainingOneShotTimer> injected_ping_timer,
40     std::unique_ptr<base::RetainingOneShotTimer> injected_liveness_timer) {
41   handler_.SetTimersForTest(std::move(injected_ping_timer),
42                             std::move(injected_liveness_timer));
43 }
44 
45 // CastTransport::Delegate interface.
Start()46 void KeepAliveDelegate::Start() {
47   handler_.Start();
48   inner_delegate_->Start();
49 }
50 
OnError(ChannelError error_state)51 void KeepAliveDelegate::OnError(ChannelError error_state) {
52   DVLOG(1) << "KeepAlive::OnError: "
53            << ::cast_channel::ChannelErrorToString(error_state);
54   inner_delegate_->OnError(error_state);
55   handler_.Stop();
56 }
57 
OnMessage(const CastMessage & message)58 void KeepAliveDelegate::OnMessage(const CastMessage& message) {
59   DVLOG(2) << "KeepAlive::OnMessage : " << message.payload_utf8();
60   if (!handler_.HandleMessage(message)) {
61     inner_delegate_->OnMessage(message);
62   }
63 }
64 
65 }  // namespace cast_channel
66