blob: 9f79bf3d4626d50fb7862e2cab64d71c53d44881 [file] [log] [blame]
Garrick Evans96e03042019-05-28 14:30:52 +09001// Copyright 2019 The Chromium OS 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
Garrick Evans3388a032020-03-24 11:25:55 +09005#ifndef PATCHPANEL_MESSAGE_DISPATCHER_H_
6#define PATCHPANEL_MESSAGE_DISPATCHER_H_
Garrick Evans96e03042019-05-28 14:30:52 +09007
8#include <memory>
9#include <string>
10
Hidehiko Abede129222019-08-16 00:55:04 +090011#include <base/files/file_descriptor_watcher_posix.h>
Garrick Evans96e03042019-05-28 14:30:52 +090012#include <base/files/scoped_file.h>
13#include <base/macros.h>
14#include <base/memory/weak_ptr.h>
Garrick Evans96e03042019-05-28 14:30:52 +090015
Garrick Evans3388a032020-03-24 11:25:55 +090016#include "patchpanel/ipc.pb.h"
Garrick Evans96e03042019-05-28 14:30:52 +090017
Garrick Evans3388a032020-03-24 11:25:55 +090018namespace patchpanel {
Garrick Evans96e03042019-05-28 14:30:52 +090019
20// Helper message processor
Hidehiko Abede129222019-08-16 00:55:04 +090021class MessageDispatcher {
Garrick Evans96e03042019-05-28 14:30:52 +090022 public:
Taoyu Liaf944c92019-10-01 12:22:31 +090023 explicit MessageDispatcher(base::ScopedFD fd, bool start = true);
24
25 void Start();
Garrick Evans96e03042019-05-28 14:30:52 +090026
27 void RegisterFailureHandler(const base::Callback<void()>& handler);
28
29 void RegisterGuestMessageHandler(
30 const base::Callback<void(const GuestMessage&)>& handler);
31
32 void RegisterDeviceMessageHandler(
33 const base::Callback<void(const DeviceMessage&)>& handler);
34
Taoyu Liaf944c92019-10-01 12:22:31 +090035 void SendMessage(const google::protobuf::MessageLite& proto) const;
36
Garrick Evans96e03042019-05-28 14:30:52 +090037 private:
38 // Overrides MessageLoopForIO callbacks for new data on |control_fd_|.
Hidehiko Abede129222019-08-16 00:55:04 +090039 void OnFileCanReadWithoutBlocking();
Garrick Evans96e03042019-05-28 14:30:52 +090040
Garrick Evans96e03042019-05-28 14:30:52 +090041 base::ScopedFD fd_;
Hidehiko Abede129222019-08-16 00:55:04 +090042 std::unique_ptr<base::FileDescriptorWatcher::Controller> watcher_;
Garrick Evans96e03042019-05-28 14:30:52 +090043 base::Callback<void()> failure_handler_;
44 base::Callback<void(const GuestMessage&)> guest_handler_;
45 base::Callback<void(const DeviceMessage&)> device_handler_;
Hidehiko Abede129222019-08-16 00:55:04 +090046
Garrick Evans96e03042019-05-28 14:30:52 +090047 IpHelperMessage msg_;
48
49 base::WeakPtrFactory<MessageDispatcher> weak_factory_{this};
50 DISALLOW_COPY_AND_ASSIGN(MessageDispatcher);
51};
52
Garrick Evans3388a032020-03-24 11:25:55 +090053} // namespace patchpanel
Garrick Evans96e03042019-05-28 14:30:52 +090054
Garrick Evans3388a032020-03-24 11:25:55 +090055#endif // PATCHPANEL_MESSAGE_DISPATCHER_H_