MotionLib  1.0.0
SamBuCa motion library
MGrblDeviceWrapper.cpp
1 // Copyright (C) 2022 CERN
2 //
3 // This software is provided 'as-is', without any express or implied
4 // warranty. In no event will the authors be held liable for any damages
5 // arising from the use of this software.
6 //
7 // Permission is granted to anyone to use this software for any purpose,
8 // including commercial applications, and to alter it and redistribute it
9 // freely, subject to the following restrictions:
10 //
11 // 1. The origin of this software must not be misrepresented; you must not
12 // claim that you wrote the original software. If you use this software
13 // in a product, an acknowledgment in the product documentation would be
14 // appreciated but is not required.
15 // 2. Altered source versions must be plainly marked as such, and must not be
16 // misrepresented as being the original software.
17 // 3. This notice may not be removed or altered from any source distribution.
18 //
19 // Created on: 2022-05-13
20 // Author: Michal Mysior <mmysior> <michal.mysior@cern.ch>
21 //
22 
23 #include "MGrblDeviceWrapper.hpp"
24 
25 #include <logger/Logger.hpp>
26 
27 using namespace logger;
28 
29 namespace grbl {
30 
31 static const std::string s_loggerCat{"smc:grbl:mgrbldevice"};
32 
33 MGrblDeviceWrapper::MGrblDeviceWrapper(
34  size_t instance,
35  const std::shared_ptr<grbl::GrblDeviceBase> &device) :
36  m_instance(instance),
37  m_device(device)
38 {}
39 
40 void MGrblDeviceWrapper::read()
41 {
42  m_device->read();
43 }
44 void MGrblDeviceWrapper::write(const std::string &data)
45 {
46  warning(s_loggerCat) << "raw write called on MGrblDeviceWrapper";
47  m_device->write(data);
48 }
49 
50 grbl::ErrorCode MGrblDeviceWrapper::send(
51  const std::string &cmd,
52  std::function<bool(const std::string &)> msg,
53  const std::chrono::milliseconds &timeout)
54 {
55  char id = static_cast<char>('0' + m_instance);
56  if (bool(msg))
57  return m_device->send(
58  id + cmd,
59  [this, msg, id](const std::string &line) {
60  if (!line.empty() && line[0] == id)
61  return msg(line.substr(1));
62  return false;
63  },
64  timeout);
65  else
66  return m_device->send(id + cmd, {}, timeout);
67 }
68 
69 grbl::ErrorCode MGrblDeviceWrapper::sendRealtime(
70  const std::string &cmd,
71  std::function<bool(const std::string &)> msg,
72  const std::chrono::milliseconds &timeout)
73 {
74  char id = static_cast<char>('0' + m_instance);
75  if (bool(msg))
76  return m_device->sendRealtime(
77  id + cmd,
78  [this, msg, id](const std::string &line) {
79  if (!line.empty() && line[0] == id)
80  return msg(line.substr(1));
81  return false;
82  },
83  timeout);
84  else
85  return m_device->sendRealtime(id + cmd, {}, timeout);
86 }
87 
88 bool MGrblDeviceWrapper::wait(const std::chrono::milliseconds &timeout)
89 {
90  return m_device->wait(timeout);
91 }
92 
93 void MGrblDeviceWrapper::wake()
94 {
95  m_device->wake();
96 }
97 
98 } // namespace grbl