Beispiel #1
0
int psoaConnect( psoaConnector    * pConnector,
                 const char       * address,
                 struct qsrOutput * pAnswer,
                 psocErrorHandler * errorHandler )
{
   int errcode = 0;
   unsigned short port;
   struct sockaddr_in addr;
   long int dummy = 0;
#if defined (WIN32) 
   WORD versionRequested;
   WSADATA wsaData;
#endif
   struct qsrInput input;

   PSO_PRE_CONDITION( pConnector   != NULL );
   PSO_PRE_CONDITION( address      != NULL );
   PSO_PRE_CONDITION( pAnswer      != NULL );
   PSO_PRE_CONDITION( errorHandler != NULL );
   
   pConnector->socketFD = PSO_INVALID_SOCKET;
#if defined (WIN32)
   pConnector->cleanupNeeded = false;
#endif

   dummy = strtol( address, NULL, 10 );
   if ( dummy <= 0 || dummy > 65535 ) return PSO_INVALID_QUASAR_ADDRESS;
   port = (unsigned short) dummy;

#if defined (WIN32) 
   versionRequested = MAKEWORD( 2, 2 );
 
   errcode = WSAStartup( versionRequested, &wsaData );
   if ( errcode != 0 ) {
      psocSetError( errorHandler, PSOC_SOCKERR_HANDLE, WSAGetLastError() );
      return PSO_SOCKET_ERROR;
   }
   pConnector->cleanupNeeded = true;   
#endif

   pConnector->socketFD = socket( PF_INET, SOCK_STREAM, 0 );
   if ( pConnector->socketFD == PSO_INVALID_SOCKET ) {
#if defined (WIN32) 
      psocSetError( errorHandler, PSOC_SOCKERR_HANDLE, WSAGetLastError() );
#else
      psocSetError( errorHandler, PSOC_ERRNO_HANDLE, errno );
#endif
      return PSO_SOCKET_ERROR;
   }
   
   memset( &addr, 0, sizeof(struct sockaddr_in) );
   addr.sin_family = PF_INET;
   addr.sin_port = htons( port );
   addr.sin_addr.s_addr = inet_addr( "127.0.0.1" );

   errcode = connect( pConnector->socketFD, 
                      (const struct sockaddr *)&addr,
                      sizeof addr );
   if ( errcode != 0 ) {
#if defined (WIN32) 
      psocSetError( errorHandler, PSOC_SOCKERR_HANDLE, WSAGetLastError() );
#else
      psocSetError( errorHandler, PSOC_ERRNO_HANDLE, errno );
#endif
      return PSO_CONNECT_ERROR;
   }

   input.opcode = QSR_CONNECT;
   input.processId = getpid();

   errcode = Send( pConnector, &input, sizeof(struct qsrInput), errorHandler );
   if ( errcode != 0 ) return PSO_SEND_ERROR;

   errcode = Receive( pConnector, pAnswer, sizeof(struct qsrOutput), errorHandler );
   if ( errcode != 0 ) return PSO_RECEIVE_ERROR;

   return 0;
}
Beispiel #2
0
void handle_connection (Connection con, const char *peer, const char *now)
{
  char tmps[33];
  unsigned char mdc[16];
  unsigned long tmp;
  int genexp = 1;
  longnum y;
  struct message in, out;
  int l;
  struct timeval t;
  struct tms t_times;

  out.type = SC_Modulus;
  memcpy (&out.body.sc_modulus.n, &n, sizeof(n));
  fprintf (stderr, "-> %s: SC_Modulus\n", peer);
  fflush (stderr);
  Transmit (con, &out, sizeof (out));
  while (1) {
    if ((l=Receive (con, &in, sizeof (in))) != sizeof (in)) {
      if (! l) {
        fprintf (stderr, "<- %s: connection closed\n", peer);
      } else {
        fprintf (stderr, "<- %s: receive %d instead of %lu\n", peer, l, sizeof(in));
      }
      fflush (stderr);
      return;
    }
    if (genexp) {
      MD5_CTX c;
      fprintf (stderr, "-- %s: Generating new exponent\n", peer);
      fflush (stderr);

      /* XXX Zufaelligen Exponenten erzeugen ... */

      genexp = 0;
    }
    switch (in.type) {
    case CS_Exp:
      /* fprintf (stderr, "<- %s: CS_Exp\n", peer); */
      out.body.sc_exp_r.timing =
        LITModExp (&out.body.sc_exp_r.z, &in.body.cs_exp.x, &y, &n);
      out.type = SC_ExpResp;
      break;
    case CS_Key:
      fprintf (stderr, "<- %s: CS_Key ", peer);
      memcpy (&out.body.sc_key_r.y, &y, sizeof (y));
      out.type = SC_KeyResp;
      out.body.sc_key_r.ok = ! LCompare (&y, &in.body.cs_key.y);
      if (! out.body.sc_key_r.ok) fprintf (stderr, "not ");
      fprintf (stderr, "ok\n");
      fflush (stderr);
      genexp = 1;
      break;
    default:
      fprintf (stderr, "<- %s: unknown type %d\n", peer, in.type);
      fflush (stderr);
      return;
    }
    /* fprintf (stderr, "-> %s: response\n", peer); */
    Transmit (con, &out, sizeof (out));
  }
}
void uart1_sender_notifier() {
	bwdebug( DBG_SYS, UART1_SENDER_DEBUG_AREA, "UART1_SENDER_NOTIFIER: enters" );

	int* uart_flags =	(int *)( UART1_BASE + UART_FLAG_OFFSET );
	int* uart_data =	(int *)( UART1_BASE + UART_DATA_OFFSET );
	int* modem_ctrl =	(int *)( UART1_BASE + UART_MDMCTL_OFFSET);
	int* modem_status =	(int *)( UART1_BASE + UART_MDMSTS_OFFSET);
	
	int uart_flags_temp = 0;
	int modem_ctrl_temp = 0;
	int modem_status_temp = 0;

	int sender_tid;
	UART_request request;
	
	//State machine variables
	//CTS states:
	//	0 - CTS is set to '1' before the character is sent
	//	1 - CTS is set to '0' after the character is sent
	//	2 - CTS is set to '1' after the character is sent
	int cts_state = 0;
	
	//Transmit states:
	//	0 - Transmit is set to '0' right after the character is sent
	//	1 - Transmit is set to '1' after the character is sent
	int txfe_state = 0;

	//Utility variables
	int first_request = 1;
	int first_iter = 1;

	FOREVER {
		//Get request with character from the uart1_sender_server
		bwdebug( DBG_SYS, UART1_SENDER_DEBUG_AREA, "UART1_SENDER_NOTIFIER: Waiting for request..." );
		Receive(&sender_tid, (char *) &request, sizeof(request));
		//Reply, to unblock the uart1_sender_server
		Reply(sender_tid, (char *) 0, 0);
		bwdebug( DBG_SYS, UART1_SENDER_DEBUG_AREA, "UART1_SENDER_NOTIFIER: Received send request." );

		//Reinitialize modem
		//RTSn pin is set to low
		//DTRn pin is set to low
		modem_ctrl_temp = *modem_ctrl;
		*modem_ctrl = modem_ctrl_temp | 3;

		//Initialize the state machine
		cts_state = 0;
		txfe_state = 0;
		first_iter = 1;
		
		FOREVER {
			//*uart_data = 'b';
			//Wait until UART1 is ready to receive a character
			if(txfe_state == 0 || first_iter) {
				bwdebug( DBG_SYS, UART1_SENDER_DEBUG_AREA, "UART1_SENDER_NOTIFIER: Waiting for INIT event." );
				AwaitEvent(UART1_INIT_SEND, 0);
			}
			else {
				bwdebug( DBG_SYS, UART1_SENDER_DEBUG_AREA, "UART1_SENDER_NOTIFIER: Waiting for SEND READY event." );
				AwaitEvent(UART1_SEND_READY, 0);
			}

			
			//*uart_data = 'd';
			
			first_iter = 0;
			//txfe_state = 1;
			//*uart_data = 'e';
			
			modem_status_temp = *modem_status;
			uart_flags_temp = *uart_flags;

			//Changing state of the state machine////////////////////
			// bwprintf( COM2, "STATE00: CTS: %d TXFE: %d\n", cts_state, txfe_state );
			
			//IF   CTS value has changed
			//AND  CTS value is now set to '1'
			//THEN CTS has been reasserted
			if( ((modem_status_temp & DCTS_MASK) || first_request)
				&& (uart_flags_temp & CTS_MASK)) {
				cts_state = 2;
				// bwprintf( COM2, "STATE03: CTS: %d TXFE: %d\n", cts_state, txfe_state );
			}
			
			//IF   CTS value is set to '0'
			//THEN CTS has been deasserted
			if( cts_state == 0 && !(uart_flags_temp & CTS_MASK) ) {
				cts_state = 1;
				// bwprintf( COM2, "STATE02: CTS: %d TXFE: %d\n", cts_state, txfe_state );
			}
			
			

			//IF   CTS has been deasserted
			//AND  CTS value is now set to '1'
			//THEN CTS has been reasserted
			if( cts_state == 1 && (uart_flags_temp & CTS_MASK) ) {
				cts_state = 2;
				// bwprintf( COM2, "STATE04: CTS: %d TXFE: %d\n", cts_state, txfe_state );
			}
			
			//IF transmit is set to '1'
			if( (uart_flags_temp & TXFE_MASK) ) {
				txfe_state = 1;
				// bwprintf( COM2, "STATE01: CTS: %d TXFE: %d\n", cts_state, txfe_state );
			}
			
			//IF   CTS has been reasserted
			//AND  Transmit has been reasserted
			//THEN Send the character to UART1
			if( cts_state == 2 && txfe_state == 1 ) {
				*uart_data = (char) request.ch;
				first_request = 0;
				bwdebug( DBG_SYS, UART1_SENDER_DEBUG_AREA, "UART1_SENDER_NOTIFIER: Sending data" );
				break;
			}
		}
	}
}
void USCI_SLAVE_SETUP(void){
  P3SEL |= 0x06;                            // Assign I2C pins to USCI_B0
  Setup_RX();
  Receive();
}
Beispiel #5
0
	bool TcpClient::ReceivePacket(NetPacket* packet)
	{
		//TODO: Every packet requires at least two Receive call, using an internal buffer of a fixed size would prevent this
		NazaraAssert(packet, "Invalid packet");

		if (!m_pendingPacket.headerReceived)
		{
			m_pendingPacket.data.Resize(NetPacket::HeaderSize);

			std::size_t received;
			if (!Receive(&m_pendingPacket.data[m_pendingPacket.received], NetPacket::HeaderSize - m_pendingPacket.received, &received))
				return false;

			m_pendingPacket.received += received;

			//TODO: Should never happen in production !
			NazaraAssert(m_pendingPacket.received <= NetPacket::HeaderSize, "Received more data than header size");
			if (m_pendingPacket.received >= NetPacket::HeaderSize)
			{
				UInt16 size;
				if (!NetPacket::DecodeHeader(m_pendingPacket.data.GetConstBuffer(), &size, &m_pendingPacket.netcode))
				{
					m_lastError = SocketError_Packet;
					NazaraWarning("Invalid header data");
					return false;
				}

				m_pendingPacket.data.Resize(size - NetPacket::HeaderSize);
				m_pendingPacket.headerReceived = true;
				m_pendingPacket.received = 0;
			}
		}

		// We may have just received the header now
		if (m_pendingPacket.headerReceived)
		{
			UInt16 packetSize = static_cast<UInt16>(m_pendingPacket.data.GetSize()); //< Total packet size
			if (packetSize == 0)
			{
				// Special case: our packet carry no data
				packet->Reset(m_pendingPacket.netcode);

				// And reset every state
				m_pendingPacket.data.Clear();
				m_pendingPacket.headerReceived = false;
				m_pendingPacket.received = 0;
				return true;
			}

			std::size_t received;
			if (!Receive(&m_pendingPacket.data[m_pendingPacket.received], packetSize - m_pendingPacket.received, &received))
				return false;

			m_pendingPacket.received += received;

			//TODO: Should never happen in production !
			NazaraAssert(m_pendingPacket.received <= packetSize, "Received more data than packet size");
			if (m_pendingPacket.received >= packetSize)
			{
				// Okay we received the whole packet, copy it
				packet->Reset(m_pendingPacket.netcode, m_pendingPacket.data.GetConstBuffer(), m_pendingPacket.data.GetSize());

				// And reset every state
				m_pendingPacket.data.Clear();
				m_pendingPacket.headerReceived = false;
				m_pendingPacket.received = 0;
				return true;
			}
		}

		return false;
	}
Beispiel #6
0
void PipeReader::Pump()
{
    char    buf[PUMP_BUFFER_SIZE];
    bool    pljtmpOnce = 0;

    connected = true;

    while (g_shutdown == false)
    {
        int received = 0;
        int sent = 0;

        if (!wait.read)
        {
            //
            // If there's room in the recieve buffer, attempt to receive
            // some.

            int receivable = receiveBuffer.QueryInsertable();

            if (receivable != 0)
            {
                if ((received = Receive(buf, receivable)) != 0)
                {
                    if (receiveDataSeen == false)
                    {
                        printf("pipe connected.\n");
                        log->Log(TAG_READ_DBG, tag, "Recieve data from debugger.\n");
                        receiveDataSeen = true;
                    }
                    log->Log(TAG_READ, tag, received, buf);
                    if (sender->Connected() == false)
                    {
                        // Ignore all incoming data until there is something
                        // connected to send it to.
                        printf("pipereader: dropping %d bytes because socket is not connected.\n",
                                received);
                        log->Log(TAG_READ_DBG, tag,
                                "dropping %d bytes because socket is not connected.\n",
                                received);
                        received = 0;
                    }
                    if (resetAckExpected)
                    {
                        // Ignore all incoming data until the other side tells
                        // us a reset ack has been seen.
                        log->Log(TAG_READ_DBG, tag,
                                "dropping %d bytes, waiting for reset ack from target.\n",
                                received);
                        received = 0;
                    }

                    int count = CheckForResetPacket(buf, received);
                    if (count != 0)
                    {
                        log->Log(TAG_READ_DBG, tag, "RESET packet received.\n");
                        if (!resetAckExpected)
                        {
                            printf("debugger sent RESET.\n");
                        }
                        // Truncate received data to end of reset packet.  We
                        // discard all remaining data until we see a reset ack
                        // from the other end.  Note: On send the reset packet
                        // is usually followed by 8 bytes of zero, the target
                        // seems to depend on it ... and being as we truncated
                        // and we don't know we got them all yet anyway and we
                        // will drop all further data until we see something,
                        // better send the zeros along.
                        receiveBuffer.Insert(buf, count);
                        int z = 0;
                        receiveBuffer.Insert((char *)&z, sizeof(z));
                        receiveBuffer.Insert((char *)&z, sizeof(z));
                        received = 0;
                        SetResetAckExpected(true);
                    }
                    receiveBuffer.Insert(buf, received);
                }
            }
        }

        if (!wait.write)
        {
            //
            // Attempt to send. 
            //
            // Note: The Send routine will take care of the no data case.
            //

            sent = sender->Send(&receiveBuffer);
        }

        if (!(sent | received))
        {
            //
            // Nothing sent, nothing received, wait until something happens
            // on one end or the other.
            //

            Wait();
        }
    }
    connected = false;
}
Beispiel #7
0
void COAK10Socket::OnReceive(int nErrorCode) 
{
	CHiddenWnd* pWnd = (CHiddenWnd*)AfxGetApp()->m_pMainWnd;
	CString s;
	INT iCRAt, iReceived, iLen;
	DWORD dwCurrentTicks, dwDiff;
	bool bPostPacket;
	
	iReceived = Receive(&m_cIncomingBuffer[m_iBufferLength],m_iBufferMaxLength - m_iBufferLength);
	m_iBufferLength += iReceived;
	s = m_cIncomingBuffer;
	iCRAt = s.Find(13);
	while (iCRAt != -1)
	{
		s = s.Left(iCRAt + 1);
		iLen = s.GetLength();
		m_iBufferLength -= iLen;
		memcpy(&m_cIncomingBuffer[0],&m_cIncomingBuffer[iLen],m_iBufferLength);
		memset(&m_cIncomingBuffer[m_iBufferLength],0,m_iBufferMaxLength - m_iBufferLength);
		dwCurrentTicks = ::GetTickCount();
		if (dwCurrentTicks < m_dwLastPacketReceive)
		{	// ticks have turned over so reverse the math
			dwDiff = m_dwLastPacketReceive - dwCurrentTicks;
		}
		else
		{
			dwDiff = dwCurrentTicks - m_dwLastPacketReceive;
		}
		if (dwDiff >= m_dwMinimumPacketInterval)
		{
			bPostPacket = true;
		}
		else
		{
			bPostPacket = false;
			if (m_pOwner)
			{
				DebugTell("COAK10Socket::OnReceive: data skipped from %d:%s,%d at %s:%d...",
					m_pOwner->m_nRoomId,m_pOwner->m_sRoomName,m_pOwner->m_nCardReaderId,
					m_pOwner->m_sAddress, m_pOwner->m_usPort);
				DebugTell("\tskipped data: %s",s);
			}
			else
			{
				DebugTell("COAK10Socket::OnReceive: data skipped from UNKNOWN: %s",s);
			}
		}
		if (bPostPacket)
		{
			pWnd->PostMessage(UDS_MESSAGE,(WPARAM)_strdup((LPCTSTR)s),(LPARAM)m_nCardReaderId);
		}
		m_dwLastPacketReceive = dwCurrentTicks;

		s = m_cIncomingBuffer;
		iCRAt = s.Find(13);
	}
/*
	if (iCRAt != -1)
	{
		s = s.Left(iCRAt + 1);
		iLen = s.GetLength();
		m_iBufferLength -= iLen;
		memcpy(&m_cIncomingBuffer[0],&m_cIncomingBuffer[iLen],m_iBufferLength);
		memset(&m_cIncomingBuffer[m_iBufferLength],0,m_iBufferMaxLength - m_iBufferLength);
		pWnd->PostMessage(UDS_MESSAGE,(WPARAM)_strdup((LPCTSTR)s),(LPARAM)m_nCardReaderId);
	}
*/
	//CCardReaderSocket::OnReceive(nErrorCode);
	UNREFERENCED_PARAMETER(nErrorCode);
}
void genResponse(int cid) {
    int power = motor[motorA];
    float temp = 0.0;
    string tmpString;
    int index = 0;
    ubyte linebuff[20];
    StringFromChars(tmpString,rxbuffer);
    index = StringFind(tmpString, "/");
    StringDelete(tmpString, 0, index);
    index = StringFind(tmpString, "HTTP");
    StringDelete(tmpString, index, strlen(tmpString));
    writeDebugStreamLine("Request:%s", tmpString);
    nxtDisplayTextLine(2, "Request: ");
    nxtDisplayTextLine(3, tmpString);
    if (StringFind(tmpString, "MOTA") > 0) {
        StringDelete(tmpString, 0, 6);
        index = StringFind(tmpString, " ");
        if (index > -1)
            StringDelete(tmpString, index, strlen(tmpString));
        //power = RC_atoix(tmpString);
        power = clip(atoi(tmpString), -100, 100);
        writeDebugStreamLine("Power:%d", power);
    } else {
        writeDebugStreamLine("NO POWER: %s", tmpString);
    }

    sendHeader(cid);
    while(nxtHS_Status == HS_SENDING) wait1Msec(5);

    wait1Msec(100);

    index = 0;
    linebuff[0] = 27; // escape;
    linebuff[1] = 'S'; // the CID;
    linebuff[2] = (ubyte)cid + 48; // the CID;
    index = appendToBuff(buffer, index, linebuff, 3);
    StringFormat(tmpString, "MotorA=%d\n", power);
    memcpy(linebuff, tmpString, strlen(tmpString));
    index = appendToBuff(buffer, index, linebuff, strlen(tmpString));
    DTMPreadTemp(DTMP, temp);
    StringFormat(tmpString, "Temp: %2.2f C", temp);
    memcpy(linebuff, tmpString, strlen(tmpString));
    index = appendToBuff(buffer, index, linebuff, strlen(tmpString));
    linebuff[0] = 27; // escape;
    linebuff[1] = 'E'; // the CID;
    index = appendToBuff(buffer, index, endmarker, 2);
    writeRawHS(buffer, index);
    if (power != 0) nMotorEncoderTarget[motorA] = 2000;
    motor[motorA] = power;
    if (power > 0)
        SensorType[COLOUR] = sensorCOLORGREEN;
    else if (power < 0)
        SensorType[COLOUR] = sensorCOLORBLUE;
    else if (nMotorRunState[motorA] == runStateIdle)
        SensorType[COLOUR] = sensorCOLORRED;
    else
        SensorType[COLOUR] = sensorCOLORRED;
    wait1Msec(300);
    clear_read_buffer();
    closeConn(1);
    memset(rxbuffer, 0, sizeof(rxbuffer));
    //wait1Msec(100);
    Receive();
    //clear_read_buffer();
}
void SocketsToSDL::RunThread()
{
#ifdef WIN32
    FD_SET fdRead;
    int fd_max = -1;
#else
    fd_set fdRead;
    fd_set fdWrite;
    int fd_max = m_Read_Sign;
#endif
	while (!m_bTerminate)
	{
		FD_ZERO(&fdRead);
#ifndef WIN32
		FD_ZERO(&fdWrite);
#endif

		int iNum = m_SocketHandles.size();
        for (int i = 0; i < iNum; i++)
		{
			SOCK_HANDLE * pHandle = m_SocketHandles[i];
			int socket = pHandle->socket;
			FD_SET(socket, &fdRead);
#ifndef WIN32
			FD_SET(socket, &fdWrite);
#endif
            fd_max = fd_max > socket? fd_max : socket;
		}
		FD_SET(m_Read_Sign, &fdRead);

#ifdef WIN32
        if (select(0, &fdRead, NULL, NULL, NULL) == SOCKET_ERROR)
#else
        if (select(fd_max+1, &fdRead, &fdWrite, NULL, NULL) == SOCKET_ERROR)
#endif
		{
            goto SOCKET_WRONG;
		}

        bool bSend = FD_ISSET(m_Read_Sign, &fdRead);
		if (bSend)
		{
			unsigned char buffer[8];
			int bytes_read = 0;
			do
			{
				bytes_read = recv(m_Read_Sign, (char *)buffer, sizeof(buffer), 0);
			} while (bytes_read > 0);
            for (int i = 0; i < iNum; i++)
            {
                SOCK_HANDLE * pHandle = m_SocketHandles[i];
                if(!Send(pHandle))
                    goto SOCKET_WRONG;
            }
		}

        for (int i = 0; i < iNum; i++)
		{
			SOCK_HANDLE * pHandle = m_SocketHandles[i];
			if (FD_ISSET(pHandle->socket, &fdRead))
			{
                if(!Receive(pHandle))
                    goto SOCKET_WRONG;
            }
		}
	}
    return;

SOCKET_WRONG:
    m_bTerminate = true;
    CloseSockets();

    if(m_pNetwork)
        m_pNetwork->onNetworkBroken();
    return;
}
void Debug_glDrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices)
{
    DbgContext * const dbg = getDbgContextThreadSpecific();
    glesv2debugger::Message msg, cmd;
    msg.set_context_id(reinterpret_cast<int>(dbg));
    msg.set_type(glesv2debugger::Message_Type_BeforeCall);
    bool expectResponse = dbg->expectResponse.Bit(glesv2debugger::Message_Function_glDrawElements);
    msg.set_expect_response(expectResponse);
    msg.set_function(glesv2debugger::Message_Function_glDrawElements);
    msg.set_arg0(mode);
    msg.set_arg1(count);
    msg.set_arg2(type);
    msg.set_arg3(reinterpret_cast<int>(indices));

    msg.set_arg7(dbg->maxAttrib); // indicate capturing vertex data
    std::string * const data = msg.mutable_data();
    if (GL_UNSIGNED_BYTE == type) {
        if (dbg->indexBuffer) {
            FetchIndexed(count, (unsigned char *)dbg->indexBuffer->data +
                         (unsigned long)indices, data, dbg);
        } else {
            FetchIndexed(count, (unsigned char *)indices, data, dbg);
        }
    } else if (GL_UNSIGNED_SHORT == type) {
        if (dbg->indexBuffer) {
            FetchIndexed(count, (unsigned short *)((char *)dbg->indexBuffer->data +
                                                   (unsigned long)indices), data, dbg);
        } else {
            FetchIndexed(count, (unsigned short *)indices, data, dbg);
        }
    } else {
        assert(0);
    }

    void * pixels = NULL;
    int viewport[4] = {};
    cmd.set_function(glesv2debugger::Message_Function_CONTINUE);
    cmd.set_expect_response(expectResponse);
    glesv2debugger::Message_Function oldCmd = cmd.function();
    Send(msg, cmd);
    expectResponse = cmd.expect_response();
    while (true) {
        msg.Clear();
        nsecs_t c0 = systemTime(timeMode);
        switch (cmd.function()) {
        case glesv2debugger::Message_Function_CONTINUE:
            dbg->hooks->gl.glDrawElements(mode, count, type, indices);
            msg.set_time((systemTime(timeMode) - c0) * 1e-6f);
            msg.set_context_id(reinterpret_cast<int>(dbg));
            msg.set_function(glesv2debugger::Message_Function_glDrawElements);
            msg.set_type(glesv2debugger::Message_Type_AfterCall);
            msg.set_expect_response(expectResponse);
            if (!expectResponse) {
                cmd.set_function(glesv2debugger::Message_Function_SKIP);
                cmd.set_expect_response(false);
            }
            oldCmd = cmd.function();
            Send(msg, cmd);
            expectResponse = cmd.expect_response();
            // TODO: pack glReadPixels data with vertex data instead of
            //  relying on separate call for transport, this would allow
            //  auto generated message loop using EXTEND_Debug macro
            if (dbg->captureDraw > 0) {
                dbg->captureDraw--;
                dbg->hooks->gl.glGetIntegerv(GL_VIEWPORT, viewport);
                pixels = dbg->GetReadPixelsBuffer(viewport[2] * viewport[3] *
                                                  dbg->readBytesPerPixel);
                Debug_glReadPixels(viewport[0], viewport[1], viewport[2], viewport[3],
                        GL_RGBA, GL_UNSIGNED_BYTE, pixels);
            }
            break;
        case glesv2debugger::Message_Function_SKIP:
            return;
        case glesv2debugger::Message_Function_SETPROP:
            SetProp(dbg, cmd);
            expectResponse = cmd.expect_response();
            if (!expectResponse) // SETPROP is "out of band"
                cmd.set_function(oldCmd);
            else
                Receive(cmd);
            break;
        default:
            GenerateCall(dbg, cmd, msg, NULL);
            msg.set_expect_response(expectResponse);
            if (!expectResponse) {
                cmd.set_function(cmd.SKIP);
                cmd.set_expect_response(expectResponse);
            }
            oldCmd = cmd.function();
            Send(msg, cmd);
            expectResponse = cmd.expect_response();
            break;
        }
    }
}
void Debug_glDrawArrays(GLenum mode, GLint first, GLsizei count)
{
    DbgContext * const dbg = getDbgContextThreadSpecific();
    glesv2debugger::Message msg, cmd;
    msg.set_context_id(reinterpret_cast<int>(dbg));
    msg.set_type(glesv2debugger::Message_Type_BeforeCall);
    bool expectResponse = dbg->expectResponse.Bit(glesv2debugger::Message_Function_glDrawArrays);
    msg.set_expect_response(expectResponse);
    msg.set_function(glesv2debugger::Message_Function_glDrawArrays);
    msg.set_arg0(mode);
    msg.set_arg1(first);
    msg.set_arg2(count);

    msg.set_arg7(dbg->maxAttrib); // indicate capturing vertex data
    if (dbg->hasNonVBOAttribs) {
        std::string * const data = msg.mutable_data();
        for (unsigned i = 0; i < count; i++)
            dbg->Fetch(i + first, data);
    }

    void * pixels = NULL;
    int viewport[4] = {};
    cmd.set_function(glesv2debugger::Message_Function_CONTINUE);
    cmd.set_expect_response(expectResponse);
    glesv2debugger::Message_Function oldCmd = cmd.function();
    Send(msg, cmd);
    expectResponse = cmd.expect_response();
    while (true) {
        msg.Clear();
        nsecs_t c0 = systemTime(timeMode);
        switch (cmd.function()) {
        case glesv2debugger::Message_Function_CONTINUE:
            dbg->hooks->gl.glDrawArrays(mode, first, count);
            msg.set_time((systemTime(timeMode) - c0) * 1e-6f);
            msg.set_context_id(reinterpret_cast<int>(dbg));
            msg.set_function(glesv2debugger::Message_Function_glDrawArrays);
            msg.set_type(glesv2debugger::Message_Type_AfterCall);
            msg.set_expect_response(expectResponse);
            if (!expectResponse) {
                cmd.set_function(glesv2debugger::Message_Function_SKIP);
                cmd.set_expect_response(false);
            }
            oldCmd = cmd.function();
            Send(msg, cmd);
            expectResponse = cmd.expect_response();
            // TODO: pack glReadPixels data with vertex data instead of
            //  relying on sperate call for transport, this would allow
            //  auto generated message loop using EXTEND_Debug macro
            if (dbg->captureDraw > 0) {
                dbg->captureDraw--;
                dbg->hooks->gl.glGetIntegerv(GL_VIEWPORT, viewport);
//                ALOGD("glDrawArrays CAPTURE: x=%d y=%d width=%d height=%d format=0x%.4X type=0x%.4X",
//                     viewport[0], viewport[1], viewport[2], viewport[3], readFormat, readType);
                pixels = dbg->GetReadPixelsBuffer(viewport[2] * viewport[3] *
                                                  dbg->readBytesPerPixel);
                Debug_glReadPixels(viewport[0], viewport[1], viewport[2], viewport[3],
                        GL_RGBA, GL_UNSIGNED_BYTE, pixels);
            }
            break;
        case glesv2debugger::Message_Function_SKIP:
            return;
        case glesv2debugger::Message_Function_SETPROP:
            SetProp(dbg, cmd);
            expectResponse = cmd.expect_response();
            if (!expectResponse) // SETPROP is "out of band"
                cmd.set_function(oldCmd);
            else
                Receive(cmd);
            break;
        default:
            GenerateCall(dbg, cmd, msg, NULL);
            msg.set_expect_response(expectResponse);
            if (!expectResponse) {
                cmd.set_function(cmd.SKIP);
                cmd.set_expect_response(expectResponse);
            }
            oldCmd = cmd.function();
            Send(msg, cmd);
            expectResponse = cmd.expect_response();
            break;
        }
    }
}
void SocketConnection::WaitForClient() {
    uint8_t junk[1];
    Receive(junk, 1);
}
Beispiel #13
0
int main()
{

int j;
Message msg;

//Echo(strcat("b,SDRAM,",itoa(GetTick())));


	for(j=0;j<128;j++) msg.msg[j]=j;

	/*Comm BAB 1280*/
	msg.length=128;
	for(j=0;j<10;j++) Send(&msg,BAB_0);
	//Echo(strcat("s,MPEG_m6(1280),",itoa(GetTick())));
	/*Comm BAB 1280*/
	msg.length=128;
	for(j=0;j<10;j++) Receive(&msg,BAB_0);
	//Echo(strcat("r,MPEG_m8(1280),",itoa(GetTick())));
	/*Comm UPSAMP 15000*/
	msg.length=128;
	for(j=0;j<117;j++)
	{
		//Echo("SEND upsamp antes\n");
		Send(&msg,UPSAMP_0);
		//Echo("SEND upsamp depois\n");
	}
	msg.length=24;
	Send(&msg,UPSAMP_0);
	//Echo(strcat("s,MPEG_m9(15000),",itoa(GetTick())));
	/*Comm UPSAMP 15000*/
	msg.length=128;
	for(j=0;j<117;j++)
	{
		//Echo("receive upsamp antes\n");
		Receive(&msg,UPSAMP_0);
		//Echo("receive upsamp depois\n");
	}
	msg.length=24;
	Receive(&msg,UPSAMP_0);
	//Echo(strcat("r,MPEG_m10(15000),",itoa(GetTick())));
	/*Comm ADSP 1280*/
	msg.length=128;
	for(j=0;j<10;j++) Send(&msg,ADSP_0);
	//Echo(strcat("s,MPEG_m11(1280),",itoa(GetTick())));
	/*Comm MCPU 1280*/
	msg.length=128;
	for(j=0;j<10;j++) Send(&msg,MCPU_0);
	//Echo(strcat("s,MPEG_m12(1280),",itoa(GetTick())));
	/*Comm ADSP 1280*/
	msg.length=128;
	for(j=0;j<10;j++) Receive(&msg,ADSP_0);
	//Echo(strcat("r,MPEG_m13(1280),",itoa(GetTick())));
	/*Comm RAST 10130*/
	msg.length=128;
	for(j=0;j<79;j++) Send(&msg,RAST_0);
	msg.length=18;
	Send(&msg,RAST_0);
	//Echo(strcat("s,MPEG_m16(10130),",itoa(GetTick())));
	/*Comm RAST 10130*/
	msg.length=128;
	for(j=0;j<79;j++) Receive(&msg,RAST_0);
	msg.length=18;
	Receive(&msg,RAST_0);
	//Echo(strcat("r,MPEG_m17(10130),",itoa(GetTick())));
	/*Comm AU 1280*/
	msg.length=128;
	for(j=0;j<10;j++) Send(&msg,AU_0);
	//Echo(strcat("s,MPEG_m18(1280),",itoa(GetTick())));
	/*Comm VU 3210*/
	msg.length=128;
	for(j=0;j<25;j++) Send(&msg,VU_0);
	msg.length=10;
	Send(&msg,VU_0);
	//Echo(strcat("s,MPEG_m19(3210),",itoa(GetTick())));
	//Echo(strcat(strcat(strcat("i,",itoa(i)),","),itoa(GetTick())));

//Echo(strcat("e,SDRAM,",itoa(GetTick())));

exit();

}
void uart1_receiver_server() {
	bwdebug( DBG_SYS, UART1_RECEIVER_DEBUG_AREA, "UART1_RECEIVER_SERVER: enters" );

	//Register the server
	RegisterAs("uart1_receiver");

	//Create the notifier
	int notifier_tid = Create(UART1_RECEIVER_NOTIFIER_PRIORITY, &uart1_receiver_notifier);
	bwdebug( DBG_SYS, UART1_RECEIVER_DEBUG_AREA, 
		"UART1_RECEIVER_SERVER: uart1_receiver_server_notifier created. [tid: %d priority: %d]", 
		notifier_tid, UART1_RECEIVER_NOTIFIER_PRIORITY );
	
	//Request & Reply
	UART_request request;
	UART_reply reply;
	
	//Buffers
	Char_queue cqueue;
	init_char_queue( &cqueue );
	Int_queue iqueue;
	init_int_queue( &iqueue );

	FOREVER {
		//Utility functions for communication
		int sender_tid = -1;
		int target_tid = -1;

		//Receive request from:
		//	system function (Getc)
		//	notifier (uart1_receiver_notifier)
		//bwprintf( COM2, "A\n" );
		bwdebug( DBG_SYS, UART1_RECEIVER_DEBUG_AREA, "UART1_RECEIVER_SERVER: Waiting for request" );
		Receive(&sender_tid, (char *) &request, sizeof(request));

		switch(request.type){
			case UART1_RECEIVE_REQUEST:
				//Enqueue the system function tid to reply later
				bwdebug( DBG_SYS, UART1_RECEIVER_DEBUG_AREA, "UART1_RECEIVER_SERVER: Getc request from [sender_tid: %d]", 
					sender_tid );
				//bwprintf( COM2, "B\n" );
				enqueue_int_queue( sender_tid, &iqueue );
				break;
				
			case UART1_RECEIVE_NOTIFIER_REQUEST:
				//Reply to unblock the notifier
				bwdebug( DBG_SYS, UART1_RECEIVER_DEBUG_AREA, "UART1_RECEIVER_SERVER: message received from notifier" );
				//bwprintf( COM2, "C\n" );
				Reply(sender_tid, (char *) 0, 0);

				//Enqueue received character
				//if ( iqueue.size > 0 ){
					//todo_debug( 0x7, 1 );
					char_queue_push( request.ch, &cqueue );
					//todo_debug( 0x8, 1 );
				//}

				break;
			
			default:
				// Invalid Request
				bwdebug( DBG_SYS, UART1_RECEIVER_DEBUG_AREA, "UART1_RECEIVER_SERVER: invalid request from [sender_tid: %d]", 
					sender_tid );
				//bwprintf( COM2, "D\n" );
				reply.type = INVALID_REQUEST;
				reply.ch = 0;
				Reply(sender_tid, (char *) &reply, sizeof(reply));
				break;
		}

		//If there are system functions to receive
		//and characters to be sent
		while(iqueue.size > 0 && cqueue.size > 0) {
			//Prepare the reply to the system function
			target_tid = dequeue_int_queue( &iqueue );
			reply.type = UART1_RECEIVE_REPLY;
			reply.ch = char_queue_pop( &cqueue );

			//Perform the reply
			bwdebug( DBG_SYS, UART1_RECEIVER_DEBUG_AREA, "UART1_RECIEVER_SERVER: replying [to: %d with: %d]",
								target_tid, reply.ch );
			//bwprintf( COM2, "E\n" ); 
			Reply(target_tid, (char *) &reply, sizeof(reply));
		}
	}
}
	virtual void OnRead()
	{
		TRACE("OnRead\n");

		char buf[512];
		int nRead = Receive(buf, 1);
		m_data += buf;

	//	::MessageBox(NULL, buf, NULL, MB_OK);
		for (int i = 0; i < nRead; i++)
		{
			TRACE("%c", buf[i]);
		}

		const char* end = strstr(m_data.c_str(), "\r\n");
		if (end)
		{
			//std::string response = std::string(m_data, end - m_data.c_str());
			//m_response = end + 2;
		}

#if 0
		if (m_state == STATE_CONNECT)
		{
			if (!strncmp(m_response.c_str(), "+OK", 3))
			{
				// The server has greeted us

				// Let's identify ourselves
				m_state = STATE_USER;
				m_response = "";

			}
		}
		else if (m_state == STATE_USER)
		{
			if (!strncmp(m_response.c_str(), "+OK", 3))
			{
				// Username has been accepted

				// Send the password
				m_state = STATE_PASS;
				m_response = "";

		//		char* msg = "PASS 04bi1u6\r\n";
		//		send(m_socket, msg, strlen(msg), 0);
			}
			/*
			else
			{
				char* msg = "QUIT\r\n";
				send(m_socket, msg, strlen(msg), 0);
			}
			*/
		}
		else if (m_state == STATE_PASS)
		{
			if (!strncmp(m_response.c_str(), "+OK", 3))
			{
				// Password has been accepted
				m_state = STATE_LIST;
				m_response = "";
#if 0

				char* msg = "LIST\r\n";
				send(m_socket, msg, strlen(msg), 0);
#endif

			}
			/*
			else
			{
				char* msg = "QUIT\r\n";
				send(m_socket, msg, strlen(msg), 0);
			}
			*/
		}
		/*
		else if (m_state == STATE_LIST)
		{
			if (!strncmp(m_response.c_str(), "+OK", 3))
			{
				if (strstr(m_response.c_str(), "\r\n."))
				{
					char* msg = "QUIT\r\n";
					send(m_socket, msg, strlen(msg), 0);
				}
			}
		}
		else
		{
			char* msg = "QUIT\r\n";
			send(m_socket, msg, strlen(msg), 0);
		}
		*/
#endif
	}
Beispiel #16
0
static int HandleReply(zloop_t *wloop, zmq_pollitem_t *item, void *arg) {
	
	proto::Reply rep;
	Receive(rep, item->socket);
	
	//rep.PrintDebugString();
	
	if(rep.has_errstr())
		printf("Message from server: %s\n", rep.errstr().c_str());
	
	if(rep.has_block()){
		
		HandleNewBlock(rep.block());
		
	}
	
	if(rep.type() == proto::Request::GETWORK){
		
		if(rep.has_work()){
			
			HandleNewWork(rep.work());
			
		}
		
	}else if(rep.type() == proto::Request::SHARE){
		
		unsigned length = gSharesSent[rep.reqid()];
		gSharesSent.erase(rep.reqid());
		
		switch(rep.error()){
		case proto::Reply::NONE:
			printf("Share accepted.\n");
			gShares[length].accepted++;
			break;
		case proto::Reply::INVALID:
			printf("Invalid share.\n");
			gShares[length].invalid++;
			break;
		case proto::Reply::STALE:
			printf("Stale share.\n");
			gShares[length].stale++;
			ReConnectSignals();
			break;
		case proto::Reply_ErrType_DUPLICATE:
			printf("Duplicate share.\n");
			gShares[length].duplicate++;
			break;
		default: break;
		}
		
	}else if(rep.type() == proto::Request::STATS){
		
		if(rep.error() == proto::Reply::NONE)
			{}//printf("Statistics accepted.\n");
		else
			printf("Statistics rejected.\n");
		
	}else if(rep.type() == proto::Request::PING){
		
		//printf("Received heartbeat.\n");
		
	}
	
	gHeartBeat = true;
	
	return 0;
	
}
Beispiel #17
0
void 
qsrWaitForConnections( qsrAcceptor * pAcceptor )
{
   int errcode = 0;
   fd_set readSet, writeSet;
   int maxFD, fired;
   struct timeval timeout;   
   unsigned int i;
   bool rc;
   
   PSO_PRE_CONDITION( pAcceptor != NULL );

   /*
    * NOTE: since socket handles, on Windows, are not integers, we will
    * not used the handles as indices to the pAcceptor->dispatch array
    */

   pAcceptor->dispatch[0].socketId = pAcceptor->socketFD;
   pAcceptor->dispatch[0].pid = 0;
   pAcceptor->dispatch[0].dataToBeWritten = false;
   
   for ( i = 1; i < FD_SETSIZE; ++i ) {
      pAcceptor->dispatch[i].socketId = PSO_INVALID_SOCKET;
      pAcceptor->dispatch[i].pid = -1;
      pAcceptor->dispatch[i].dataToBeWritten = false;
   }   

   while ( true ) {
      int zzz = 0;
      if ( g_pQSR->controlWord & QSR_SHUTDOWN_REQUEST ) {
         break;
      }
      
      timeout.tv_sec = 1;
      timeout.tv_usec = 0;
      FD_ZERO( &readSet  );
      FD_ZERO( &writeSet );
      maxFD = 0;
      for ( i = 0; i < FD_SETSIZE; ++i ) {
         
         if ( pAcceptor->dispatch[i].socketId != PSO_INVALID_SOCKET) {
            if ( pAcceptor->dispatch[i].dataToBeWritten == 0 ) {
               FD_SET( pAcceptor->dispatch[i].socketId, &readSet);
               zzz++;
            }
            else {
               FD_SET( pAcceptor->dispatch[i].socketId, &writeSet);
               zzz++;
            }
#if ! defined (WIN32)
            if ( pAcceptor->dispatch[i].socketId+1 > maxFD ) {
               maxFD = pAcceptor->dispatch[i].socketId+1;
            }
#endif
         }
      }

      do {
         fired = select( maxFD, &readSet, &writeSet, NULL, &timeout );
      } while ( fired == -1 && errno == EINTR );
      

      if ( fired == -1 ) {
         qsrSendMessage( &pAcceptor->pQuasar->log, 
                          QSR_ERROR, 
                          "In function select(), error = %d",
                          GetSockError() );
         errcode = -1;
         break;
      }
      if ( fired == 0 ) continue;
      
      /*
       * Start with the socket listening for new connection requests
       */
      if ( FD_ISSET( pAcceptor->socketFD, &readSet ) ) {
         rc = Accept( pAcceptor );
         PSO_POST_CONDITION( rc == true || rc == false );
         if ( ! rc ) break;
         fired--;
      }
      if ( fired == 0 ) continue;
      
      /*
       * Process all open sockets 
       */
      for ( i = 1; i < FD_SETSIZE; ++i ) {
         if ( pAcceptor->dispatch[i].socketId != PSO_INVALID_SOCKET ) {
            if ( FD_ISSET( pAcceptor->dispatch[i].socketId, &writeSet ) ) {
               Send( pAcceptor, i );
               fired--;
            }
            else if ( FD_ISSET( pAcceptor->dispatch[i].socketId, &readSet ) ) {
               Receive( pAcceptor, i );
               fired--;
            }
         }
         if ( fired == 0 ) break;
      }
   }

   // Cleanup (close all sockets)
   for ( i = 0; i < FD_SETSIZE; ++i ) {
      if ( pAcceptor->dispatch[i].socketId != PSO_INVALID_SOCKET ) {
#if defined (WIN32) 
         shutdown( pAcceptor->dispatch[i].socketId, SD_BOTH );      
         closesocket( pAcceptor->dispatch[i].socketId );
#else
         shutdown( pAcceptor->dispatch[i].socketId, 2 );      
         close( pAcceptor->dispatch[i].socketId );
#endif
      }
   }
   pAcceptor->socketFD = PSO_INVALID_SOCKET;

}
Beispiel #18
0
int main(void) {
	
	gBlock.set_height(0);
	gClientName = sysinfo::GetClientName();
	gClientID = sysinfo::GetClientID();
	gInstanceID = gClientID * (unsigned)time(0);
	srand(gInstanceID);
	
	std::string frontHost;
	unsigned frontPort;
	
	Configuration* cfg = Configuration::create();
	try{
		cfg->parse("config.txt");
		frontHost = cfg->lookupString("", "server", "localhost");
		frontPort = cfg->lookupInt("", "port", 6666);
		gAddr = cfg->lookupString("", "address", "");
		gClientName = cfg->lookupString("", "name", gClientName.c_str());
	}catch(const ConfigurationException& ex){
		printf("ERROR: %s\n", ex.c_str());
		printf("hit return to exit...\n");
		std::string line;
		std::getline(std::cin, line);
		exit(EXIT_FAILURE);
	}
	
	if(!gClientName.size())
		gClientName = sysinfo::GetClientName();
	
	printf("madPrimeMiner-v%d.%d\n", gClientVersion/10, gClientVersion%10);
	printf("ClientName = '%s'  ClientID = %u  InstanceID = %u\n", gClientName.c_str(), gClientID, gInstanceID);
	printf("Address = '%s'\n", gAddr.c_str());
	
	if(!gAddr.size()){
		printf("ERROR: address not specified in config.txt\n");
		printf("hit return to exit...\n");
		std::string line;
		std::getline(std::cin, line);
		exit(EXIT_FAILURE);
	}
	
	gCtx = zctx_new();
	
	gWorkers = zsocket_new(gCtx, ZMQ_PULL);
	zsocket_bind(gWorkers, "inproc://shares");
	
	gClient = new XPMClient(gCtx);
	gExit = !gClient->Initialize(cfg);
	
	while(!gExit){
		
		printf("Connecting to frontend: %s:%d ...\n", frontHost.c_str(), frontPort);
		
		gBlock.Clear();
		proto::Reply rep;
		gExit = true;
		
		while(gExit){
			
			zsocket_destroy(gCtx, gFrontend);
			gFrontend = zsocket_new(gCtx, ZMQ_DEALER);
			
			int err = zsocket_connect(gFrontend, "tcp://%s:%d", frontHost.c_str(), frontPort);
			if(err){
				printf("ERROR: invalid hostname and/or port.\n");
				exit(EXIT_FAILURE);
			}
			
			proto::Request req;
			req.set_type(proto::Request::CONNECT);
			req.set_reqid(++gNextReqID);
			req.set_version(gClientVersion);
			req.set_height(0);
			
			GetNewReqNonce(req);
			Send(req, gFrontend);
			
			bool ready = zsocket_poll(gFrontend, 3*1000);
			
			if(zctx_interrupted)
				break;
			
			if(!ready)
				continue;
			
			Receive(rep, gFrontend);
			
			if(rep.error() != proto::Reply::NONE){
				printf("ERROR: %s\n", proto::Reply::ErrType_Name(rep.error()).c_str());
				if(rep.has_errstr())
					printf("Message from server: %s\n", rep.errstr().c_str());
			}
			
			if(!rep.has_sinfo())
				break;
			
			gServerInfo = rep.sinfo();
			
			bool ret = false;
			ret |= !ConnectBitcoin();
			ret |= !ConnectSignals();
			if(ret)
				break;
			
			gExit = false;
			
		}
		
		zsocket_disconnect(gFrontend, "tcp://%s:%d", frontHost.c_str(), frontPort);
		
		if(gExit)
			break;
		
		zloop_t* wloop = zloop_new();
		
		zmq_pollitem_t item_server = {gServer, 0, ZMQ_POLLIN, 0};
		int err = zloop_poller(wloop, &item_server, &HandleReply, 0);
		assert(!err);
		
		zmq_pollitem_t item_signals = {gSignals, 0, ZMQ_POLLIN, 0};
		err = zloop_poller(wloop, &item_signals, &HandleSignal, 0);
		assert(!err);
		
		zmq_pollitem_t item_workers = {gWorkers, 0, ZMQ_POLLIN, 0};
		err = zloop_poller(wloop, &item_workers, &HandleWorkers, 0);
		assert(!err);
		
		err = zloop_timer(wloop, 60*1000, 0, &HandleTimer, 0);
		assert(err >= 0);
		
		gHeartBeat = true;
		gExit = true;
		
		if(rep.has_block())
			HandleNewBlock(rep.block());
		else
			RequestWork();
		
		gClient->Toggle();
		zloop_start(wloop);
		
		gClient->Toggle();
		zloop_destroy(&wloop);
		
		zsocket_destroy(gCtx, gServer);
		zsocket_destroy(gCtx, gSignals);
		
		gServer = 0;
		gSignals = 0;
		
	}
	
	delete gClient;
	
	zsocket_destroy(gCtx, gWorkers);
	zsocket_destroy(gCtx, gFrontend);
	zctx_destroy(&gCtx);
	
	return EXIT_SUCCESS;
	
}
void train_command_entry() {
	RegisterAs(TRAIN_COMMAND);
	
	int clock_tid = WhoIs(CLOCK_SERVER);
	int uart_tid = WhoIs(UART_SERVER);

	int sender_tid;
	struct train_command_message msg;
	while (1) {
		int reply = 0;

		Receive(&sender_tid, (char*)&msg, sizeof(msg));

		switch (msg.command) {
			case TRAIN_GO:
				Putc(COM1, 0x60, uart_tid);
				break;

			case TRAIN_STOP:
				Putc(COM1, 0x61, uart_tid);
				break;

			case TRAIN_SPEED:
				if (msg.data1 <= 14) {
					if (msg.data2 > 0 && msg.data2 <= 80) {
						Putc(COM1, msg.data1 | 16, uart_tid);
						Putc(COM1, msg.data2, uart_tid);
						break;
					}
				}
				// Error case
				reply = -1;
				break;

			case TRAIN_REVERSE:
				if (msg.data1 > 0 && msg.data1 <= 80) {
					Putc(COM1, 0x0F, uart_tid);
					Putc(COM1, msg.data1, uart_tid);
					break;
				}
				// Error case
				reply = -1;
				break;

			case TRAIN_READ_SENSORS:
				if (msg.data1 > 0 && msg.data1 <= 31) {
					Putc(COM1, 0x80 + msg.data1, uart_tid);
					break;
				}
				// Error case
				reply = -1;
				break;

			case TRAIN_RESET_SENSORS:
				if (msg.data1 > 0 && msg.data1 <= 31) {
					Putc(COM1, 192, uart_tid);
					break;
				}
				// Error case
				reply = -1;
				break;

			case TRAIN_SWITCH_CURVED:
				Putc(COM1, 0x22, uart_tid);
				Putc(COM1, msg.data1, uart_tid);
				break;

			case TRAIN_SWITCH_STRAIGHT:
				Putc(COM1, 0x21, uart_tid);
				Putc(COM1, msg.data1, uart_tid);
				break;

			case TRAIN_SOLENOID_OFF:
				Putc(COM1, 0x20, uart_tid);
				break;

			default:
				reply = -1;
				break;
		}

		// delay between train commands
		Delay(1, clock_tid); // 1 tick = 10ms

		Reply(sender_tid, (char*)&reply, sizeof(reply));
	}

	Exit();
}
void sensors_server() {
	bwdebug( DBG_SYS, SENSORS_SERVER_DEBUG_AREA, "SENSORS_SERVER: enters" );
	RegisterAs( SENSORS_SERVER_NAME );
	
	// Data structures
	int notifier_tid, sender_tid;
	char s88s[10], s88s_prev[10];
	Sensor_history sensor_history;
	Sensor_waiting_list sensors_waiting_list[ NUM_SENSORS ];
	All_sensors_waiting_queue all_sensors_waiting_queue; 
	Sensor_server_data server_data; 
	server_data.sensor_history = &sensor_history; 
	server_data.sensor_waiting_list = sensors_waiting_list; 
	server_data.all_sensors_wait_queue = &all_sensors_waiting_queue; 

	// Messages
	Sensor_msg sensor_msg; 	
	Init_sensor_msg init_msg; 
	Sensor_id_list_reply sensor_id_list_reply; 
	
	// Initialization
	init_sensor_data( s88s ); 
	init_sensor_data( s88s_prev ); 
	init_sensor_history( &sensor_history );
	init_sensor_waiting_lists( sensors_waiting_list ); 
	init_all_sensors_waiting_queue( &all_sensors_waiting_queue ); 
	init_id_list_reply( &sensor_id_list_reply ); 

	init_msg.sensor_data_buff = s88s; 
	init_msg.prev_sensor_data_buff = s88s_prev; 
	notifier_tid = Create( SENSOR_NOTIFIER_PRIORITY, sensors_server_notifier ); 
	bwdebug( DBG_SYS, SENSORS_SERVER_DEBUG_AREA, "SENSORS_SERVER: sensors_server_notifier created [tid: %d priority: %d]", 
			notifier_tid, SENSOR_NOTIFIER_PRIORITY );
	Send( notifier_tid, ( char * ) &init_msg, sizeof( init_msg ), 0, 0 ); 
	
	FOREVER {
		bwdebug( DBG_SYS, SENSORS_SERVER_DEBUG_AREA, "SENSORS_SERVER: listening for a request" );
		Receive( &sender_tid, ( char * ) &sensor_msg, sizeof( sensor_msg )  );
		switch( sensor_msg.type ){
			case SENSOR_DATA_RECEIVED_MSG:				
				Reply( sender_tid, 0, 0 ); 
				parse_sensors( s88s, s88s_prev, &server_data ); // If this slows down the server put it in a different task. 
				draw_sensor_history( &sensor_history );	
				store_previous_sensors( s88s, s88s_prev );
				break; 
			case WAIT_SENSOR_CHANGE_MSG:
				// Wait for a particular sensor to be triggered
				wait_for_sensor( sensors_waiting_list, sender_tid, sensor_msg.sensor_group, sensor_msg.pin_id );
				break; 
			case WAIT_ALL_SENSORS_CHANGE_MSG:
				// Wait for any sensor to be triggered
				wait_for_all_sensors( &all_sensors_waiting_queue, sender_tid ); 
				break;
			case GET_SENSOR_LIST_MSG:
				// Get the list of sensors
				bwdebug( DBG_USR, TEMP_DEBUG_AREA, "Received msg" ); 
				Reply( sender_tid, ( char * ) &sensor_id_list_reply, sizeof( sensor_id_list_reply ) );
				bwdebug( DBG_USR, TEMP_DEBUG_AREA, "Replying msg" ); 
			default:
				bwdebug( DBG_SYS, SENSORS_SERVER_DEBUG_AREA, "SENSORS_SERVER: Invalid request. [type: %d]", sensor_msg.type );
				break; 
		}
	}
}
Beispiel #21
0
void driver() {
  Driver me;
  initDriver(&me, 1);

  unsigned int naggCount = 0;
  unsigned int updateStoppingDistanceCount = 0;

  for (;;) {
    int tid = -1;
    DriverMsg msg;
    msg.data2 = -1;
    msg.data3 = -1;
    msg.replyTid = -1;
    Receive(&tid, (char*)&msg, sizeof(DriverMsg));
    if (tid != me.delayer && tid != me.stopDelayer) {
      Reply(tid, (char*)1, 0);
    }
    const int replyTid = msg.replyTid;

    switch (msg.type) {
      case SET_SPEED: {
        //TrainDebug(&me, "Set speed from msg");
        trainSetSpeed(msg.data2,
                      getStoppingTime(&me),
                      (msg.data3 == DELAYER),
                      &me);
        if (msg.data3 != DELAYER) {
          //TrainDebug(&me, "Replied to %d", replyTid);
          Reply(replyTid, (char*)1, 0);
          sendUiReport(&me);
          break;
        } else if (me.route.length != 0) {
          // Delayer came back. Reverse command completed
          me.stopCommited = 0; // We're moving again.
          // We've completed everything up to the reverse node.
          me.routeRemaining = me.stopNode+1;
          me.previousStopNode = me.routeRemaining;
          me.distanceFromLastSensorAtPreviousStopNode = me.distanceFromLastSensor;
          // Calculate the next stop node.
          updateStopNode(&me);
          me.nextSetSwitchNode = -1;
          updateSetSwitch(&me);
          // if the reverse is last node, nothing to do
          // if it isn't.. it should speed up again.
        }
      }
      case DELAYER: {
        //TrainDebug(&me, "delayer come back.");
        break;
      }
      case STOP_DELAYER: {
        // To prevent the first receive from this delayer
        if (me.lastSensorActualTime > 0 && me.speed == 0 && !me.isAding) {
          TrainDebug(&me, "releasing reserveration");
          int reserveStatus = reserveMoreTrack(&me, 1, 0);
          if (reserveStatus == RESERVE_FAIL) {
            TrainDebug(&me, "WARNING: unable to reserve during init");
          }
        }
        break;
      }
      case SENSOR_TRIGGER: {

        // only handle sensor reports in primary + secondary prediction if not position finding
        int sensorReportValid = 0;
        TrackLandmark conditionLandmark;
        int condition;
        int isSensorReserved = QueryIsSensorReserved(&me, msg.data2, msg.data3);
        if (me.positionFinding) {
          sensorReportValid = 1;
          me.lastSensorUnexpected = 1;
          //FinishPositionFinding(me.trainNum, me.trainController);
        } else if (isSensorReserved) {
          //TrainDebug(&me, "Predictions.");
          for (int i = 0; i < me.numPredictions; i ++) {
            TrackLandmark predictedSensor = me.predictions[i].sensor;
            //printLandmark(&me, &predictedSensor);
            if (predictedSensor.type == LANDMARK_SENSOR && predictedSensor.num1 == msg.data2 && predictedSensor.num2 == msg.data3) {
              sensorReportValid = 1;
              if (i != 0) {
                TrainDebug(&me, "Trigger Secondary");
                // secondary prediction, need to do something about them
                conditionLandmark = me.predictions[i].conditionLandmark;
                condition = me.predictions[i].condition;
                me.lastSensorUnexpected = 1;
                if (conditionLandmark.type == LANDMARK_SWITCH) {
                  TrackMsg setSwitch;
                  setSwitch.type = UPDATE_SWITCH_STATE;
                  TrainDebug(&me, "UPDATE SWITCH STATE");
                  setSwitch.landmark1 = conditionLandmark;
                  setSwitch.data = condition;

                  Send(me.trackManager, (char*)&setSwitch, sizeof(TrackMsg), (char *)1, 0);
                }

                // Stop and then try to reroute.
                reroute(&me);
              } else {
                me.lastSensorUnexpected = 0;
              }
            }
          }
        }
        if (sensorReportValid) {
          updateRoute(&me, msg.data2, msg.data3);
          me.lastSensorBox = msg.data2; // Box
          me.lastSensorVal = msg.data3; // Val
          me.lastSensorIsTerminal = 0;
          me.lastSensorActualTime = msg.timestamp;
          dynamicCalibration(&me);
          me.lastSensorPredictedTime = me.nextSensorPredictedTime;

          TrackNextSensorMsg trackMsg;
          QueryNextSensor(&me, &trackMsg);
          // Reserve the track above train and future (covers case of init)

          for (int i = 0; i < trackMsg.numPred; i++) {
            me.predictions[i] = trackMsg.predictions[i];
          }
          me.numPredictions = trackMsg.numPred;

          int reserveStatus = reserveMoreTrack(&me, me.positionFinding, getStoppingDistance(&me));
          if (reserveStatus == RESERVE_FAIL) {
            if (!me.positionFinding) {
              reroute(&me);
            } else {
              TrainDebug(&me, "WARNING: unable to reserve during init");
            }
          }

          TrackSensorPrediction primaryPrediction = me.predictions[0];
          me.calibrationStart = msg.timestamp;
          me.calibrationDistance = primaryPrediction.dist;
          int dPos = 50 * getVelocity(&me) / 100000.0;
          me.lastSensorDistanceError =  -(int)me.distanceToNextSensor - dPos;
          me.distanceFromLastSensor = dPos;
          me.distanceToNextSensor = primaryPrediction.dist - dPos;
          me.lastPosUpdateTime = msg.timestamp;
          if (primaryPrediction.sensor.type != LANDMARK_SENSOR &&
              primaryPrediction.sensor.type != LANDMARK_END) {
            TrainDebug(&me, "QUERY_NEXT_SENSOR_FROM_SENSOR ..bad");
          }
          me.nextSensorIsTerminal = (primaryPrediction.sensor.type == LANDMARK_END);
          me.nextSensorBox = primaryPrediction.sensor.num1;
          me.nextSensorVal = primaryPrediction.sensor.num2;
          me.nextSensorPredictedTime =
            msg.timestamp + me.distanceToNextSensor*100000 /
            getVelocity(&me);

          updatePosition(&me, msg.timestamp);
          sendUiReport(&me);
          if (me.positionFinding) {
            trainSetSpeed(0, getStoppingTime(&me), 0, &me); // Found position, stop.
            me.positionFinding = 0;
            me.currentlyLost = 0;
          }
        }
        break;
      }
      case NAVIGATE_NAGGER: {
        updatePosition(&me, msg.timestamp);
        if (me.routeRemaining != -1) {
          if (!me.stopCommited) {
            if (shouldStopNow(&me)) {
              if (me.route.nodes[me.stopNode].num == REVERSE) {
                //TrainDebug(&me, "Navi reversing.");
                const int speed = -1;
                trainSetSpeed(speed, getStoppingTime(&me), 0, &me);
              }
              else {
                //TrainDebug(&me, "Navi Nagger stopping.");
                const int speed = 0;  // Set speed zero.
                trainSetSpeed(speed, getStoppingTime(&me), 0, &me);
                me.route.length = 0; // Finished the route.
                me.testMode = 0;
              }
              me.stopCommited = 1;
              me.useLastSensorNow = 0;
              me.stopNow = 0;
              me.stopSensorHit = 0;
            } else {
              if ((++updateStoppingDistanceCount & 15) == 0) updateStopNode(&me);
            }
          }
        }

        if (me.nextSetSwitchNode != -1 && (++me.setSwitchNaggerCount & 3) == 0) {
          trySetSwitch_and_getNextSwitch(&me);
        }
        if (me.rerouteCountdown-- == 0) {
          if (me.testMode) {
            int reserveStatus = reserveMoreTrack(&me, 0, me.d[8][ACCELERATE][MAX_VAL]); // moving
            if (reserveStatus == RESERVE_FAIL) {
              reroute(&me);
            } else {
              me.nextSetSwitchNode = -1;
              updateSetSwitch(&me);
              trainSetSpeed(8, 0, 0, &me);
            }
          } else {
            // reroute
            if (me.route.length != 0) {
              setRoute(&me, &(me.routeMsg));
            }
          }
        }
        if ((++naggCount & 15) == 0) sendUiReport(&me);
        break;
      }
      case SET_ROUTE: {
        Reply(replyTid, (char*)1, 0);
        me.routeMsg = msg;
        setRoute(&me, &msg);
        break;
      }
      case BROADCAST_UPDATE_PREDICTION: {
        updatePrediction(&me);
        int reserveStatus = reserveMoreTrack(&me, 0, getStoppingDistance(&me)); // moving
        if (reserveStatus == RESERVE_FAIL) {
          reroute(&me);
        }
        break;
      }
      case BROADCAST_TEST_MODE: {
        me.testMode = 1;
        setRoute(&me, &msg);
        break;
      }
      case FIND_POSITION: {
        me.positionFinding = 1;
        trainSetSpeed(5, 0, 0, &me);
        break;
      }
      default: {
        TrainDebug(&me, "Not suppported train message type.");
      }
    }
  }
}
// CSysTimeSocket 成员函数
// CMySocket2 成员函数
void CSysTimeSocket::OnReceive(int nErrorCode) 
{
	// TODO: Add your specialized code here and/or call the base class
	int ret=0;

	ret = Receive(udp_buf,RcvFrameSize);

	
	if(ret == RcvFrameSize) 
	{
		unsigned short usCommand = 0;
		byte	ucCommand = 0;
		int iPos = 26;
		unsigned short usCRC16 = 0;
		unsigned int uiSysTime = 0;
		memcpy(&usCRC16, &udp_buf[RcvFrameSize - CRCSize], 2);
		if (usCRC16 != get_crc_16(&udp_buf[FrameHeadSize], RcvFrameSize - FrameHeadSize - CRCCheckSize))
		{
		//	return FALSE;
		}

		memcpy(&usCommand, &udp_buf[iPos], 2);
		iPos += 2;

		if (usCommand == SendQueryCmd)
		{
			// 查询本地时间,0x04命令
			memcpy(&ucCommand, &udp_buf[iPos], 1);
			iPos++;
			if (ucCommand == 0x04)
			{
				memcpy(&uiSysTime, &udp_buf[iPos], 4);
				m_uiSysTimeCount++;
				if (m_uiSysTimeCount == 1)
				{
					m_uiSysTime = uiSysTime;
					// 广播命令开始采样
					m_uiIPAim = 0xffffffff;
					TRACE(_T("查询到的本地时间%d"), m_uiSysTime);
					OnADCStartSample(m_uiIPAim, m_uiSysTime);
				}
			}
			else if (ucCommand == 0x17)
			{
 				memcpy(&m_uiIPAim, &udp_buf[16], 4);
				TRACE1("接收零漂矫正查询-仪器IP地址:%d\r\n", m_uiIPAim);
				for (int i=0; i<GraphViewNum; i++)
				{
					ProcessMessages();
					if (m_uiIPAim == 81 + i*10)
					{
						memcpy(&m_ucZeroDrift[i][0], &udp_buf[0x29], 2);
						memcpy(&m_ucZeroDrift[i][2], &udp_buf[0x2c], 2);
						memcpy(&m_ucZeroDrift[i][4], &udp_buf[0x2e], 2);
						break;
					}
				}
			}
		}
	}
	CAsyncSocket::OnReceive(nErrorCode);
}
Beispiel #23
0
main(int argc, char *argv[]) {
	unsigned short cr_com=0;
	unsigned int Tpr=0;
	unsigned int Tpr1=0;
	unsigned int Tstart=0;
	short OC4=0;
    pid_t proxy;
	FILE 		 	*out_fp = NULL;
    timer_t id;
	unsigned char chkSUM=0,N=0;
	struct itimerspec timer;
    struct sigevent event;

	int K2count=0;//счетчик бафтов в буфере К2
	while( (i=getopt(argc, argv, "t:s:") )!=-1)	{
		switch(i){
			case 't' :	TM=1; break;
			case 's' :	TS=1; break;
			//case 'c' :	sscanf(optarg,"%d",COR_T); break;
		}//switch
	}//while

	delay(500);
	open_shmem();

	p->to41.PrM_K2=0;
	if (TS) printf("		УСТАНОВЛЕН РЕЖИМ РАБОТЫ ПО СИГНАЛУ ТВК\n");
	if (TM) printf("		УСТАНОВЛЕН РЕЖИМ РАБОТЫ БЕЗ ОЖИДАНИЯ КОМАНДЫ НАЧАЛА СС\n");
	if (COR_T!=0) printf("		УСТАНОВЛЕНА КОРРЕКЦИЯ ПО ВРЕМЕНИ %d МИНУТ\n",COR_T);

//	printf("TM=%d TS=%d COR_T=%d\n\n",TM,TS,COR_T);
	COR_T=COR_T*60;

	if (!TM)
	{
		//if ( ( out_fp = fopen( "//1/home/seversk/new31/k2_log", "w" ) ) == NULL ) 
		//		fprintf( stderr, "Couldn't create/open file. %s\n",  strerror( errno ) );
		printf("ОЖИДАНИЕ КОМАНДЫ НАЧАЛА СС \n");
		while((p->from41.num_com!=1)&&(p->from41.num_com!=2)) delay(500);
	}	

    proxy = qnx_proxy_attach( 0, 0, 0, -1 );
    if( proxy == -1 ) {
      printf( "Unable to attach proxy." );
      return;
    }

    /* Attach to the timer */
    event.sigev_signo = -proxy;
    id = timer_create( CLOCK_REALTIME, &event );
    if( id == -1 ) {
      printf( "Unable to attach timer." );
      return;
    }

    timer.it_value.tv_sec     = 3L; //start after X sec
    timer.it_value.tv_nsec    = 0L;
    timer.it_interval.tv_sec  = 0;
    timer.it_interval.tv_nsec = 100*m_sec;
    timer_settime( id, 0, &timer, NULL );

	delay(1000);	
	Init_K2();
	delay(500);
	printf("			НАСТРОЙКА К2	команда %d\n",p->from41.num_com);
	
	while(1)
	{
		pid=Receive(0,0,0); //получение всех системных сообщений
		if (pid==proxy_DRV2) 
		{  //получили сообщение чтения данных из ПОСТ-3Ц
			rd_cpcs_s.type=4;
			rd_cpcs_s.cnl=chan2;
		    // выдача команды и прием данных
			i=Send(pid_drv,&rd_cpcs_s,&rd_cpcs_r,sizeof(rd_cpcs_s),sizeof(rd_cpcs_r));
			//printf("Ответ =");
			//for(i=0;i<rd_cpcs_r.cnt;i++) printf(" %02x",rd_cpcs_r.uim.dt[i]);printf("\n");
    		// переформатирование
		    for (i=0;i<rd_cpcs_r.cnt;i++)  buffer[i+K2count]=rd_cpcs_r.uim.dt[i];//дополним массив

			//if ( out_fp != NULL ) 
			//	if ( fwrite( buffer+K2count, rd_cpcs_r.cnt, 1, out_fp ) != 1 )
			//		fprintf( stderr, "Failed to write to file. %s\n", strerror( errno ) );

			K2count=K2count+rd_cpcs_r.cnt;//увеличим кол-во байт в буфере
		}

		if (pid==proxy) 
		{  //срабатывание таймера
			Tcount++;
			//for(i1=0;i1<K2count;i1++) printf("%x ",buffer[i1]);printf("\n");         
			//printf("com1=%2x ", c);  //печать байта
			//printf("count=%d\n",K2count);
			if (K2count>4) 
			for(i=0;i<K2count;i++)
			if (buffer[i]==0x55) //найден заголовок
			{	
				N=buffer[i+1]; //кол-во байт в пакете без КС
				if (K2count>N+i) //достаточное кол-во байт в буфере
				{
					//printf("N=%d \n",N);					
					//1_of_day=time(NULL);
					//1strftime(b, 40 , "%T", localtime(&time_of_day));//D T
					//1msec=div(Tcount,10);
					//1printf("%s:%03d -->",b,msec.rem*100);			
					printf("%02x:%02x:%02x ", p->CEB[2]>>8,p->CEB[3]>>8,p->CEB[3]&0x00ff);
					for(i1=0;i1<N;i1++) chkSUM+=buffer[i+i1]; //подсчет контр суммы         
					//printf("i=%d chkSUM=%x\n",i,chkSUM);
					if (chkSUM!=buffer[N+i]) //если не совпадает контр сумма
					{
						printf(" error CHKSUM\n");//проверка контрольной суммы
						K2count=chkSUM=0;		//очистка буфера
						break;					//выходим и ждем дальше
					}
					//пришел правильный пакет
					printf(" (");			
					for(i1=0;i1<N+1;i1++) printf("%x.",buffer[i1+i]);printf(")");         
					//анализ полученного пакета
					switch(buffer[i+1])
					{
 						case 4: if(buffer[i+2]==3)
								{
									//printf(" Получена квитанция - команда принята ");		
									//if(buffer[i+3]==0) {comOK[1]++;printf("ПРАВИЛЬНО");break;}
									//else printf("неправильно");
									if(buffer[i+3]==0) {comOK[1]++;printf("");break;}
									else printf("");
								}
								else printf(" Получен неизвестный пакет");		
								break;
 						case 5: if(buffer[i+2]==2)
								{
									switch(buffer[i+3])
									{
										case 0x03 : printf(" ИЛС Сообщение принято - ");
													if (buffer[i+4]==0) {printf("норма");comOK[0]=1;}
													else printf("ненорма");
													break;
										case 0x06 : printf(" ЛК1 Сообщение принято - ");
													if (buffer[i+4]==0) {printf("норма");comOK[17]=1;}
													else printf("ненорма");
													break;
										case 0x18 : printf(" ЛК2 Сообщение принято - ");
													if (buffer[i+4]==0) {printf("норма");comOK[5]=1;}
													else printf("ненорма");
													break;
										case 0x01 : printf(" АвтК Сообщение принято - ");
													if (buffer[i+4]==0) {printf("норма");comOK[7]=1;}
													else printf("ненорма");
													break;
										case 0x02 : printf("  Дан.Н.НН - ");
													if (buffer[i+4]&1) printf(" нет-ДанИ");
													if (buffer[i+4]&2) printf(" нет-ДанП");
													//printf("\n");
													break;
										case 0x010: printf("  ПРМ - ");
													if (buffer[i+4]&0x01) {printf(" ПРС");p->to41.PrM_K2=1;}else p->to41.PrM_K2=0;
													if (buffer[i+4]&0x02) printf(" СС");
													if (buffer[i+4]&0x04) printf(" ЗС");
													if (buffer[i+4]&0x08) printf(" СБ");
													if (buffer[i+4]&0x10) {printf(" ИДК");p->to41.Pr_ZI_K2=1;}else p->to41.Pr_ZI_K2=0;
													if (buffer[i+4]&0x20) printf(" ИДД");
													if (buffer[i+4]&0x40) printf(" ВИ");
													if (buffer[i+4]&0x80) printf(" ПС");
													//printf("\n");
													break;
																
									}
								}
								else printf(" Получен неизвестный пакет");								
								break;
 						case 6: if(buffer[i+2]==2)
								{
									switch(buffer[i+3])
									{
										case 0x07 : OC4=buffer[i+5];OC4=(OC4<<8)|buffer[i+4];
													printf(" ОСЧ - %6.3f м/с ",OC4*0.582);break;
													//printf(" ОСЧ - %d м/с ",OC4);break;
										case 0x11 : printf(" Pтек - %d ",buffer[i+4]);
													if (buffer[i+4]>0)	p->to41.UR_sign_K2=buffer[i+4]*3;
													else p->to41.UR_sign_K2=0;
													break;
										case 0x73 : printf(" ПРМ1 - ");
													if (buffer[i+4]&0x01) {printf(" ПРС");p->to41.PrM_K2=1;}else p->to41.PrM_K2=0;
													if (buffer[i+4]&0x02) printf(" СС");
													if (buffer[i+4]&0x04) printf(" ЗС");
													if (buffer[i+4]&0x08) printf(" СБ");
													if (buffer[i+4]&0x10) {printf(" ИДК");p->to41.Pr_ZI_K2=1;}else p->to41.Pr_ZI_K2=0;
													if (buffer[i+4]&0x20) printf(" ИДД");
													if (buffer[i+4]&0x40) printf(" ВИ");
													if (buffer[i+4]&0x80) printf(" ПС");	

													if (buffer[i+5]&0x01) printf(" 27М1н");
													if (buffer[i+5]&0x02) printf(" ПФ");
													if (buffer[i+5]&0x04) printf(" РНС");
													if (buffer[i+5]&0x08) printf(" РПС");
													if (buffer[i+5]&0x10) printf(" РСС");
													if (buffer[i+5]&0x20) printf(" ЗКС");
													if (buffer[i+5]&0x40) printf(" ОСС");
													if (buffer[i+5]&0x80) printf(" НС");
													//printf("\n");
													break;
									}
								}
								else printf(" Получен неизвестный пакет");								
								break;
 						case 7: if(buffer[i+2]==2)
								{
									switch(buffer[i+3])
									{
										case 0x014: printf(" НУС Сообщение принято - ");
													if (buffer[i+4]==0) {printf("норма");comOK[10]=1;}
													else printf("ненорма");
													comOK[10]=1;//!!!
													break;
									}
								}
								else printf(" Получен неизвестный пакет");								
								break;
 						case 0x1b:
								if(buffer[i+2]==2)
								{
									printf("\n		");
									if (buffer[i+5]||buffer[i+6]) printf("ГР=%02x%02x ",buffer[i+6],buffer[i+5]);
									if (buffer[i+7]||buffer[i+8]) printf("НДИ=%02x%02x ",buffer[i+8],buffer[i+7]);
									if (buffer[i+9]||buffer[i+10])printf("МН=%02x%02x ",buffer[i+10],buffer[i+9]);
									if (buffer[i+19]||buffer[i+20]||buffer[i+21]) printf("ИИ=%02x%02x%02x ",buffer[i+21],buffer[i+20],buffer[i+19]);
									if (buffer[i+24]) {printf("СИГ=%x ",buffer[i+24]);p->to41.GL_priem=1;} else p->to41.GL_priem=0;
									if (buffer[i+25]) {printf("СРГ=%x ",buffer[i+25]);p->to41.GL_CP=1;} else p->to41.GL_CP=0;
									if (buffer[i+26]) printf("СбСИГ=%x ",buffer[i+26]);
								}
								else printf(" Получен неизвестный пакет");								
								break;


					}									
					printf("\n");
					chkSUM=0;
					K2count-=N+i+1; // сдвигаем данные в буфере
					for(i1=0;i1<K2count;i1++) buffer[i1]=buffer[i+N+i1+1];
				}			
			}
void Connection::Run()
{
	Receive();

	io_service.run();
}
Beispiel #25
0
void CSocketSend::OnReceive(int nErrorCode)
{
    // TODO: ÔÚ´ËÌí¼ÓרÓôúÂëºÍ/»òµ÷ÓûùÀà
    int ret=0;
    unsigned short uiPort = 0;
    unsigned short usADCDataPoint = 0;
    unsigned short usADCDataPointMove = 0;
    unsigned int uiIP = 0;
    ret = Receive(m_ucudp_buf[m_usudp_count],256);

    if(ret == 256)
    {
        CString strTemp = _T("");
        unsigned int uiCommand = 0;
        // 加入端口分发功能
        memcpy(&uiPort, &m_ucudp_buf[m_usudp_count][24], 2);
        if (uiPort == HeadFramePort)
        {
            memcpy(&uiCommand, &m_ucudp_buf[m_usudp_count][28], 1);
            if (uiCommand == 0x01)
            {
                // 显示SN
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][29]);
                m_csHeadFrameShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][30]);
                m_csHeadFrameShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][31]);
                m_csHeadFrameShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][32]);
                m_csHeadFrameShow += strTemp;
                m_csHeadFrameShow += _T("\t");
                // 显示首包时刻
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][34]);
                m_csHeadFrameShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][35]);
                m_csHeadFrameShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][36]);
                m_csHeadFrameShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][37]);
                m_csHeadFrameShow += strTemp;
                m_csHeadFrameShow += _T("\r\n");

                m_pwnd->GetDlgItem(IDC_EDIT_HEADFRAMESHOW)->SetWindowText(m_csHeadFrameShow);
                m_uiHeadFrameNum++;
                strTemp.Format(_T("%d"),m_uiHeadFrameNum);
                m_pwnd->GetDlgItem(IDC_STATIC_HEADFRAMENUM)->SetWindowText(strTemp);
            }
        }
        else if (uiPort == IPSetPort)
        {
            memcpy(&uiCommand, &m_ucudp_buf[m_usudp_count][28], 1);
            if (uiCommand == 0x01)
            {
                // 显示SN
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][29]);
                m_csIPSetReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][30]);
                m_csIPSetReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][31]);
                m_csIPSetReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][32]);
                m_csIPSetReturnShow += strTemp;
                m_csIPSetReturnShow += _T("\t");
                // 显示IP
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][34]);
                m_csIPSetReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][35]);
                m_csIPSetReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][36]);
                m_csIPSetReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][37]);
                m_csIPSetReturnShow += strTemp;
                m_csIPSetReturnShow += _T("\r\n");
                m_pwnd->GetDlgItem(IDC_EDIT_IPSETRETURNSHOW)->SetWindowText(m_csIPSetReturnShow);
                m_uiIPSetReturnNum++;
                strTemp.Format(_T("%d"),m_uiIPSetReturnNum);
                m_pwnd->GetDlgItem(IDC_STATIC_IPSETRETURNNUM)->SetWindowText(strTemp);
            }
        }
        else if (uiPort == TailFramePort)
        {
            memcpy(&uiCommand, &m_ucudp_buf[m_usudp_count][33], 1);
            if (uiCommand == 0x01)
            {
                // 显示SN
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][34]);
                m_csTailFrameShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][35]);
                m_csTailFrameShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][36]);
                m_csTailFrameShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][37]);
                m_csTailFrameShow += strTemp;
                m_csTailFrameShow += _T("\t");

                // 显示IP
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][29]);
                m_csTailFrameShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][30]);
                m_csTailFrameShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][31]);
                m_csTailFrameShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][32]);
                m_csTailFrameShow += strTemp;
                m_csTailFrameShow += _T("\r\n");

                m_pwnd->GetDlgItem(IDC_EDIT_TAILFRAMESHOW)->SetWindowText(m_csTailFrameShow);
                m_uiTailFrameNum++;
                strTemp.Format(_T("%d"),m_uiTailFrameNum);
                m_pwnd->GetDlgItem(IDC_STATIC_TAILFRAMENUM)->SetWindowText(strTemp);
            }
        }
        else if (uiPort == TailTimeFramePort)
        {
            memcpy(&uiCommand, &m_ucudp_buf[m_usudp_count][28], 1);
            if (uiCommand == 0x01)
            {   // 显示SN
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][29]);
                m_csTailTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][30]);
                m_csTailTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][31]);
                m_csTailTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][32]);
                m_csTailTimeReturnShow += strTemp;
                m_csTailTimeReturnShow += _T(" ");
                // 显示网络时间
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][34]);
                m_csTailTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][35]);
                m_csTailTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][36]);
                m_csTailTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][37]);
                m_csTailTimeReturnShow += strTemp;
                m_csTailTimeReturnShow += _T(" ");
                // 显示本地时间
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][39]);
                m_csTailTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][40]);
                m_csTailTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][41]);
                m_csTailTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][42]);
                m_csTailTimeReturnShow += strTemp;
                //							m_csTailTimeReturnShow += _T(" ");
                // 							// 显示尾包接收发送时刻(前14位有效)
                // 							strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][44]);
                // 							m_csTailTimeReturnShow += strTemp;
                // 							strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][45]);
                // 							m_csTailTimeReturnShow += strTemp;
                // 							strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][46]);
                // 							m_csTailTimeReturnShow += strTemp;
                // 							strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][47]);
                // 							m_csTailTimeReturnShow += strTemp;
                m_csTailTimeReturnShow += _T("\r\n");
                m_pwnd->GetDlgItem(IDC_EDIT_TAILTIMERETURNSHOW)->SetWindowText(m_csTailTimeReturnShow);
                m_uiTailTimeReturnNum++;
                strTemp.Format(_T("%d"),m_uiTailTimeReturnNum);
                m_pwnd->GetDlgItem(IDC_STATIC_TAILTIMERETURNNUM)->SetWindowText(strTemp);
            }
        }
        else if (uiPort == TimeSetPort)
        {
            memcpy(&uiCommand, &m_ucudp_buf[m_usudp_count][28], 1);
            if (uiCommand == 0x05)
            {
                // 显示IP
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][16]);
                m_csDelayTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][17]);
                m_csDelayTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][18]);
                m_csDelayTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][19]);
                m_csDelayTimeReturnShow += strTemp;
                m_csDelayTimeReturnShow += _T(" ");

                // 显示延时修正高位
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][29]);
                m_csDelayTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][30]);
                m_csDelayTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][31]);
                m_csDelayTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][32]);
                m_csDelayTimeReturnShow += strTemp;
                m_csDelayTimeReturnShow += _T(" ");

                // 显示延时修正低位
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][34]);
                m_csDelayTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][35]);
                m_csDelayTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][36]);
                m_csDelayTimeReturnShow += strTemp;
                strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][37]);
                m_csDelayTimeReturnShow += strTemp;
                m_csDelayTimeReturnShow += _T("\r\n");

                m_pwnd->GetDlgItem(IDC_EDIT_DELAYTIMERETURNSHOW)->SetWindowText(m_csDelayTimeReturnShow);
                m_uiDelayTimeReturnNum++;
                strTemp.Format(_T("%d"),m_uiDelayTimeReturnNum);
                m_pwnd->GetDlgItem(IDC_STATIC_DELAYTIMERETURNNUM)->SetWindowText(strTemp);
            }
        }
        else if (uiPort == ADSetReturnPort)
        {
            // 每次采集只有一个ADC设置应答帧
            m_uiADCSetReturnNum++;
            strTemp.Format(_T("%d"),m_uiADCSetReturnNum);
            m_pwnd->GetDlgItem(IDC_STATIC_ADCSETRETURNNUM)->SetWindowText(strTemp);
        }
        else if (uiPort == ADRecPort)
        {
            // 显示IP
            strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][16]);
            m_csADCDataRecShow += strTemp;
            strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][17]);
            m_csADCDataRecShow += strTemp;
            strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][18]);
            m_csADCDataRecShow += strTemp;
            strTemp.Format(_T("%02x "),m_ucudp_buf[m_usudp_count][19]);
            m_csADCDataRecShow += strTemp;
            m_csADCDataRecShow += _T(" ");

            // 显示ADC数据采样帧个数
            m_uiADCDataRecNum++;
            strTemp.Format(_T("%d"),m_uiADCDataRecNum);
            m_pwnd->GetDlgItem(IDC_STATIC_ADCDATARECNUM)->SetWindowText(strTemp);
            m_csADCDataRecShow += strTemp;
            m_csADCDataRecShow += _T("\t");

            memcpy(&usADCDataPoint, &m_ucudp_buf[m_usudp_count][28], 2);
            strTemp.Format(_T("%d"),usADCDataPoint);
            m_csADCDataRecShow += strTemp;
            m_csADCDataRecShow += _T("\t");

            memcpy(&uiIP, &m_ucudp_buf[m_usudp_count][16], 4);
            if (uiIP == 81)
            {
                usADCDataPointMove = usADCDataPoint - m_usADCLastDataPoint[0];
                m_usADCLastDataPoint[0] = usADCDataPoint;
            }
            else if (uiIP == 91)
            {
                usADCDataPointMove = usADCDataPoint - m_usADCLastDataPoint[1];
                m_usADCLastDataPoint[1] = usADCDataPoint;
            }
            else if (uiIP == 101)
            {
                usADCDataPointMove = usADCDataPoint - m_usADCLastDataPoint[2];
                m_usADCLastDataPoint[2] = usADCDataPoint;
            }
            else if (uiIP == 111)
            {
                usADCDataPointMove = usADCDataPoint - m_usADCLastDataPoint[3];
                m_usADCLastDataPoint[3] = usADCDataPoint;
            }
            else
            {
                usADCDataPointMove = 0;
            }
            strTemp.Format(_T("%d"),usADCDataPointMove);
            m_csADCDataRecShow += strTemp;
            m_csADCDataRecShow += _T("\r\n");
            m_pwnd->GetDlgItem(IDC_EDIT_ADCDATARECSHOW)->SetWindowText(m_csADCDataRecShow);

        }
        else
        {

        }
        m_uiRecFrameNum++;
        strTemp.Format(_T("%d"),m_uiRecFrameNum);
        m_pWndTab->GetDlgItem(IDC_STATIC_RECFRAMENUM)->SetWindowText(strTemp);
        if (m_bPortDistribution == TRUE)
        {
            // 开启端口分发功能
            SendTo(m_ucudp_buf[m_usudp_count],256,uiPort,m_csIP);
        }
        else
        {
            SendTo(m_ucudp_buf[m_usudp_count],256,m_iSendPort,m_csIP);
        }

        m_pSaveFile->OnSaveSendData(m_ucudp_buf[m_usudp_count],256);
        m_usudp_count +=1;
        m_usudp_count = m_usudp_count%8;
    }

//	AsyncSelect(FD_READ); //提请一个“读”的网络事件

    CSocket::OnReceive(nErrorCode);
}
Beispiel #26
0
main() {
    int i, j;
    int tid, tid1;

    int send=13;
    int reply=0;
    int *pSend = &send;
    int *pReply = &reply;

     printf("delaying 20\n");
     Delay(5);
     printf("delay 20 finished >>\n");


    printf("test tid %d pri %d parent tid %d\n", \
		MyTid(), MyPriority(), MyParentTid());

    tid = Receive(&i, sizeof(int));
    printf("test received << %d \n", i);

    if(i >1) {
	tid1 = Create("Test", 10);
	printf("Test %d created %d\n", MyTid(), tid1);
	j = i - 1;
	Send(tid1, &j, sizeof(int), &j, sizeof(int));
	printf("Test %d gotBack %d\n", MyTid(),j);
	i = i*j;
	Reply(tid, &i, sizeof(int));
    } else
	Reply(tid, &i, sizeof(int));

    while(1) {
	Delay(40);
	printf("test\n");
    }

    Exit();


    *pSend = 6;
    Send(tid, pSend, sizeof(int), pReply, sizeof(int));
    printf("init replyied << %d \n", *pReply);

    Exit();

    for(i=0;i <10;i++) {
	printf("init\n");
    }
    getchar();
    Pass();

    for(i=0;i <10;i++) {
	printf("init\n");
    }
    getchar();

    tid = Create("Init", 63);

    printf("init is exiting new tid %d\n", tid);

    printf("before send , send %d, reply %d\n", *pSend, *pReply);
    Send(2, pSend, sizeof(int), pReply, sizeof(int));
    printf("got replied  , send %d, reply %d\n", *pSend, *pReply);

    tid = Receive( pSend, 9);
    printf("init received from tid %d\n", tid);
    printf("init exitting...\n");
    Exit();
}
Beispiel #27
0
int cgWinSocket::ReceiveData( void * pBuff, int nBuffLen )
{
	return Receive(pBuff, nBuffLen);
}
void uart1_sender_server() {
	bwdebug( DBG_SYS, UART1_SENDER_DEBUG_AREA, "UART1_SENDER_SERVER: enters" );

	//Register the server
	RegisterAs("uart1_sender");
	
	//Create the notifier
	int notifier_tid = Create(UART1_SENDER_NOTIFIER_PRIORITY, &uart1_sender_notifier);
	bwdebug( DBG_SYS, UART1_SENDER_DEBUG_AREA, 
		"UART1_SENDER_SERVER: uart1 sender server notifier created. [tid: %d priority: %d]",
		notifier_tid, UART1_SENDER_NOTIFIER_PRIORITY );
	
	//Request & Reply
	UART_request request;
	UART_reply reply;

	//Buffer queues
	Char_queue cqueue;
	init_char_queue( &cqueue );

	FOREVER{
		//Receive request from the system function (Putc)
		bwdebug( DBG_SYS, UART1_SENDER_DEBUG_AREA, "UART1_SENDER_SERVER: listening for a request" );
		int sender_tid = -1;
		Receive(&sender_tid, (char *) &request, sizeof(request));

		
		switch(request.type){
			case UART_SEND_REQUEST_PUTC:
				bwdebug( DBG_SYS, UART1_SENDER_DEBUG_AREA, "UART1_SENDER_SERVER: Putc request from [sender_tid: %d]",
					sender_tid );
				//Reply to unblock the system function (Putc)
				//reply.type = UART1_SEND_REPLY;
				//reply.ch = 0;
				//Reply(sender_tid, (char *) &reply, sizeof(reply));
				//bwprintf( COM2, "Before reply Sender: %d\n", sender_tid  ); 
				
				char_queue_push( request.ch, &cqueue );
				Reply(sender_tid, 0, 0);
				break;

			default:
				//Invalid request
				bwdebug( DBG_SYS, UART1_SENDER_DEBUG_AREA, "UART1_SENDER_SERVER: Invalid request from [sender_tid: %d]",
					sender_tid );
				
				reply.type = INVALID_REQUEST;
				reply.ch = 0;
				Reply(sender_tid, (char *) &reply, sizeof(reply));
				break;
		}
		
		while( cqueue.size > 0){
			request.type = UART1_SEND_NOTIFIER_REQUEST;
			request.ch = char_queue_pop( &cqueue );
			
			bwdebug( DBG_SYS, UART1_SENDER_DEBUG_AREA, "UART1_SENDER_SERVER: Waking up notifier." );
			Send( notifier_tid, (char *) &request, sizeof(request), 0, 0);
		}
	}
}