Ejemplo n.º 1
0
void ReceiveThread(int* s, int id)
{
	bool paskafix = true;
	char* buf = (char*)malloc(sizeof(int));

	recvThreadMutex.lock();

	while (1)
	{
		if(purkka != 0)
		{
			memset((void*)buf, 0, sizeof(int));
			if (recv(*s, buf, sizeof(int), 0) == SOCKET_ERROR)
			{
				int errsave = errno;
				printf("recvfrom(...) failed! Error code : %d\n", errsave);
				free(buf);
				return;
			}

			if (paskafix)
			{
				recvThreadMutex.unlock();
				paskafix = false;
			}

			ParseMessage(buf, *s, id);
		}
		else
			return;
	}
}
Ejemplo n.º 2
0
/**
 * Handle as message from JavaScript on the worker thread.
 *
 * @param[in] message The message to parse and handle.
 */
static void HandleMessage(struct PP_Var message)
{
    const char *function_name,*error;
    struct PP_Var params,result_var;
    if ( ParseMessage(message, &function_name, &params) != 0 )
    {
        PostMessage("Error: Unable to parse message");
        return;
    }
    HandleFunc function = GetFunctionByName(function_name);
    if ( function == 0 )
    {
        PostMessage("Error: Unknown function \"%s\"", function_name); // Function name wasn't found.
        return;
    }
    // Function name was found, call it.
    int result = (*function)(params, &result_var, &error);
    if ( result != 0 )
    {
        if ( error != NULL )
        {
            PostMessage("Error: \"%s\" failed: %s.", function_name, error);
            free((void*)error);
        }
        else PostMessage("Error: \"%s\" failed.", function_name);
        return;
    }
    // Function returned an output dictionary. Send it to JavaScript.
    g_ppb_messaging->PostMessage(g_instance, result_var);
    g_ppb_var->Release(result_var);
}
Ejemplo n.º 3
0
void RemoteClient::IncomingData() {
  while (client_->bytesAvailable()) {
    if (!reading_protobuf_) {
      // Read the length of the next message
      QDataStream s(client_);
      s >> expected_length_;

      // Receiving more than 128mb is very unlikely
      // Flush the data and disconnect the client
      if (expected_length_ > 134217728) {
        qLog(Debug) << "Received invalid data, disconnect client";
        qLog(Debug) << "expected_length_ =" << expected_length_;
        client_->close();
        return;
      }

      reading_protobuf_ = true;
    }

    // Read some of the message
    buffer_.write(
      client_->read(expected_length_ - buffer_.size()));

    // Did we get everything?
    if (buffer_.size() == expected_length_) {
      // Parse the message
      ParseMessage(buffer_.data());

      // Clear the buffer
      buffer_.close();
      buffer_.setData(QByteArray());
      buffer_.open(QIODevice::ReadWrite);
      reading_protobuf_ = false;
    }
  }
Ejemplo n.º 4
0
int DiskoveryListener::svc()
{
   core_.LogMessage(&device_, "Starting Diskovery Listener Thread", true);

   char answer[MM::MaxStrLength];
   std::string term = "\r\n";
   int ret = DEVICE_OK;
   while (!stop_)
   {
      ret = core_.GetSerialAnswer(&device_, port_.c_str(), MM::MaxStrLength, answer, term.c_str());
      // serial timeout should be set to a number larger than 5 seconds
      // and a timeout indicates that the device is not here.  
      // TODO: communicate this fact back to the adapter
      if (ret == DEVICE_SERIAL_TIMEOUT)
      {
      }
      if (ret == DEVICE_OK) {
         ParseMessage(answer);
      } else
      {
         // this can only be bad
         // TODO: communicate the bad situation and bail
      }

   }
   return 0;
}
Ejemplo n.º 5
0
void service::ParseIRCCommand( QString command ) {
    QStringList section = command.split(" ");
    if( section[0] == "PING" ) {
        qDebug() << "Received PING, sending PONG";
        server->send( QString("PONG :tmi.twitch.tv\r\n") );
    } else {
        ParseMessage( section );
    }
}
Ejemplo n.º 6
0
 void ParsePacket(const char *buf, size_t len) {
   // uint16_t hdr_len = read16(buf);
   int count = read8(buf + 2);
   uint32_t seqno = read32(buf + 4);
   buf += 8;
   for (int i = 0; i < count; ++i) {
     uint8_t msg_len = read8(buf);
     ParseMessage(seqno + i, buf);
     buf += msg_len;
   }
 }
Ejemplo n.º 7
0
bool ParseMessage(const std::string& msg_json, IMMessage& message)
{
	Json::Value values;
	Json::Reader reader;
	if (reader.parse(msg_json, values) && values.isObject())
	{
		ParseMessage(values, message);
		return true;
	}
	return false;
}
Ejemplo n.º 8
0
 size_t ParseStream(const char *buf, size_t len) {
   size_t i = 0;
   while (i < len) {
     int msg_len = read8(buf + i);
     if (i + msg_len > len) {
       break;
     }
     ParseMessage(0, buf + i);
     i += msg_len;
   }
   return i;
 }
Ejemplo n.º 9
0
static uint8_t RAPP_OnPacketRx(RPHY_PacketDesc *packet) {
  uint8_t size;
  uint8_t *data;
  RAPP_MSG_Type type;
  RNWK_ShortAddrType srcAddr;
  
  type = (RAPP_MSG_Type)RAPP_BUF_TYPE(packet->phyData);
  size = RAPP_BUF_SIZE(packet->phyData);
  data = RAPP_BUF_PAYLOAD_START(packet->phyData);
  srcAddr = RNWK_BUF_GET_SRC_ADDR(packet->phyData);
  return ParseMessage(type, size, data, srcAddr, packet);
}
Ejemplo n.º 10
0
BOOL SipMessageCallback(char *string, char *ip, int port)
{
    MESSAGE *message = CreateMessage();

    SetMessageAddr(message, ip);
    SetMessagePort(message, port);
    
    if (ParseMessage(string, message) < 0) {
        return FALSE;
    }

    return SipMessageInput(message);
}
Ejemplo n.º 11
0
TEST(TryingMessageBuildTestGroup, TryingMessageCallIdTest)
{
    MESSAGE *invite = CreateMessage();
    ParseMessage(INCOMMING_INVITE_MESSAGE, invite);
    MESSAGE *trying = BuildResponse(invite, STATUS_CODE_TRYING);

    struct CallIdHeader *inviteCallId = (struct CallIdHeader *)MessageGetHeader(HEADER_NAME_CALLID, invite);
    struct CallIdHeader *tryingCallId = (struct CallIdHeader *)MessageGetHeader(HEADER_NAME_CALLID, trying);
    
    CHECK_TRUE(CallIdHeaderMatched(inviteCallId, tryingCallId));
    
    DestroyMessage(&trying);
    DestroyMessage(&invite);    
}
Ejemplo n.º 12
0
TEST(TryingMessageBuildTestGroup, TryingMessageCSeqTest)
{
    MESSAGE *invite = CreateMessage();
    ParseMessage(INCOMMING_INVITE_MESSAGE, invite);
    MESSAGE *trying = BuildResponse(invite, STATUS_CODE_TRYING);
    
    struct CSeqHeader *inviteCSeq = (struct CSeqHeader *)MessageGetHeader(HEADER_NAME_CSEQ, invite);
    struct CSeqHeader *tryingCSeq = (struct CSeqHeader *)MessageGetHeader(HEADER_NAME_CSEQ, trying);

    CHECK_TRUE(CSeqHeadersMatched(inviteCSeq, tryingCSeq));

    DestroyMessage(&trying);
    DestroyMessage(&invite);
}
Ejemplo n.º 13
0
TEST(TryingMessageBuildTestGroup, TryingMessageFromHeaderTest)
{
    MESSAGE *invite = CreateMessage();
    ParseMessage(INCOMMING_INVITE_MESSAGE, invite);

    MESSAGE *trying = BuildResponse(invite, STATUS_CODE_TRYING);
    CONTACT_HEADER *inviteFrom = (CONTACT_HEADER *)MessageGetHeader(HEADER_NAME_FROM, invite);
    CONTACT_HEADER *tryingFrom = (CONTACT_HEADER *)MessageGetHeader(HEADER_NAME_FROM, trying);

    CHECK_TRUE(ContactHeaderMatched(inviteFrom, tryingFrom));

    DestroyMessage(&trying);
    DestroyMessage(&invite);
}
Ejemplo n.º 14
0
TEST(TryingMessageBuildTestGroup, TryingMessageViaTest)
{
    MESSAGE *invite = CreateMessage();
    ParseMessage(INCOMMING_INVITE_MESSAGE, invite);
    MESSAGE *trying = BuildResponse(invite, STATUS_CODE_TRYING);

    VIA_HEADER *inviteVia = (VIA_HEADER *)MessageGetHeader(HEADER_NAME_VIA, invite);
    VIA_HEADER *tryingVia = (VIA_HEADER *)MessageGetHeader(HEADER_NAME_VIA, trying);
    
    CHECK_TRUE(ViaHeaderMatched(inviteVia, tryingVia));

    DestroyMessage(&trying);
    DestroyMessage(&invite);    
}
Ejemplo n.º 15
0
bool ParseReceiveMessage(const std::string& msg_json, IMMessage& message)
{
	Json::Value values;
	Json::Reader reader;
	if (reader.parse(msg_json, values) && values.isObject())
	{
		message.rescode_ = (NIMResCode)values[kNIMMsgKeyLocalRescode].asUInt();
		message.feature_ = (NIMMessageFeature)values[kNIMMsgKeyLocalMsgFeature].asUInt();

		ParseMessage(values[kNIMMsgKeyLocalReceiveMsgContent], message);
		return true;
	}
	
	return false;
}
Ejemplo n.º 16
0
TEST(TryingMessageBuildTestGroup, TryingMessageToWithTagTest)
{
    MESSAGE *invite = CreateMessage();
    ParseMessage(INCOMMING_INVITE_MESSAGE_WITH_TO_TAG, invite);
    
    MESSAGE *trying = BuildResponse(invite, STATUS_CODE_TRYING);

    CONTACT_HEADER *inviteTo = (CONTACT_HEADER *)MessageGetHeader(HEADER_NAME_TO, invite);
    CONTACT_HEADER *tryingTo = (CONTACT_HEADER *)MessageGetHeader(HEADER_NAME_TO, trying);

    CHECK_TRUE(ContactHeaderMatched(inviteTo, tryingTo));

    DestroyMessage(&trying);
    DestroyMessage(&invite);    
}
Ejemplo n.º 17
0
TEST(TryingMessageBuildTestGroup, TryingMessageStatusLineTest)
{
    MESSAGE *invite = CreateMessage();
    ParseMessage(INCOMMING_INVITE_MESSAGE, invite);

    MESSAGE *trying = BuildResponse(invite, STATUS_CODE_TRYING);
    struct StatusLine *status = MessageGetStatusLine(trying);
    
    CHECK_TRUE(status != NULL);
    STRCMP_EQUAL(SIP_VERSION, StatusLineGetSipVersion(status));
    CHECK_EQUAL(100, StatusLineGetStatusCode(status));
    STRCMP_EQUAL("Trying", StatusLineGetReasonPhrase(status));

    DestroyMessage(&trying);
    DestroyMessage(&invite);
}
Ejemplo n.º 18
0
/** Handle as message from JavaScript on the worker thread.
 *
 * @param[in] message The message to parse and handle. */
static void HandleMessage(char* message) {
  char* function_name;
  char* params[MAX_PARAMS];
  size_t num_params;
  char* output = NULL;
  int result;
  HandleFunc function;

  num_params = ParseMessage(message, &function_name, &params[0], MAX_PARAMS);

  function = GetFunctionByName(function_name);
  if (!function) {
    /* Function name wasn't found. Error. */
    ppb_messaging_interface->PostMessage(
        g_instance, PrintfToVar("Error: Unknown function \"%s\"", function));
  }

  /* Function name was found, call it. */
  result = (*function)(num_params, &params[0], &output);
  if (result != 0) {
    /* Error. */
    struct PP_Var var;
    if (output != NULL) {
      var = PrintfToVar("Error: Function \"%s\" returned error %d. "
                        "Additional output: %s",
                        function_name,
                        result,
                        output);
      free(output);
    } else {
      var = PrintfToVar(
          "Error: Function \"%s\" returned error %d.", function_name, result);
    }

    /* Post the error to JavaScript, so the user can see it. */
    ppb_messaging_interface->PostMessage(g_instance, var);
    return;
  }

  if (output != NULL) {
    /* Function returned an output string. Send it to JavaScript. */
    ppb_messaging_interface->PostMessage(g_instance, CStrToVar(output));
    free(output);
  }
}
Ejemplo n.º 19
0
int main(int argc, char **argv) {
  char data[512];
  char host[4];
  init(argc, argv);
  
  pthread_mutex_init(&client_lock, NULL);
  
  pthread_create(&data_thread, NULL, DataSender, NULL);
  
  while (true) {
    char type;
    char client;
    int direction;
    int port;
    
    if (Listen(data))
      continue;
    ParseMessage(data, &type, &client);

    switch(type) {
    case CONNECT:
      ParseConnect(data, host, &port, &client);
      pthread_mutex_lock(&client_lock);
      DoConnect(host, port);
      pthread_mutex_unlock(&client_lock);
      break;
    case DISCONNECT:
      pthread_mutex_lock(&client_lock);
      DoDisconnect(client);
      pthread_mutex_unlock(&client_lock);
      break;
    case ENGINE:
      ParseEngine(data, &direction);
      DoEngine(client, direction);
      break;
    case TURN:
      ParseTurn(data, &direction);
      DoTurn(client, direction);
      break;
    default:
      fprintf(stderr, "Unknown message:\t%d\n", &type);
      break;
    }
  }
}
Ejemplo n.º 20
0
static void HandleMessage(char* message) {
  char* function_name;
  char* params[MAX_PARAMS];
  size_t num_params;
  char* output = NULL;
  int result;
  HandleFunc function;

  num_params = ParseMessage(message, &function_name, &params[0], MAX_PARAMS);

  function = GetFunctionByName(function_name);
  if (!function) {
    
    ppb_messaging_interface->PostMessage(
        g_instance,
        PrintfToVar("Error: Unknown function \"%s\"", function_name));
    return;
  }

  
  result = (*function)(num_params, &params[0], &output);
  if (result != 0) {
    
    struct PP_Var var;
    if (output != NULL) {
      var = PrintfToVar("Error: \"%s\" failed: %d: %s.", function_name,
                        result, output);
      free(output);
    } else {
      var = PrintfToVar(
          "Error: \"%s\" failed: %d.", function_name, result);
    }

    
    ppb_messaging_interface->PostMessage(g_instance, var);
    return;
  }

  if (output != NULL) {
    
    ppb_messaging_interface->PostMessage(g_instance, CStrToVar(output));
    free(output);
  }
}
Ejemplo n.º 21
0
int CSubscriptionMgr::RefreshMailbox(TerminalState &terminalState, vector<MsgStruct> &msgStruct)
{
	//获取请求地址
	string url = m_Interface->GetUrl();
	if (url.empty())
	{
		TEX0_LOG_ERROR("RefreshMailbox::Get server url failed, please login first");
		return TEX0_URL_EMPTY;
	}
	url.append("/action.cgi?ActionID=WEB_GetMailboxDataAPI");

	//设置请求参数
	REQUEST_OPTIONS request;
	request.strUrl = url;
	request.uiTimeOut = TIMEOUT_2S;
	request.uiVersion = VERSION_1_1;
	request.uiReqMode = MODE_POST;
	request.ReqHeader.push_back(m_Interface->GetCookie());

	//发送请求
	string rspBody;
	string rspHeader;
	int ret = eSDK_HTTP_SendRequest(request, rspBody, rspHeader);
	if (RET_OK != ret)
	{
		TEX0_LOG_ERROR("RefreshMailbox::Send http request failed, url[%s] time out[%d] http version[%d] mode[%d] data[%s], error code[%d]", 
			request.strUrl.c_str(), request.uiTimeOut, request.uiVersion, request.uiReqMode, request.strReqData.c_str(), ret);
		return TEX0_SEND_REQUEST_FAILED;
	}

	//解析响应
	bool success;
	string data;
	int id, code;
	string paras;
	ret = ParseResponse(rspBody, success, data, id, code, paras);
	if (TEX0_SUCCESS != ret)
	{
		TEX0_LOG_ERROR("RefreshMailbox::Invalid response, not json form or missing something[%s]", rspBody.c_str());
		return ret;
	}

	return success ? ParseMessage(data, terminalState, msgStruct) : code;
}
Ejemplo n.º 22
0
/**
 \brief Read feedback from 2FOC
 \pre  */
static void read_feedback(void *arg, long period)
{
    int nbytes=0;
    int n;
    FOC_data_t *focrxdata = NULL;

    // point to first axis data
    focrxdata = arg;

rmw = RD(map_MiscAddress + PMODA_OUTREG);
rmw = rmw | 0x01;
rmw = rmw & 0xFD;
WR(map_MiscAddress + PMODA_OUTREG, rmw);

    // for each FOC axis
    for (n = 0; n < num_chan; n++) {

        // procede to periodic CAN data exchange only if FOC in 'enable operation'
        if( false != FOCAxisIsOperationEnable[n] ) {
            // parse all messages (eventually) in the rx queue 
            do {
                // read data (hopefully not-blocking)
                nbytes = read (sock[n], &rxframe[n], sizeof (struct can_frame));
                if (nbytes >= 0) {
                    // parse packet type, mask away CAN address
                    if ( 0 != ParseMessage(&(rxframe[n]), n, focrxdata) ){
                        //exit(-1);
                    }
                }
            } while ( 0 < nbytes  );
        }
        // move to next axis
        focrxdata++;
    }

rmw = rmw & 0xFE;
WR(map_MiscAddress + PMODA_OUTREG, rmw);

}
Ejemplo n.º 23
0
/**
 * Handle as message from JavaScript on the worker thread.
 *
 * @param[in] message The message to parse and handle.
 */
static void HandleMessage(struct PP_Var message) {
  pp_post_message("debug", "Received a message.");

  char* command;
  struct PP_Var params;
  if (ParseMessage(message, &command, &params)) {
    pp_post_message("error", "Unable to parse message.");
    return;
  }

  if (!strcmp(command, "k2pdfopt")) {
    pp_post_message("debug", "Received k2pdfopt command.");

    int numargs = g_ppb_var_array->GetLength(params);
    int argc = numargs + 1;
    char **argv;
    argv = malloc(argc * sizeof(char*));
    argv[0] = command;

    for (int i=0; i<numargs; i++) {
      struct PP_Var argvar = g_ppb_var_array->Get(params, i);
      argv[i+1] = VarToCStr(argvar);
      g_ppb_var->Release(argvar);
    }

    pp_post_message("status", "start");
    k2pdfoptmain(numargs+1, argv);
    pp_post_message("status", "done");

    // Fre argv[1...numargs+1]; argv[0] will be freed below by calling free(command)
    for (int i=1; i<numargs+1; i++) {
      free(argv[i]);
    }
    free(argv);
  }

  free(command);
}
Ejemplo n.º 24
0
void
Client::Receive()
{
  SocketMessage msg;
  try {
    msg = FetchMessage();
  } catch (Exception& e) {
    if (e.ErrorNumber()==11000) // client has been disconnected
      throw Exception(__PRETTY_FUNCTION__, "Some other socket asked for this client's disconnection. Obtemperating...", Fatal);
  }
  if (msg.GetKey()==MASTER_DISCONNECT) {
    throw Exception(__PRETTY_FUNCTION__, "Master disconnected!", Fatal);
  }
  else if (msg.GetKey()==OTHER_CLIENT_DELETED) {
    throw Exception(__PRETTY_FUNCTION__, "Some other socket asked for this client's disconnection. Obtemperating...", Fatal);
  }
  else if (msg.GetKey()==GET_CLIENT_TYPE) {
    Send(SocketMessage(CLIENT_TYPE, static_cast<int>(GetType())));
  } 
  else if (msg.GetKey()==PING_CLIENT) {
    std::ostringstream os; os << "Pong. My name is " << GetSocketId() << " and I feel fine, thank you!";
    Send(SocketMessage(PING_ANSWER, os.str()));
    PrintInfo("Got a ping, answering...");
  } 
  else if (msg.GetKey()==CLIENTS_LIST) {
    VectorValue vals = msg.GetVectorValue();
    int i = 0; std::ostringstream o; o << "List of members on the socket:\n\t";
    for (VectorValue::const_iterator v=vals.begin(); v!=vals.end(); v++, i++) {
      if (i!=0) o << ", ";
      o << *v;
    }
    PrintInfo(o.str());
  }
  else {
    ParseMessage(msg);
  }
}
Ejemplo n.º 25
0
Boolean OSCBeProductiveWhileWaiting(void) {
    /* Here's where we could be clever if an allocation fails. 
       (I.e., if we're out of QD objects, we should avoid
       parsing bundles.) The code isn't that smart yet. */

    queuedData *qd;

    if (globals.timePassed) {
	OSCQueueScanStart(globals.TheQueue);
    }

    while (1) {
	qd = (queuedData *) OSCQueueScanNext(globals.TheQueue);
	if (qd == 0) return FALSE;

	if (qd->type == BUNDLE) {
            ParseBundle(qd);
	    OSCQueueRemoveCurrentScanItem(globals.TheQueue);
	    return TRUE;
	} else {
	    if (qd->data.message.callbacks == NOT_DISPATCHED_YET) {
                if (ParseMessage(qd) == FALSE) {
                    /* Problem with this message - flush it. */
		    DropMessage(qd->data.message.messageName,
				qd->data.message.length,
				qd->myPacket);
		    OSCQueueRemoveCurrentScanItem(globals.TheQueue);
		    PacketRemoveRef(qd->myPacket);
                    FreeQD(qd);
		}
		return TRUE;
	    }
	    /* The item we found was an already-dispatched message,
	       so continue the while loop. */
	}
    }
}
Ejemplo n.º 26
0
void ReceiveThread(int s, int recvLength)
{
	bool paskafix = true;
	char* buf = (char*)malloc(recvLength);

	recvThreadMutex.lock();

	while (1)
	{
		if (recv(s, buf, recvLength, 0) == SOCKET_ERROR)
		{
			printf("recvfrom(...) failed! Error code : %d\n", WSAGetLastError());
			recvThreadMutex.unlock();
			return;
		}
		if (paskafix)
		{
			recvThreadMutex.unlock();
			paskafix = false;
		}

		ParseMessage(buf);
	}
}
Ejemplo n.º 27
0
JaMessage CJabloDongle::ParseMessage(std::string msgstring) {
	JaMessage msg;
	std::stringstream msgstream(msgstring);
	std::string msgtok;
	int tokNum;
	bool singlePlaceTemp = false;

	if(msgstring == "\nOK\n") {
		msg.mtype = JMTYPE_OK;
	}
	else if(msgstring == "\nERROR\n") {
		msg.mtype = JMTYPE_ERR;
	}
	else if(!msgstring.compare(0, 16, "\nTURRIS DONGLE V") && (msgstring.length() > 17)) {
		msg.mtype = JMTYPE_VERSION;
		msg.version = std::string(msgstring.c_str() + 16);
		msg.version.erase(msg.version.size() - 1);
	}
	else if(!msgstring.compare(0, 6, "\nSLOT:")) {
		if(sscanf(msgstring.c_str(), "\nSLOT:%u [%u]\n", &msg.slot_num, &msg.slot_val) == 2) {
			msg.mtype = JMTYPE_SLOT;
		}
		else if(sscanf(msgstring.c_str(), "\nSLOT:%u [--------]\n", &msg.slot_num) == 1) {
			msg.mtype = JMTYPE_SLOT;
			msg.slot_val = 0;
		}
	}
	else {
		tokNum = 0;
		while(msgstream >> msgtok) {
			if(tokNum == 0) {
				if(sscanf(msgtok.c_str(), "[%u]", &msg.did) != 1)
					break;
			}
#ifdef OLDFW
			else if(tokNum == 1) {
				if(sscanf(msgtok.c_str(), "ID:%u", &msg.mid) != 1) {
					msg.mid = -1;
					if(msgtok.compare("ID:---") != 0)
						break;
				}
			}
#endif
#ifdef OLDFW
			else if(tokNum == 2) {
#else
			else if(tokNum == 1) {
#endif
				msg.devmodel = msgtok;
			}
#ifdef OLDFW
			else if(tokNum == 3) {
#else
			else if(tokNum == 2) {
#endif
				if(msgtok == "SENSOR") {
					msg.mtype = JMTYPE_SENSOR;
				}
				else if(msgtok == "TAMPER") {
					msg.mtype = JMTYPE_TAMPER;
				}
				else if(msgtok == "BEACON") {
					msg.mtype = JMTYPE_BEACON;
				}
				else if(msgtok == "BUTTON") {
					msg.mtype = JMTYPE_BUTTON;
				}
				else if(msgtok == "ARM:1") {
					msg.mtype = JMTYPE_ARM;
				}
				else if(msgtok == "ARM:0") {
					msg.mtype = JMTYPE_DISARM;
				}
				else if(sscanf(msgtok.c_str(), "SET:%f", &msg.temp) == 1) {
					msg.mtype = JMTYPE_SET;
				}
				else if(sscanf(msgtok.c_str(), "INT:%f", &msg.temp) == 1) {
					msg.mtype = JMTYPE_INT;
				}
				else if(msgtok == "SET:") {
					msg.mtype = JMTYPE_SET;
					singlePlaceTemp = true;
				}
				else if(msgtok == "INT:") {
					msg.mtype = JMTYPE_INT;
					singlePlaceTemp = true;
				}
				else {
					msg.mtype = JMTYPE_UNDEF;
				}
			}
#ifdef OLDFW
			else if((tokNum == 4) && (singlePlaceTemp == true)) {
#else
			else if((tokNum == 3) && (singlePlaceTemp == true)) {
#endif
				if(sscanf(msgtok.c_str(), "%f", &msg.temp) != 1) {
					msg.temp = 0;
					msg.mtype = JMTYPE_UNDEF;
				}						
				singlePlaceTemp = false;
			}
			else {
				if(sscanf(msgtok.c_str(), "LB:%d", &msg.lb) != 1)
					if(sscanf(msgtok.c_str(), "ACT:%d", &msg.act) != 1)
						sscanf(msgtok.c_str(), "BLACKOUT:%d", &msg.blackout);
			}

			tokNum++;
		}
	}

	return msg;
}

void CJabloDongle::ProcessMessage(JaMessage jmsg) {
	Ja_device *jdev;

	if((jmsg.mtype != JMTYPE_SLOT) && (jmsg.mtype != JMTYPE_VERSION) && (jmsg.mtype != JMTYPE_OK) && (jmsg.mtype != JMTYPE_ERR)) {
		_log.Log(LOG_STATUS, "Received message of type %s from device %d (%s)", jmsg.MtypeAsString().c_str(), jmsg.did, jmsg.devmodel.c_str());
	}

	switch(jmsg.mtype) {
		case JMTYPE_SLOT: {
			SlotReadCallback(jmsg.slot_num, jmsg.slot_val);
			readSlotsCond.notify_one();
			break;
		}
		case JMTYPE_VERSION: {
			ProbeCallback(jmsg.version);
			probeCond.notify_one();
			break;
		}
		case JMTYPE_SENSOR: {
				std::stringstream dev_desc;
				dev_desc << jmsg.devmodel << "_" << std::setfill('0') << jmsg.did << "_SENSOR";
				SendSwitch(jmsg.did, SUBSWITCH_SENSOR, (jmsg.lb == 1) ? 0 : 100, (jmsg.act == -1) ? 1 : jmsg.act, 0, dev_desc.str());
			break;
		}
		case JMTYPE_TAMPER: {
				std::stringstream dev_desc;
				dev_desc << jmsg.devmodel << "_" << std::setfill('0') << jmsg.did << "_TAMPER";
				SendSwitch(jmsg.did, SUBSWITCH_TAMPER, (jmsg.lb == 1) ? 0 : 100, (jmsg.act == -1) ? 1 : jmsg.act, 0, dev_desc.str());

			break;
		}
		case JMTYPE_BUTTON: {
				std::stringstream dev_desc;
				dev_desc << jmsg.devmodel << "_" << std::setfill('0') << jmsg.did << "_BUTTON";
				SendSwitch(jmsg.did, SUBSWITCH_BUTTON, (jmsg.lb == 1) ? 0 : 100, (jmsg.act == -1) ? 1 : jmsg.act, 0, dev_desc.str());

			break;
		}
		case JMTYPE_ARM:
		case JMTYPE_DISARM: {
				std::stringstream dev_desc;
				dev_desc << jmsg.devmodel << "_" << std::setfill('0') << jmsg.did << "_ARM";
				SendSwitch(jmsg.did, SUBSWITCH_ARM, (jmsg.lb == 1) ? 0 : 100, (jmsg.mtype == JMTYPE_ARM) ? 1 : 0, 0, dev_desc.str());

			break;
		}
		case JMTYPE_SET: {
			std::stringstream dev_desc;
			dev_desc << jmsg.devmodel << "_" << std::setfill('0') << jmsg.did << "_SET";

			SendSetPointSensor(jmsg.did, (jmsg.lb == 1) ? 0 : 100, jmsg.temp, dev_desc.str());

			break;
		}
		case JMTYPE_INT: {
			std::stringstream dev_desc;
			dev_desc << jmsg.devmodel << "_" << std::setfill('0') << jmsg.did << "_INT";
			SendTempSensor(jmsg.did, (jmsg.lb == 1) ? 0 : 100, jmsg.temp, dev_desc.str());
			break;
		}
	}
}

void CJabloDongle::ReadCallback(const char *data, size_t len)
{
	unsigned char *mf, *ml;
	unsigned char *bufptr;
	unsigned char msgline[128];
	JaMessage jmsg;
	bool messagesInBuffer;

	boost::lock_guard<boost::mutex> l(readQueueMutex);

	if (!m_bIsStarted)
		return;

	if (!m_bEnableReceive)
		return;

	//receive data to buffer
	if((m_bufferpos + len) < sizeof(m_buffer)) {
		memcpy(m_buffer + m_bufferpos, data, len);
		m_bufferpos += len;
	}
	else {
		_log.Log(LOG_STATUS, "JabloDongle: Buffer Full");
	}

	//m_buffer[m_bufferpos] = '\0';
	//_log.Log(LOG_STATUS, "Pokus received: %s", m_buffer);

	do {
		messagesInBuffer = false;
		//find sync sequence \n[
		bufptr = m_buffer;
		while((mf = (unsigned char*)strchr((const char*)bufptr, '\n')) != NULL) {
			//check if character after newline is printable character
			if((mf[1] > 32 && (mf[1] < 127)))
				break;
			bufptr = mf + 1;
		}

		//is there at least 1 whole msg in buffer?
		if((mf != NULL) && (strlen((char*)mf) > 2)) {
			ml = (unsigned char*)strchr((char*)mf + 2, '\n');
			if(ml != NULL)
				messagesInBuffer = true;
		}

		if(messagesInBuffer) {
			//copy single message into separate buffer
			memcpy(msgline, mf, ml - mf + 1);
			msgline[ml - mf + 1] = '\0';

			//shift message buffer and adjust end pointer
			memmove(m_buffer, ml + 1, m_bufferpos);
			m_bufferpos -= (ml - m_buffer) + 1;

			//process message
			//_log.Log(LOG_STATUS, "Received line %s", msgline);

			jmsg = ParseMessage(std::string((char*)msgline));

#ifdef OLDFW
			//quick and dirty hack for msg deduplication, will be removed in final version
			if((jmsg.mid == -1) && ((jmsg.mtype != last_mtype) || ((jmsg.mtype != JMTYPE_SET) && (jmsg.mtype != JMTYPE_INT)))) {
				ProcessMessage(jmsg);
				last_mtype = jmsg.mtype;
			}
			else if(jmsg.mid != last_mid) {
				ProcessMessage(jmsg);
				last_mid = jmsg.mid;
			}
#else
			ProcessMessage(jmsg);
#endif

		}
	}while(messagesInBuffer);
}

void CJabloDongle::SendTempSensor(int NodeID, const int BatteryLevel, const float temperature, const std::string &defaultname)
{
	bool bDeviceExits = true;
	std::stringstream szQuery;
	std::vector<std::vector<std::string> > result;

	NodeID &= 0xFFFF; //TEMP packet has only 2 bytes for ID.

	char szTmp[30];
	sprintf(szTmp, "%d", (unsigned int)NodeID);

	szQuery << "SELECT Name FROM DeviceStatus WHERE (HardwareID==" << m_HwdID << ") AND (DeviceID=='" << szTmp << "') AND (Type==" << int(pTypeTEMP) << ") AND (Subtype==" << int(sTypeTemperature) << ")";
	result = m_sql.query(szQuery.str());
	if (result.size() < 1)
	{
		bDeviceExits = false;
	}

	RBUF tsen;
	memset(&tsen, 0, sizeof(RBUF));
	tsen.TEMP.packetlength = sizeof(tsen.TEMP) - 1;
	tsen.TEMP.packettype = pTypeTEMP;
	tsen.TEMP.subtype = sTypeTemperature;
	tsen.TEMP.battery_level = BatteryLevel;
	tsen.TEMP.rssi = 12;
	tsen.TEMP.id1 = (NodeID & 0xFF00) >> 8;
	tsen.TEMP.id2 = NodeID & 0xFF;
	tsen.TEMP.tempsign = (temperature >= 0) ? 0 : 1;
	int at10 = round(temperature*10.0f);
	tsen.TEMP.temperatureh = (BYTE)(at10 / 256);
	at10 -= (tsen.TEMP.temperatureh * 256);
	tsen.TEMP.temperaturel = (BYTE)(at10);
	sDecodeRXMessage(this, (const unsigned char *)&tsen.TEMP);

	if (!bDeviceExits)
	{
		//Assign default name for device
		szQuery.clear();
		szQuery.str("");
		szQuery << "UPDATE DeviceStatus SET Name='" << defaultname << "' WHERE (HardwareID==" << m_HwdID << ") AND (DeviceID=='" << szTmp << "') AND (Type==" << int(pTypeTEMP) << ") AND (Subtype==" << int(sTypeTemperature) << ")";
		m_sql.query(szQuery.str());
	}
}
Ejemplo n.º 28
0
bool
DirectParser::Read (DirectMessage & msg)
{
  msg.Clear ();
  if (!bufLock.tryLock (5000)) {
    qDebug () << "WARNING: Mutex locked 5 seconds, giving up";
    return false;
  }
  QXmlStreamReader              xread (&inbuf);
  QXmlStreamReader::TokenType   tokt;
  bool finished (false);
  bool complete (false);
  bool good (false);
  bool badData (false);
  QString  topname;
  QString  bottomtag;
  QString  version;
  qint64 offset (0);
  while (!finished) {
    tokt = ReadNext (xread);
    offset = xread.characterOffset ();
    qDebug () << " Direct token " << xread.tokenString();
    switch (tokt) {
    case QXmlStreamReader::NoToken :
      qDebug () << " no token found";
      finished = true; complete = false; good = false;
      lastErr = Proto_EmptyInput;
      break;
    case QXmlStreamReader::Invalid :
      qDebug () << " bad token";
      qDebug () << " text until here: " << inbuf.buffer().left(offset);
    
      finished = true; complete = false; good = false;
      lastErr = Proto_BadTag;
      badData = true;
      break;
    case QXmlStreamReader::StartElement:
      topname = xread.name().toString().toLower();
      if (topname == oldTopTag) {
        ParseOld (xread, msg, offset, complete, good);
        msg.SetAttribute ("version","0.1");
      } else if (topname == topTag) {
        version = xread.documentVersion ().toString();
        msg.SetAttribute ("version",version);
        ParseMessage (xread, msg, offset, complete, good);
      } else {
qDebug () << " topname unknown: " << topname;
        finished = true;  complete = false; good = false;
        lastErr = Proto_WrongProtocol;
      }
      break;
    case QXmlStreamReader::EndElement:
      bottomtag = xread.name().toString().toLower();
      if (bottomtag == topname) {
        finished = true;
      }
      break;
    case QXmlStreamReader::EndDocument :
      finished = true;
      break;
    case QXmlStreamReader::Characters:
      break;
    case QXmlStreamReader::StartDocument:
    case QXmlStreamReader::Comment:
    case QXmlStreamReader::DTD:
    case QXmlStreamReader::EntityReference:
    case QXmlStreamReader::ProcessingInstruction:
      break;
    default:
      qDebug () << " unknown token type " << tokt;
      lastErr = Proto_Unknown;
      finished = true; complete = false; good = false;
      break;
    }
  }
    if (good && complete) {
    /// we have consumed a message, so get rid of the raw data
    /// so we can read the next message next time   
    qDebug () << " trailing token " << xread.tokenString ();
    while (!xread.atEnd() && xread.tokenType() != QXmlStreamReader::EndDocument) {
      xread.readNext();
      qDebug () << " consumed " << xread.tokenString ();
    }
    qDebug () << " remove " << offset << " bytes from buffer: ";
    qDebug () << inbuf.buffer().left(offset);
    inbuf.buffer().remove (0,offset+1);
    inbuf.seek (0);
  } else {
    msg.Clear ();
  }
  qDebug () << " after DirectParser::Read buffer has [[" << inbuf.buffer() << "]]";
  qDebug () << " token " << xread.tokenString() << " error " << xread.error();
  if (!good) {
    if (xread.error () == QXmlStreamReader::PrematureEndOfDocumentError) {
      complete = false;
      good = true;
    }
  }
  lastComplete = complete;
  lastGood = good;
  bufLock.unlock ();
  return good && complete;
}
Ejemplo n.º 29
0
bool Talk::ParseIMMessage(const std::string& json_msg, IMMessage& msg)
{
	return ParseMessage(json_msg, msg);
}
Ejemplo n.º 30
0
Boolean OSCInvokeMessagesThatAreReady(OSCTimeTag now) {
    queuedData *x;
    OSCTimeTag thisTimeTag;

    globals.lastTimeTag = now;
    globals.timePassed = TRUE;

    thisTimeTag = OSCQueueEarliestTimeTag(globals.TheQueue);

    if (OSCTT_Compare(thisTimeTag, now) > 0) {
	/* No messages ready yet. */
	return FALSE;
    }

#ifdef DEBUG
    printf("OSCInvokeMessagesThatAreReady(%llx) - yes, some are ready; earliest %llx\n", now, thisTimeTag);
#endif

    while (OSCTT_Compare(thisTimeTag, OSCQueueEarliestTimeTag(globals.TheQueue)) == 0) {
	x = (queuedData *) OSCQueueRemoveEarliest(globals.TheQueue);

#ifdef DEBUG
	printf("...Just removed earliest entry from queue: %p, TT %llx, %s\n",
	       x, x->timetag, x->type == MESSAGE ? "message" : "bundle");
	if (x->type == MESSAGE) {
	    printf("...message %s, len %d, args %p, arglen %d, callbacks %p\n",
		   x->data.message.messageName, x->data.message.length, x->data.message.args,
		   x->data.message.argLength, x->data.message.callbacks);
	} else {
	    if (x->data.bundle.length == 0) {
		printf("...bundle is empty.\n");
	    } else {
		printf("...bundle len %d, first count %d, first msg %s\n",
		       x->data.bundle.length, *((int *) x->data.bundle.bytes), x->data.bundle.bytes+4);
	    }
	}
	PrintPacket(x->myPacket);
#endif

	if (x->type == BUNDLE) {
	    ParseBundle(x);
	} else {
	    if (x->data.message.callbacks == NOT_DISPATCHED_YET) {
		if (ParseMessage(x) == FALSE) {
		    /* Problem with this message - flush it. */
		    PacketRemoveRef(x->myPacket);
		    FreeQD(x);
		    continue;
		}
	    }

	    CallWholeCallbackList(x->data.message.callbacks,
				  x->data.message.argLength,
				  x->data.message.args, 
				  thisTimeTag,
				  x->myPacket->returnAddrOK ? x->myPacket->returnAddr : 0);

	    PacketRemoveRef(x->myPacket);
	    FreeQD(x);
	}
    }


#ifdef PARANOID
    if (OSCTT_Compare(thisTimeTag, OSCQueueEarliestTimeTag(globals.TheQueue)) > 0) {
	fatal_error("OSCInvokeMessagesThatAreReady: corrupt queue!\n"
		    "  just did %llx; earliest in queue is now %llx",
		    thisTimeTag, OSCQueueEarliestTimeTag(globals.TheQueue));
    }
#endif

    return OSCTT_Compare(OSCQueueEarliestTimeTag(globals.TheQueue), now) <= 0;
}