1 // Copyright 2014 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.
5 #include "components/proximity_auth/connection.h"
7 #include "base/logging.h"
8 #include "components/proximity_auth/connection_observer.h"
9 #include "components/proximity_auth/wire_message.h"
11 namespace proximity_auth
{
13 Connection::Connection(const RemoteDevice
& remote_device
)
14 : remote_device_(remote_device
),
15 status_(DISCONNECTED
),
16 is_sending_message_(false) {
19 Connection::~Connection() {
22 bool Connection::IsConnected() const {
23 return status_
== CONNECTED
;
26 void Connection::SendMessage(scoped_ptr
<WireMessage
> message
) {
28 VLOG(1) << "Cannot send message when disconnected.";
32 if (is_sending_message_
) {
33 VLOG(1) << "Another message is currently in progress.";
37 is_sending_message_
= true;
38 SendMessageImpl(message
.Pass());
41 void Connection::AddObserver(ConnectionObserver
* observer
) {
42 observers_
.AddObserver(observer
);
45 void Connection::RemoveObserver(ConnectionObserver
* observer
) {
46 observers_
.RemoveObserver(observer
);
49 void Connection::SetStatus(Status status
) {
50 if (status_
== status
)
53 received_bytes_
.clear();
55 Status old_status
= status_
;
57 FOR_EACH_OBSERVER(ConnectionObserver
, observers_
,
58 OnConnectionStatusChanged(this, old_status
, status_
));
61 void Connection::OnDidSendMessage(const WireMessage
& message
, bool success
) {
62 if (!is_sending_message_
) {
63 VLOG(1) << "Send completed, but no message in progress.";
67 is_sending_message_
= false;
69 ConnectionObserver
, observers_
, OnSendCompleted(*this, message
, success
));
72 void Connection::OnBytesReceived(const std::string
& bytes
) {
74 VLOG(1) << "Received bytes, but not connected.";
78 received_bytes_
+= bytes
;
80 bool is_incomplete_message
;
81 scoped_ptr
<WireMessage
> message
=
82 DeserializeWireMessage(&is_incomplete_message
);
83 if (is_incomplete_message
)
88 ConnectionObserver
, observers_
, OnMessageReceived(*this, *message
));
91 // Whether the message was parsed successfully or not, clear the
92 // |received_bytes_| buffer.
93 received_bytes_
.clear();
96 scoped_ptr
<WireMessage
> Connection::DeserializeWireMessage(
97 bool* is_incomplete_message
) {
98 return WireMessage::Deserialize(received_bytes_
, is_incomplete_message
);
101 } // namespace proximity_auth