MotionLib  1.0.0
SamBuCa motion library
GrblTester.cpp
1 /*
2  * Copyright (C) 2022 CERN
3  *
4  * This software is provided 'as-is', without any express or implied
5  * warranty. In no event will the authors be held liable for any damages
6  * arising from the use of this software.
7  *
8  * Permission is granted to anyone to use this software for any purpose,
9  * including commercial applications, and to alter it and redistribute it
10  * freely, subject to the following restrictions:
11  *
12  * 1. The origin of this software must not be misrepresented; you must not
13  * claim that you wrote the original software. If you use this software
14  * in a product, an acknowledgment in the product documentation would be
15  * appreciated but is not required.
16  * 2. Altered source versions must be plainly marked as such, and must not be
17  * misrepresented as being the original software.
18  * 3. This notice may not be removed or altered from any source distribution.
19  *
20  * Created on: 2022-05-06
21  * Author: Michal Mysior <mmysior> <michal.mysior@cern.ch>
22  *
23  */
24 
25 #include "GrblTester.hpp"
26 
27 #include <logger/Logger.hpp>
28 
29 #include "Exception.hpp"
30 
31 static const std::string s_loggerCat{"smc:edgegrbltester:sim"};
32 static const std::string s_crnl("\r\n");
33 
34 using namespace logger;
35 using namespace std::chrono;
36 
37 namespace grbl {
38 
39 const milliseconds GrblTester::defaultExpectTimeout{500};
40 
41 GrblTester::GrblTester(std::unique_ptr<GrblDeviceBase> grblDevice) :
42  m_grblDevice{std::move(grblDevice)}
43 {}
44 
45 bool GrblTester::expect(const std::string &regex,
46  std::chrono::milliseconds timeout)
47 {
48  const ccut::Regex re(regex);
49  return expect(re, timeout);
50 }
51 
52 bool GrblTester::expect(const ccut::Regex &regex,
53  std::chrono::milliseconds timeout)
54 {
55  const steady_clock::time_point deadline = steady_clock::now() + timeout;
56 
57  while (steady_clock::now() <= deadline)
58  {
59  steady_clock::time_point now = steady_clock::now();
60  const milliseconds remaining = (now < deadline) ?
61  duration_cast<milliseconds>(deadline - now) :
62  milliseconds::zero();
63 
64  try
65  {
66  m_grblDevice->wait(remaining);
67  }
68  catch (smc::Exception &ex)
69  {
70  error(s_loggerCat) << ex.what();
71  return false;
72  }
73  m_grblDevice->read();
74  std::string line;
75  while (m_grblDevice->takeLine(line))
76  {
77  if (regex.search(line))
78  {
79  debug(s_loggerCat) << "<-- " << line;
80  return true;
81  }
82  else
83  {
84  debug(s_loggerCat) << "x<- " << line;
85  }
86  }
87  }
88  return false;
89 }
90 
91 void GrblTester::sendCmd(const std::string &command)
92 {
93  debug(s_loggerCat) << "--> " << command;
94  m_grblDevice->write(command);
95  m_grblDevice->write(s_crnl);
96 }
97 
98 } // namespace grbl
Exception thrown by MotionController in case of issues with command.
Definition: Exception.hpp:61