-
Notifications
You must be signed in to change notification settings - Fork 1
/
protocol.cpp
86 lines (68 loc) · 2.43 KB
/
protocol.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/* SPDX-License-Identifier: GPLv3-or-later */
/* Copyright (c) 2019 Project WomoLIN */
/* Author Myron Franze <[email protected]> */
#include "protocol.h"
#include "interface/helper.h"
#include <iostream>
namespace siguni
{
CProtocol::CProtocol( interface::IControlbus & attControlbus )
: controlbus( attControlbus )
{
}
bool CProtocol::GetKeyValue( std::string & attKey, std::string & attValue)
{
// if no key or value found, then send empty strings
attKey.clear();
attValue.clear();
// read bytes to buffer
std::string buffer;
if ( 0 >= controlbus.ReadData( buffer ) &&
0 == messageBuffer.size()
)
{
return false;
}
// add read bytes to internal message buffer
messageBuffer += buffer;
// search startbyte within messagebuffer, if not found then clear messagebuffer
auto pos = helper::CSignalStrings::FindFirstCharacter( messageBuffer, STARTBYTE );
if( pos < 0 )
{
messageBuffer.clear();
return false;
}
// remove all bytes left from startbyte
messageBuffer = messageBuffer.substr( pos );
// search first endbyte after first startbyte
pos = helper::CSignalStrings::FindFirstCharacter( messageBuffer, ENDBYTE );
if( pos < 0 )
{
// we have a max size of input messages
if( messageBuffer.size() > MESSAGE_BUFFER_MAX_SIZE )
{
// clear buffer to prevent a memory overflow for invalid messages
messageBuffer.clear();
}
return false;
}
// copy a full raw message without start and end byte
auto protocolString = messageBuffer.substr( 1, pos-1 );
// remove this message from buffer
messageBuffer = messageBuffer.substr( pos+1 );
// if there is more than one start byte, delete all previous start bytes
pos = helper::CSignalStrings::FindLastCharacter( protocolString, STARTBYTE );
if( pos >= 0)
{
protocolString = protocolString.substr( pos+1 );
}
return helper::CSignalStrings::SplitKeyValue(
protocolString, SEPARATOR, attKey, attValue );
}
void CProtocol::SendKeyValue( std::string & attKey, std::string & attValue )
{
std::string message;
message = STARTBYTE + attKey + SEPARATOR + attValue + ENDBYTE + LINEBREAK;
controlbus.WriteData( message );
}
}