BPLightContraption
 All Classes Namespaces Files Functions Variables Macros Pages
microcont.cpp
Go to the documentation of this file.
1 /*! \file
2  * \brief Class for controlling the microcontroller
3  * \author Benjamin Pritchard (ben@bennyp.org)
4  * \copyright 2013 Benjamin Pritchard. Released under the MIT License
5  */
6 
7 #include "powerunit_gui.h"
8 #include "commands.h"
9 #include "microcont.h"
10 
11 #include <QtSerialPort/QSerialPort>
12 #include <QtSerialPort/QSerialPortInfo>
13 
15 {
17 }
18 
19 QSerialPort::SerialPortError MCInterface::GetSPError(void) const
20 {
21  return _sp.error();
22 }
23 
24 int MCInterface::GetMCError(void) const
25 {
26  return _mcerror;
27 }
28 
30 {
31  return _mcerrorid;
32 }
33 
35 {
36  return _mcerrorcmd;
37 }
38 
39 void MCInterface::OpenPort(const QString & port)
40 {
41  if(_sp.isOpen())
42  ClosePort();
43 
44  //_sp.setBaudRate(QSerialPort::Baud2400);
45  //_sp.setBaudRate(QSerialPort::Baud9600);
46  _sp.setBaudRate(QSerialPort::Baud38400);
47  //_sp.setBaudRate(QSerialPort::Baud57600);
48  _sp.setStopBits(QSerialPort::OneStop);
49  _sp.setParity(QSerialPort::NoParity);
50  _sp.setDataBits(QSerialPort::Data8);
51 
52  QSerialPortInfo qi(port);
53 
54  _sp.setPort(qi);
55 
56  if(!_sp.open(QIODevice::ReadWrite))
57  {
58  _sp.close();
59  ThrowException("Unable to open port");
60  }
61 
62  QByteArray idstring = SendCommand(NULL, 0, 3, 2000);
63 
64  if(idstring.size() != 3 || idstring[0] != 'B' || idstring[1] != 'e' || idstring[2] != 'n')
65  {
66  _sp.close();
67  ThrowException(QString("Invalid initial connection response: ").append(idstring));
68  }
69 }
70 
71 
73 {
74  if(_sp.isOpen())
75  _sp.close();
76 }
77 
79 {
80  ClosePort();
81  OpenPort(_sp.portName());
82 }
83 
84 
85 
86 QByteArray MCInterface::SendCommand(const quint8 * command, int len, unsigned int expectedreslen, int timeout)
87 {
89 
90  if(!(_sp.isOpen()))
91  ThrowException("Port not opened");
92 
93  if(len > 0)
94  {
95  if(_sp.write((const char *)command, len) != len)
96  ThrowException("Unable to write command");
97  }
98 
99  QByteArray res;
100  while((unsigned int)res.size() < (4+expectedreslen))
101  {
102 
103  if(!( _sp.waitForReadyRead(timeout)))
104  ThrowException("Timeout waiting for response");
105 
106  res.push_back(_sp.readAll());
107  }
108 
109  _mcerror = res[1];
110  _mcerrorcmd = res[2];
111  _mcerrorid = res[3];
112 
113  if(_mcerror != RES_SUCCESS)
114  ThrowException("MCInterface error");
115 
116  if((unsigned int)res[0] != (3+expectedreslen))
117  ThrowException(QString("Unexpected response size: %1 instead of %2").arg((int)res[0]).arg(3+expectedreslen));
118 
119  return res.mid(4, res.size()-4);
120 }
121 
122 void MCInterface::ThrowException(const QString & desc) const
123 {
125 }
126 
128 {
129  uint8_t infocmd[2] = {'\\',COM_INFO};
130  return SendCommand(infocmd, 2, INFO_SIZE);
131 }
132 
133 
135 {
136  return _sp.isOpen();
137 }
138