client-cpp  0.7.4
DisconnectMessage.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2014 CyberVision, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef DISCONNECTMESSAGE_HPP_
18 #define DISCONNECTMESSAGE_HPP_
19 
23 #include <boost/format.hpp>
24 
25 namespace kaa
26 {
27 
28 enum class DisconnectReason : std::uint8_t
29 {
30  NONE = 0x00,
31  BAD_REQUEST = 0x01,
32  INTERNAL_ERROR = 0x02,
33 };
34 
36 {
37 public:
38  static std::string reasonToString(DisconnectReason reason)
39  {
40  switch (reason) {
42  return "No error";
44  return "Bad request";
46  return "Internal error has been occurred";
47  default:
48  return (boost::format("Invalid Disconnect reason %1%") % (std::uint8_t) reason).str();
49  }
50  }
51 
52  DisconnectMessage(DisconnectReason reason) : message_(4), reason_(reason)
53  {
54  char header[2];
56  std::copy(reinterpret_cast<const std::uint8_t *>(header),
57  reinterpret_cast<const std::uint8_t *>(header + 2),
58  message_.begin());
59  message_[2] = 0;
60  message_[3] = (std::uint8_t) reason_;
61  }
62 
63  DisconnectMessage(const char *payload, std::uint16_t size)
64  {
65  parseMessage(payload, size);
66  }
67 
69 
70  DisconnectReason getReason() const { return reason_; }
71  std::string getMessage() const { return reasonToString(reason_); }
72 
73  const std::vector<std::uint8_t>& getRawMessage() const { return message_; }
74 
75 private:
76  void parseMessage(const char *payload, std::uint16_t size)
77  {
78  if (!payload || !size) {
79  throw KaaException("Bad Disconnect payload data");
80  }
81 
82  int code = *(payload + 1);
83  if (code < (int)DisconnectReason::NONE || code > (int)DisconnectReason::INTERNAL_ERROR) {
84  throw KaaException(boost::format("Bad Disconnect return code: %1%") % code);
85  }
86  reason_ = (DisconnectReason) code;
87  }
88 
89 private:
90  std::vector<std::uint8_t> message_;
91  DisconnectReason reason_;
92 
93 };
94 
95 }
96 
97 
98 
99 #endif /* DISCONNECTREQUEST_HPP_ */
static std::string reasonToString(DisconnectReason reason)
DisconnectMessage(const char *payload, std::uint16_t size)
DisconnectMessage(DisconnectReason reason)
DisconnectReason getReason() const
std::string getMessage() const
static std::uint8_t createBasicHeader(std::uint8_t messageType, std::uint32_t length, char *message)
const std::vector< std::uint8_t > & getRawMessage() const