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
,
59 OnConnectionStatusChanged(*this, old_status
, status_
));
62 void Connection::OnDidSendMessage(const WireMessage
& message
, bool success
) {
63 if (!is_sending_message_
) {
64 VLOG(1) << "Send completed, but no message in progress.";
68 is_sending_message_
= false;
70 ConnectionObserver
, observers_
, OnSendCompleted(*this, message
, success
));
73 void Connection::OnBytesReceived(const std::string
& bytes
) {
75 VLOG(1) << "Received bytes, but not connected.";
79 received_bytes_
+= bytes
;
81 bool is_incomplete_message
;
82 scoped_ptr
<WireMessage
> message
=
83 DeserializeWireMessage(&is_incomplete_message
);
84 if (is_incomplete_message
)
89 ConnectionObserver
, observers_
, OnMessageReceived(*this, *message
));
92 // Whether the message was parsed successfully or not, clear the
93 // |received_bytes_| buffer.
94 received_bytes_
.clear();
97 scoped_ptr
<WireMessage
> Connection::DeserializeWireMessage(
98 bool* is_incomplete_message
) {
99 return WireMessage::Deserialize(received_bytes_
, is_incomplete_message
);
102 } // namespace proximity_auth