1 // ANNA - Anna is Not Nothingness Anymore
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
5 // http://redmine.teslayout.com/projects/anna-suite
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
11 // * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 // * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
17 // * Neither the name of the copyright holder nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33 // Authors: eduardo.ramos.testillano@gmail.com
34 // cisco.tierra@gmail.com
39 #include <netinet/in.h>
41 #include <anna/core/RuntimeException.hpp>
42 #include <anna/config/defines.hpp>
43 #include <anna/core/tracing/Logger.hpp>
44 #include <anna/core/functions.hpp>
45 #include <anna/core/util/Second.hpp>
46 #include <anna/core/util/Millisecond.hpp>
47 #include <anna/core/util/Microsecond.hpp>
49 #include <anna/comm/CompatCodec.hpp>
50 #include <anna/comm/functions.hpp>
51 #include <anna/comm/Variable.hpp>
56 bool comm::CompatCodec::st_initScramble(false);
59 template <class T, class M> comm::Variable* insert(const char* name, const short int id, M& theVector, T& value)
60 throw(RuntimeException) {
61 comm::Variable* result = theVector.find(id);
64 throw RuntimeException(functions::asString("Variable Id %d alreay used", id), ANNA_FILE_LOCATION);
66 theVector.add(result = new comm::Variable(id, name, value));
68 String msg("insert <T, M> | ");
69 msg << result->asString();
70 Logger::debug(msg, ANNA_FILE_LOCATION);
76 template <class T, class M> comm::Variable* insertRef(const char* name, const short int id, M& theVector, T& value)
77 throw(RuntimeException) {
78 comm::Variable* result = theVector.find(id);
81 throw RuntimeException(functions::asString("Variable Id %d alreay used", id), ANNA_FILE_LOCATION);
83 theVector.add(result = new comm::Variable(id, name, value.refValue()));
85 String msg("insert <T, M> | ");
86 msg << result->asString();
87 Logger::debug(msg, ANNA_FILE_LOCATION);
92 comm::CompatCodec::CompatCodec(const comm::CompatCodec::Type type, const bool scramble) :
93 comm::Message(comm::Message::StatusCodeBuffer::None),
97 if(a_scramble == true && st_initScramble == false) {
98 st_initScramble = true;
103 comm::CompatCodec::~CompatCodec() {
104 for(iterator ii = begin(), maxii = end(); ii != maxii; ii ++)
110 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, std::string& value)
111 throw(RuntimeException) {
112 return insert(name, id, a_variables, value);
115 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, int& value)
116 throw(RuntimeException) {
117 const int backup(value);
118 const Variable* result = insert(name, id, a_variables, value);
123 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, S64& value)
124 throw(RuntimeException) {
125 const S64 backup(value);
126 const Variable* result = insert(name, id, a_variables, value);
131 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, bool& value)
132 throw(RuntimeException) {
133 const bool backup(value);
134 const Variable* result = insert(name, id, a_variables, value);
139 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, DataBlock& value)
140 throw(RuntimeException) {
141 return insert(name, id, a_variables, value);
144 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, float& value)
145 throw(RuntimeException) {
146 const float backup(value);
147 const Variable* result = insert(name, id, a_variables, value);
152 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, double& value)
153 throw(RuntimeException) {
154 const double backup(value);
155 const Variable* result = insert(name, id, a_variables, value);
160 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, Second& value)
161 throw(RuntimeException) {
162 const Second backup(value);
163 const Variable* result = insertRef(name, id, a_variables, value);
168 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, Millisecond& value)
169 throw(RuntimeException) {
170 const Millisecond backup(value);
171 const Variable* result = insertRef(name, id, a_variables, value);
176 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, Microsecond& value)
177 throw(RuntimeException) {
178 const Microsecond backup(value);
179 const Variable* result = insertRef(name, id, a_variables, value);
184 const comm::Variable* comm::CompatCodec::attach(const char* name, const short int id, comm::CompatCodec& value)
185 throw(RuntimeException) {
187 String msg("comm::CompatCodec::attach | Variable: ");
188 msg << name << " | Can not link with itself";
189 throw RuntimeException(msg, ANNA_FILE_LOCATION);
192 return insert(name, id, a_variables, value);
195 void comm::CompatCodec::setNull(const short int id, const bool isNull)
196 throw(RuntimeException) {
197 Variable* variable = a_variables.find(id);
200 throw RuntimeException(functions::asString("Id %d is not defined", id), ANNA_FILE_LOCATION);
202 if(variable->isNull()) {
203 if(isNull == false) a_nullCounter --;
206 if(isNull == true) a_nullCounter ++;
209 variable->setNull(isNull);
212 void comm::CompatCodec::setNull(const comm::Variable* variable, const bool isNull)
214 if(variable->isNull()) {
215 if(isNull == false) a_nullCounter --;
218 if(isNull == true) a_nullCounter ++;
221 const_cast <comm::Variable*>(variable)->setNull(isNull);
224 bool comm::CompatCodec::isNull(const short int id) const
225 throw(RuntimeException) {
226 const Variable* variable = a_variables.find(id);
229 throw RuntimeException(functions::asString("Id %d is not defined", id), ANNA_FILE_LOCATION);
231 return variable->isNull();
234 const comm::Variable& comm::CompatCodec::find(const short int id) const
235 throw(RuntimeException) {
236 const Variable* variable = a_variables.find(id);
239 throw RuntimeException(functions::asString("Id %d is not defined", id), ANNA_FILE_LOCATION);
244 //-----------------------------------------------------------------------
245 // Codificacin de los datos en un bloque de memoria.
247 // mensaje ::= <byte0><byte1><byte2> <dato> ... <dato>
249 // dato ::= <byteA><byteB><byteC> [<cadena | int | long | bloque>]
250 // cadena ::= <byteLSB><byteMSB> < contenido > </0>
251 // int ::= <byteLSB> <byte> <byte> <byteMSB>
252 // long ::= <byteLSB> <byte> <byte> <byteMSB>
253 // bloque ::= <int> < contenido >
255 // (0) byte0 = Si es distinto de cero => contiene la clave usada para codificar
257 // (2) byte1 = Nmero de datos que contiene el mensaje.
258 // Recordar que slo se transfieren a este bloque de memoria los datos que
259 // tengan asignado algn value.
260 // (1) byte2 = Typeentificador del mensaje interno.
261 // (3) Los bytes A y B contienen del identificador del dato.
262 // (4) Los cuatro primeros bits del byteC indican el tipo de dato. En los
263 // tipos de datos boolean su contenido se guarda en el bit mas significativo
265 // (5) En las cadenas los dos primeros byres indican la longitud de la cadena
266 // incluyendo el indicador de fin de cadena, luego aparece el contenido
267 // de la cadena y finalmente el 0. El cero se incluye para optimizar
268 // la recogida de datos.
269 //-----------------------------------------------------------------------
270 const DataBlock& comm::CompatCodec::code()
271 throw(RuntimeException) {
274 iterator maxii(a_variables.end());
278 char aux [sizeof(S64)];
280 if(a_scramble == true) // (1)
281 while(c == 0) c = rand() % 0xff;
283 DataBlock& self = *this;
286 self += (char)(a_variables.size() - a_nullCounter); // (2)
287 self += comm::CompatCodec::getType(); // (1)
289 for(ii = begin(); ii != maxii; ii ++) {
290 variable = CompatCodec::variable(ii);
292 if(a_nullCounter > 0 && variable->isNull() == true)
295 switch(variable->getType()) {
296 case Variable::Type::String:
297 self += variable->codec();
298 stringLen = anna_strlen(string = variable->getStringValue()) + 1;
299 self.append(comm::functions::codeShort(aux, stringLen), sizeof(short int));
300 self.append(string, stringLen);
302 case Variable::Type::Integer:
303 self += variable->codec();
304 self.append(comm::functions::codeInteger(aux, variable->getInteger()), sizeof(int));
306 case Variable::Type::Integer64:
307 self += variable->codec();
308 self.append(comm::functions::codeInteger64(aux, variable->getInteger64()), sizeof(S64));
310 case Variable::Type::Boolean:
311 self.append(comm::functions::codeShort(aux, variable->getId()), sizeof(short int)); // (3)
312 c = Variable::Type::Boolean;
314 if(variable->getBoolean() == true) // (4)
319 case Variable::Type::Block:
320 self += variable->codec();
321 self.append(comm::functions::codeInteger(aux, variable->getDataBlock().getSize()), sizeof(int));
322 self += variable->getDataBlock();
324 case Variable::Type::Float:
325 self += variable->codec();
326 self.append(comm::functions::codeFloat(aux, variable->getFloat()), sizeof(float));
328 case Variable::Type::Double:
329 self += variable->codec();
330 self.append(comm::functions::codeDouble(aux, variable->getDouble()), sizeof(float));
332 case Variable::Type::Custom:
333 self += variable->codec();
335 const DataBlock& codec = reinterpret_cast <CompatCodec*>(variable->getCustom())->code();
336 self.append(comm::functions::codeInteger(aux, codec.getSize()), sizeof(int));
346 // Se sacan aqui para evitar qtene que comprobar el estado de las trazas en cada paso
347 for(ii = begin(); ii != maxii; ii ++)
348 Logger::debug(CompatCodec::variable(ii)->asString(), ANNA_FILE_LOCATION);
349 Logger::write(Logger::Debug, "comm::CompatCodec::code", self, ANNA_FILE_LOCATION)
352 if(a_scramble == true) {
353 char* data = const_cast <char*>(self.getData());
354 int size = self.getSize();
356 for(int i = 1, key = data [0]; i < size; i ++)
363 //-------------------------------------------------------------------------------------------
364 void comm::CompatCodec::decode(const DataBlock& dataBlock)
365 throw(RuntimeException) {
366 const char* data = dataBlock.getData();
367 const int size = dataBlock.getSize();
370 throw RuntimeException("Can not decode an empty DataBlock", ANNA_FILE_LOCATION);
373 for(int i = 1, key(data [0]); i < size; i ++)
374 const_cast <char*>(data)[i] ^= key ++;
376 LOGDEBUG(Logger::write(Logger::Debug, "comm::CompatCodec::decode", dataBlock, ANNA_FILE_LOCATION));
377 const int maxdata = data [1];
379 if(maxdata != a_variables.size())
380 normalDecode(data, size, maxdata);
381 else if(optimizedDecode(data, size) == false)
382 normalDecode(data, size, maxdata);
386 for(const_iterator ii = begin(), maxii = end(); ii != maxii; ii ++)
387 Logger::debug(CompatCodec::variable(ii)->asString(), ANNA_FILE_LOCATION);
391 //-------------------------------------------------------------------------------------------
392 // Decodifica los buffers que pueden contener variables nulas.
393 //-------------------------------------------------------------------------------------------
394 void comm::CompatCodec::normalDecode(const char* data, const int size, const int maxdata)
395 throw(RuntimeException) {
396 // Mientras no se demuestre lo contrario todas las variables son nulas
397 a_nullCounter = a_variables.size();
399 for(iterator ii = begin(), maxii = end(); ii != maxii; ii ++)
400 CompatCodec::variable(ii)->setNull(true);
405 bool hasError = false;
406 const char* top = data + size;
409 for(int ndata = 0; ndata < maxdata && data < top; ndata ++) {
410 id = comm::functions::decodeShort(data);
411 data += sizeof(short int);
413 if((variable = a_variables.find(id)) == NULL) {
420 switch(*data & 0x7f) {
421 case Variable::Type::String:
422 nbytes = comm::functions::decodeShort(++ data);
423 variable->setValue(data += sizeof(short int));
426 case Variable::Type::Integer:
427 variable->setInteger(comm::functions::decodeInteger(++ data));
430 case Variable::Type::Integer64:
431 variable->setValue(comm::functions::decodeInteger64(++ data));
434 case Variable::Type::Boolean:
435 variable->setBoolean((*data & 0x80) ? true : false);
438 case Variable::Type::Block:
439 nbytes = comm::functions::decodeInteger(++ data);
440 variable->setDataBlock(DataBlock(data += sizeof(int), nbytes, false));
443 case Variable::Type::Float:
444 variable->setFloat(comm::functions::decodeFloat(++ data));
445 data += sizeof(float);
447 case Variable::Type::Double:
448 variable->setDouble(comm::functions::decodeDouble(++ data));
449 data += sizeof(double);
451 case Variable::Type::Custom:
452 nbytes = comm::functions::decodeInteger(++ data);
454 DataBlock dataBlock(data += sizeof(int), nbytes, false);
455 reinterpret_cast <CompatCodec*>(variable->getCustom())->decode(dataBlock);
462 if(hasError == true) {
463 string msg("comm::CompatCodec::normalDecode | Buffer: ");
464 msg += functions::asString(DataBlock(data, size, false));
465 msg += functions::asText(" | Id is not defined: ", id);
466 Logger::error(msg, ANNA_FILE_LOCATION);
469 if(a_nullCounter < 0) {
472 string msg("comm::CompatCodec::normalDecode | Buffer: ");
473 msg += functions::asString(DataBlock(data, size, false));
474 msg += " | NullCounter is less than zero";
475 Logger::warning(msg, ANNA_FILE_LOCATION);
480 //-------------------------------------------------------------------------------------------
481 // Decodifica optimizadamente buffers que no tengan variables nulas.
482 // (1) El codigo de la variable
483 //-------------------------------------------------------------------------------------------
484 bool comm::CompatCodec::optimizedDecode(const char* data, const int size)
485 throw(RuntimeException) {
488 const char* top = data + size;
491 for(iterator ii = begin(), maxii = end(); ii != maxii && data < top; ii ++) {
492 data += sizeof(short int);
493 variable = CompatCodec::variable(ii);
495 switch(*data & 0x7f) {
496 case Variable::Type::String:
497 nbytes = comm::functions::decodeShort(++ data);
498 variable->setValue(data += sizeof(short int));
501 case Variable::Type::Integer:
502 variable->setInteger(comm::functions::decodeInteger(++ data));
505 case Variable::Type::Integer64:
506 variable->setValue(comm::functions::decodeInteger64(++ data));
509 case Variable::Type::Boolean:
510 variable->setBoolean((*data & 0x80) ? true : false);
513 case Variable::Type::Block:
514 nbytes = comm::functions::decodeInteger(++ data);
515 variable->setDataBlock(DataBlock(data += sizeof(int), nbytes, false));
518 case Variable::Type::Float:
519 variable->setFloat(comm::functions::decodeFloat(++ data));
520 data += sizeof(float);
522 case Variable::Type::Double:
523 variable->setDouble(comm::functions::decodeDouble(++ data));
524 data += sizeof(double);
526 case Variable::Type::Custom:
527 nbytes = comm::functions::decodeInteger(++ data);
529 DataBlock dataBlock(data += sizeof(int), nbytes, false);
530 reinterpret_cast <CompatCodec*>(variable->getCustom())->decode(dataBlock);
537 return (data == top);
540 comm::CompatCodec::Type comm::CompatCodec::getType(const DataBlock& dataBlock)
541 throw(RuntimeException) {
542 const int size(dataBlock.getSize());
545 throw RuntimeException("DataBlock is not valid", ANNA_FILE_LOCATION);
547 const char* data(dataBlock.getData());
548 comm::CompatCodec::Type result;
549 result = (data [0] != 0) ? ((data [0] + 1) ^ data [2]) : data [2];
550 LOGDEBUG(Logger::write(Logger::Debug, "comm::CompatCodec::getType", result, ANNA_FILE_LOCATION));
554 comm::CompatCodec::VariableContainer::VariableContainer() {
557 a_variables = new Variable* [a_maxSize];
558 anna_memset(a_variables, 0, sizeof(Variable*) * a_maxSize);
561 void comm::CompatCodec::VariableContainer::add(comm::Variable* variable)
563 if(a_size == a_maxSize) {
564 int maxSize = (a_maxSize << 1) - (a_maxSize >> 1);
565 Variable** variables = new Variable* [maxSize];
566 anna_memset(variables, 0, sizeof(Variable*) * maxSize);
567 anna_memcpy(variables, a_variables, sizeof(Variable*) * a_size);
569 a_variables = variables;
573 a_variables [a_size ++] = variable;
576 comm::Variable* comm::CompatCodec::VariableContainer::find(const int id)
578 for(int ii = 0; ii < a_size; ii ++) {
579 if(a_variables [ii]->getId() == id)
580 return a_variables [ii];
586 const comm::Variable* comm::CompatCodec::VariableContainer::find(const int id) const
588 for(int ii = 0; ii < a_size; ii ++) {
589 if(a_variables [ii]->getId() == id)
590 return a_variables [ii];
596 void comm::CompatCodec::VariableContainer::clear()
598 delete [] a_variables;
599 a_maxSize = a_size = 0;