Esempio n. 1
0
int main(int argc, char* argv[]) {

    //sending = true;

    //Socket socket();
    InitializeSockets();
    CreateSocket();

    if (sending) {
      //SendPacket(data, sizeof(data));

    }

    if (!gameCanStart) {
      printf("Waiting for players to connect...\n");
      FindPlayers();
    }

    ReceivePacket();


    ShutdownSockets();
    std::cin.get();

    return 0;

}
Esempio n. 2
0
bool
LX::ReceivePacketRetry(Port &port, Command command,
                       void *data, size_t length, OperationEnvironment &env,
                       std::chrono::steady_clock::duration first_timeout,
                       std::chrono::steady_clock::duration subsequent_timeout,
                       std::chrono::steady_clock::duration total_timeout,
                       unsigned n_retries)
{
  assert(n_retries > 0);

  while (true) {
    if (ReceivePacket(port, command, data, length, env,
                      first_timeout, subsequent_timeout,
                      total_timeout))
      return true;

    if (n_retries-- == 0)
      return false;

    if (!CommandMode(port, env))
      return false;

    port.Flush();
  }
}
Esempio n. 3
0
void RecvRoutine()
{
	//char recv[1532];
	int i,len;
	
	/*len=ReceivePacket(recv);
	printf("\n\r-===Recieve packet size:%d===-\n\r",len);
 	for (i=0;i<len;i++)
 	{
		printf(" %2x", recv[i]);
		if ((i>1)&&((i%16)==0)) printf("\n\r");  	
	}*///uncomment test code to see more detail about our packet
	struct sk_buff *skb;
	struct ethhdr *eth_hdr;		
	
	
	
	
	skb = alloc_skb(ETH_FRAME_LEN);
	len=ReceivePacket((char *)skb->data);
	skb->len=len;
	if (startTFTP==true)
	{
		eth_hdr = (struct ethhdr *)(skb->data);					
		skb_pull(skb, ETH_HLEN);
		if (ntohs(eth_hdr->h_proto) == ETH_P_ARP)
			arp_rcv_packet(skb);
		else if(ntohs(eth_hdr->h_proto) == ETH_P_IP)						
		 	ip_rcv_packet(skb);	
	}else free_skb(skb);
}
Esempio n. 4
0
int main(void) {
	unsigned char pkt[200];
	req r;
	ssize_t len;
	unsigned int i;
	FILE *in;
	uint32_t seed;

	signal(SIGALRM, tooslow);
	alarm(TIMEOUT);

	// set up the head of the SNMP MIB tree
	InitTree();
	SetCount = 0;
	ErrCount = 0;

	// seed the prng
	if ((in = fopen("/dev/urandom", "r")) == NULL) {
		exit(-1);
	}
	if (fread(&seed, 1, 4, in) != 4) {
		exit(-1);
	}
	fclose(in);
	srand(seed);

	// init the MIB with some objects
	PopulateMIB();

	while (1) {
		if (ErrCount > MAX_ERRORS) {
			DestroyTree(MIB);
			exit(-1);
		}
		bzero(pkt, 200);
		bzero(&r, sizeof(req));

		if ((len = ReceivePacket(pkt, 200)) == 0) {
			DestroyTree(MIB);
			exit(-1);
		}

		// reset the timer
		alarm(TIMEOUT);
		
		// parse the packet and handle the particular request
		if (ParseSnmpPkt(pkt, len, &r)) {
			if (r.type == GET_REQUEST) {
				HandleGetRequest(&r);
			} else if (r.type == GET_NEXT_REQUEST) {
				HandleGetNextRequest(&r);
			} else if (r.type == SET_REQUEST) {
				HandleSetRequest(&r);
			}
		} else {
			// error parsing packet
			ErrCount++;
		}
	}
}
Esempio n. 5
0
bool
LX::ReceivePacketRetry(Port &port, Command command,
                       void *data, size_t length, OperationEnvironment &env,
                       unsigned first_timeout_ms,
                       unsigned subsequent_timeout_ms,
                       unsigned total_timeout_ms,
                       unsigned n_retries)
{
  assert(n_retries > 0);

  while (true) {
    if (ReceivePacket(port, command, data, length, env,
                      first_timeout_ms, subsequent_timeout_ms,
                      total_timeout_ms))
      return true;

    if (n_retries-- == 0)
      return false;

    if (!CommandMode(port, env))
      return false;

    port.Flush();
  }
}
Esempio n. 6
0
void main()
{
  PLLEN_bit = PLL_ENABLE;        // Enable PLL
  Delay_ms(PLL_STABLE_TIME);
  ANSELA=DIGITAL;                // Set pins as digital
  ANSELB=DIGITAL;
  ANSELC=DIGITAL;
  ANSELE=DIGITAL;
  ANSELD=DIGITAL;
  TRISB=DIGITAL;
 //DIGITAL PIN DIRECTION
DR_NRF_Direction_bit=DIRECTION_INPUT;
TRX_CE_NRF_Direction_bit=DIRECTION_OUTPUT;
PWR_UP_NRF_Direction_bit=DIRECTION_OUTPUT;
TX_EN_NRF_Direction_bit=DIRECTION_OUTPUT;
CS_NRF_Direction_bit=DIRECTION_OUTPUT;
SPI1_Init_Advanced(_SPI_MASTER_OSC_DIV16, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_LOW, _SPI_LOW_2_HIGH);
SPI_Set_Active(&SPI1_Read, &SPI1_Write);          //  initializes SPI1
Nrf905Init();                                    //  initializes NRF905
LATB=CLR_LATCH;
while(LOOP)
   { 
   LATB=ReceivePacket();
   }
   
}
Esempio n. 7
0
/**
 * Interrupt service routine for the UART 1 receive interrupt.
 */
void interrupt UART_1_Receive_Byte()
{
    if(PIR1bits.RC1IF == 1)                                                     // If a message has been received
    {
        ReceivePacket(RCREG1);                                                  // Process it
        PIR1bits.RC1IF = 0;                                                     // and clear the interrupt flag
    }
}
Esempio n. 8
0
/** DismissIncomingPackets

    Discards any received packet at the same time confirming any pending packet should the
    acknowledgement arrive.
*/
void DismissIncomingPackets()
{
    int length;
    IPX_Address node;

    while (char *packet = ReceivePacket(&length, &node))
        qFree(packet);
}
Esempio n. 9
0
Comm::ErrorCode Comm::ReadExtendedQueryInfo(ExtendedQueryInfo* extendedBootInfo)
{
    QTime elapsed;
    WritePacket sendPacket;
    ErrorCode status;

    qDebug("Getting Extended Query Info packet...");

    if(connected)
    {
        memset((void*)&sendPacket, 0x00, sizeof(sendPacket));
        sendPacket.command = QUERY_EXTENDED_INFO;

        elapsed.start();

        status = SendPacket((unsigned char*)&sendPacket, sizeof(sendPacket));

        switch(status)
        {
            case Fail:
                close();
            case Timeout:
                return status;
            default:
                break;
        }

        qDebug("Successfully sent QUERY_EXTENDED_INFO command (%fs)", (double)elapsed.elapsed() / 1000);
        memset((void*)extendedBootInfo, 0x00, sizeof(ExtendedQueryInfo));

        elapsed.start();

        status = ReceivePacket((unsigned char*)extendedBootInfo, sizeof(ExtendedQueryInfo));


        if(extendedBootInfo->command != QUERY_EXTENDED_INFO)
        {
            qWarning("Received incorrect command.");
            return IncorrectCommand;
        }

        switch(status)
        {
            case Fail:
                close();
            case Timeout:
                return status;
            default:
                break;
        }

        qDebug("Successfully received QUERY_EXTENDED_INFO response packet (%fs)", (double)elapsed.elapsed() / 1000);
        return Success;
    }

    return NotConnected;
}
Esempio n. 10
0
Comm::ErrorCode Comm::ReadBootloaderInfo(BootInfo* bootInfo)
{
    QTime elapsed;
    WritePacket sendPacket;
    ErrorCode status;

    qDebug("Getting Query packet...");

    if(connected)
    {
        memset((void*)&sendPacket, 0x00, sizeof(sendPacket));
        sendPacket.command = QUERY_DEVICE;
        memcpy(&sendPacket.BootInfo.protectionPassword, protectionPassword.data(), 8);

        elapsed.start();

        status = SendPacket((unsigned char*)&sendPacket, sizeof(sendPacket));

        switch(status)
        {
            case Fail:
                close();
            case Timeout:
                return status;
            default:
                break;
        }

        qDebug("Successfully sent querying command (%fs)", (double)elapsed.elapsed() / 1000);
        memset((void*)bootInfo, 0x00, sizeof(BootInfo));

        elapsed.start();

        status = ReceivePacket((unsigned char*)bootInfo, sizeof(BootInfo));

        if(bootInfo->command != 0x02) {
            qWarning("Received incorrect command.");
            return IncorrectCommand;
        }

        switch(status)
        {
            case Fail:
                close();
            case Timeout:
                return status;
            default:
                break;
        }

        qDebug("Successfully received query packet (%fs)", (double)elapsed.elapsed() / 1000);
        return Success;
    }

    return NotConnected;
}
Esempio n. 11
0
void main( void )
{  
  // Stop watchdog timer to prevent time out reset 
  WDTCTL = WDTPW + WDTHOLD; 
  // Increase PMMCOREV level to 2 for proper radio operation
  SetVCore(2);                               
  
  ResetRadioCore();
  InitButtonLeds();
  InitTimer(); 
    
  // Clean out the RX Buffer 
  rxPosition = PACKET_LEN+2;
  while(rxPosition--)
  {
    RxBuffer[rxPosition] = 0; 
  }

  InitRadio();  
  ReceiveOn(); 
//Check RSSI here
  while (1)
  { 
    P1IE |= BIT7;                           // Enable button interrupt
    
    __bis_SR_register( LPM3_bits + GIE );   
    __no_operation(); 
    
    if (buttonPressed)                      // Process a button press->transmit
    {
      ReceiveOff();                         // Button means TX, stop RX
      receiving = 0;                         

      TransmitPacket();                 

      buttonPressed = 0;                    // Re-enable button press                           
    }
    if(receiving)
    {
      ReceivePacket(); 
      __no_operation(); 
      // Check CRC
      if(RxBuffer[CRC_LQI_IDX] & CRC_OK)
      //Got it!
      P1OUT ^= BIT0;                    // Toggle LED1 in celebration

    }
    if(!transmitting)
    {
      ReceiveOn(); 
    }
  }


}
Esempio n. 12
0
static int SendFrameAndReceivePacket(AVCodecContext* avctx, AVPacket* pkt, AVFrame* frame,
                                     int* got_packet)
{
#if LIBAVCODEC_VERSION_INT < AV_VERSION_INT(57, 37, 100)
  return avcodec_encode_video2(avctx, pkt, frame, got_packet);
#else
  *got_packet = 0;
  int error = avcodec_send_frame(avctx, frame);
  if (error)
    return error;

  return ReceivePacket(avctx, pkt, got_packet);
#endif
}
Esempio n. 13
0
bh_error GetResponse(packet_protocol ptc)
{

    int res = ReceivePacket(proxyfd, recPack, &bufferLength, DYNAMIC_BUFFER );

    if (res == BH_SRVR_SUCCESS) {
        if(recPack->header.packetID == ptc &&
           recPack->header.packetSize == sizeof(bh_error)) {
            bh_error res = *(bh_error *)recPack->data;
            return res;
        } else if(recPack->header.packetID != ptc) {
            printf("Wrong packet id for response\n");
        } else {
            printf("Wrong size of response data");
        }
    }

    return BH_ERROR;
}
Esempio n. 14
0
static char *ReceiveNextPacket(int *destSize, IPX_Address *node, int currentPacketIndex)
{
    static int packetProcessingDepth;
    char *packet;
    IPX_Listen((ECB *)m_packets[currentPacketIndex]); /* repost the ECB */

    /* prevent stack overflow in case of flooding, also limit depth because
       it affects the performance (menus become unresponsive)
       (bah, seems that IPX itself causes it... or it's just VMWare) */
    if (stackavail() < 128 || packetProcessingDepth > MAX_RECV_PACKETS * 2) {
        WriteToLog("Stack overflow prevention triggered.");
        *destSize = 0;
        return nullptr;
    }

    packetProcessingDepth++;
    packet = ReceivePacket(destSize, node);
    packetProcessingDepth--;
    return packet;
}
Esempio n. 15
0
static void HandleDelayedPackets()
{
  AVPacket pkt;

  while (true)
  {
    PreparePacket(&pkt);
    int got_packet;
    int error = ReceivePacket(s_codec_context, &pkt, &got_packet);
    if (error)
    {
      ERROR_LOG(VIDEO, "Error while stopping video: %d", error);
      break;
    }

    if (!got_packet)
      break;

    WritePacket(pkt);
  }
}
Esempio n. 16
0
int main(void) {
	unsigned char pkt[256];

	// init the VARS
	if (!InitVARS()) {
		puts("InitVARS failure");
		_terminate(-1);
	}

	// packet handler loop
	while (1) {
		if (ReceivePacket(pkt) == 0) {
			break;
		}
		HandlePacket(pkt);
	}

	// destroy the VARS
	DestroyVARS();

	return(0);
}
XnStatus SocketInConnection::ReadThreadProcImpl()
{
	XnStatus nRetVal = XN_STATUS_OK;
	XN_SOCKET_HANDLE hSocket = NULL;
	XnBool bCanceled = FALSE;
	XnUInt32 nPacketBytesRead = 0;
	XnUInt32 nTotalBytesRead = 0;

	m_nConnectionStatus = ConnectSocket(hSocket, m_strIP, m_nPort);
	XN_IS_STATUS_OK_LOG_ERROR("Connect socket", m_nConnectionStatus);
	nRetVal = xnOSSetEvent(m_hConnectEvent);
	XN_IS_STATUS_OK_LOG_ERROR("Set connect event", nRetVal);

	while (!m_bStopReadThread)
	{
		//Fill buffer with received packets
		nTotalBytesRead = 0;
		for (XnUInt32 nPacket = 0; (nPacket < BUFFER_NUM_PACKETS); nPacket++)
		{
			nPacketBytesRead = m_nMaxPacketSize;
			m_nConnectionStatus = ReceivePacket(hSocket, m_pBuffer + nTotalBytesRead, nPacketBytesRead, bCanceled);
			if (m_nConnectionStatus != XN_STATUS_OK)
			{
				m_pDataDestination->HandleDisconnection();				
				xnLogError(XN_MASK_LINK, "Failed to receive packet: %s", xnGetStatusString(m_nConnectionStatus));
				//XN_ASSERT(FALSE);
				return m_nConnectionStatus;
			}

			if (bCanceled)
			{
				//Ignore packet and exit loop
				break;
			}

			if (nTotalBytesRead == m_nBufferSize)
			{
				xnLogError(XN_MASK_LINK, "Read thread buffer overflowed :(");
				XN_ASSERT(FALSE);
				return XN_STATUS_INTERNAL_BUFFER_TOO_SMALL;
			}

			nTotalBytesRead += nPacketBytesRead;
		}

		if (m_pDataDestination != NULL)	
		{
			//Send data in buffer to its destination.
			//Even if at this point the read thread should be stopped, first we send all the complete packets we got.
			if (nTotalBytesRead > 0)
			{
				m_pDataDestination->IncomingData(m_pBuffer, nTotalBytesRead);
			}
		}
	}

	nRetVal = xnOSCloseSocket(hSocket);
	if (nRetVal != XN_STATUS_OK)
	{
		xnLogWarning(XN_MASK_LINK, "Failed to close input data socket :(");
		XN_ASSERT(FALSE);
	}
	m_nConnectionStatus = XN_STATUS_OS_NETWORK_CONNECTION_CLOSED;

	return XN_STATUS_OK;	
}
Esempio n. 18
0
//**********************************************************************************************//
//*******************************    Receive Packet Handling   *********************************//
//**********************************************************************************************//
static void ethernet_interrupt_handler() {
	unsigned int receive_status;
	int i;
	int j;
	int k;
	int termination;
	int byte14;
	int byte15;
	int byte16;
	int byte17;
	int byte18;
	int byte19;
	int byte20;
	int byte21;
	int byte22;
	int byte23;
	int byte24;
	int byte25;
	int byte26;
	int byte27;
	int byte28;
	int byte29;
	int byte30;
	int byte31;
	int byte32;
	int byte33;
	int ip_header0;
	int ip_header1;
	int ip_header2;
	int ip_header3;
	int ip_header4;
	int ip_header5;
	int ip_header6;
	int ip_header7;
	int ip_header8;
	int ip_header9;
	int long crc_twos;
	int crc_carry;
	int crc_ones;
	unsigned int long checksum;
	alt_u32 checksum_32;
	receive_status = ReceivePacket(receive_buffer, &receive_buffer_length);
	if (receive_status == DMFE_SUCCESS) {
#if 1
		printf("\n\nReceive Packet Length = %d", receive_buffer_length);
		for (i = 411; i < 435; i++)
		{
			for (j = 0; j < 640; j++)
			{
				Vga_Clr_Pixel(VGA_0_BASE, j, i);
			}
		}
		for(i=0;i<receive_buffer_length;i++) {
			if (i%8==0) printf("\n");
			printf("0x%.2X,", receive_buffer[i]);
		}
		printf("\n");
#endif
		if (receive_buffer_length >= 14) {
			//  A real Ethernet packet
			if (receive_buffer[12] == 8 && receive_buffer[13] == 0 &&
					receive_buffer_length >= 34) {
				// An IP packet
				if (receive_buffer[23] == 0x11) {
					// A UDP packet
					if (receive_buffer_length >= UDP_PACKET_PAYLOAD_OFFSET) {

//**********************************************************************************************//
//*****************************    Incoming Checksum Validation   ******************************//
//**********************************************************************************************//
						byte14 = receive_buffer[14] << 8;
						byte15 = receive_buffer[15];
						byte16 = receive_buffer[16] << 8;
						byte17 = receive_buffer[17];
						byte18 = receive_buffer[18] << 8;
						byte19 = receive_buffer[19];
						byte20 = receive_buffer[20] << 8;
						byte21 = receive_buffer[21];
						byte22 = receive_buffer[22] << 8;
						byte23 = receive_buffer[23];
						byte24 = receive_buffer[24] << 8;
						byte25 = receive_buffer[25];
						byte26 = receive_buffer[26] << 8;
						byte27 = receive_buffer[27];
						byte28 = receive_buffer[28] << 8;
						byte29 = receive_buffer[29];
						byte30 = receive_buffer[30] << 8;
						byte31 = receive_buffer[31];
						byte32 = receive_buffer[32] << 8;
						byte33 = receive_buffer[33];
						ip_header0 = byte14 + byte15;
						ip_header1 = byte16 + byte17;
						ip_header2 = byte18 + byte19;
						ip_header3 = byte20 + byte21;
						ip_header4 = byte22 + byte23;
						ip_header5 = byte24 + byte25;
						ip_header6 = byte26 + byte27;
						ip_header7 = byte28 + byte29;
						ip_header8 = byte30 + byte31;
						ip_header9 = byte32 + byte33;
						crc_twos = ip_header0+ip_header1+ip_header2+ip_header3+ip_header4+ip_header5+ip_header6+ip_header7+ip_header8+ip_header9;
						printf("\n %hx twos: ", crc_twos);
						crc_carry = crc_twos >> 16;
						printf("\n %hx carry: ", crc_carry);
						crc_ones = crc_twos + crc_carry;
						printf("\n ones: %hx", crc_ones);
						checksum = (crc_ones ^ 0xFFFF) & 0xFFFF; // invert bits
						printf("\n %hx checksum: ", checksum);

//**********************************************************************************************//
//*******************************    Display Received Message   ********************************//
//**********************************************************************************************//
						if (!checksum)
						{
							put_vga_string("Message received.", 0, 26);
							printf("Received: %s\n",receive_buffer + UDP_PACKET_PAYLOAD_OFFSET);
							if (current_line < 25 && receive_buffer_length < 79)
							{
								for (i = UDP_PACKET_PAYLOAD_OFFSET; receive_buffer[i] != 0; i++)
									put_vga_char(receive_buffer[i], i-UDP_PACKET_PAYLOAD_OFFSET, current_line);
								current_line++;
							}
							else if (current_line < 24 && receive_buffer_length > 78)
							{
								for (i = UDP_PACKET_PAYLOAD_OFFSET; i < 79+UDP_PACKET_PAYLOAD_OFFSET; i++)
									put_vga_char(receive_buffer[i], i-UDP_PACKET_PAYLOAD_OFFSET, current_line);
								for (i = UDP_PACKET_PAYLOAD_OFFSET+79; receive_buffer[i] != 0; i++)
									put_vga_char(receive_buffer[i], i-UDP_PACKET_PAYLOAD_OFFSET-79, current_line+1);
								current_line++;
								current_line++;
							}
							else if (current_line == 25 && receive_buffer_length < 79)
							{
								for (k = 26; k < 409; k++)
								{
									for (j = 0; j < 640; j++)
									{
										Vga_Clr_Pixel(VGA_0_BASE, j, k);
									}
								}
								current_line = 2;
								for (i = UDP_PACKET_PAYLOAD_OFFSET; receive_buffer[i] != 0; i++)
									put_vga_char(receive_buffer[i], i-UDP_PACKET_PAYLOAD_OFFSET, current_line);
								current_line++;
							}
							else if (current_line = 24 && receive_buffer_length > 78)
							{
								for (k = 26; k < 409; k++)
								{
									for (j = 0; j < 640; j++)
									{
										Vga_Clr_Pixel(VGA_0_BASE, j, k);
									}
								}
								current_line = 2;
								for (i = UDP_PACKET_PAYLOAD_OFFSET; i < 79+UDP_PACKET_PAYLOAD_OFFSET; i++)
									put_vga_char(receive_buffer[i], i-UDP_PACKET_PAYLOAD_OFFSET, current_line);
								for (i = UDP_PACKET_PAYLOAD_OFFSET+79; receive_buffer[i] != 0; i++)
									put_vga_char(receive_buffer[i], i-UDP_PACKET_PAYLOAD_OFFSET-79, current_line+1);
								current_line++;
								current_line++;
							}
							printf("\n rcvd correct checksum: %hx", checksum);
						}
						else
							put_vga_string("Some slob tried to send you a message but his checksum was wrong.", 0, 26);
							printf("\n rcvd incorrect checksum: %hx", checksum);
					}
				} else {
					printf("Received non-UDP packet\n");
				}
			} else {
Esempio n. 19
0
/**
  * @brief  Receive a file using the ymodem protocol with CRC16.
  * @param  p_size The size of the file.
  * @retval COM_StatusTypeDef result of reception/programming
  */
COM_StatusTypeDef Ymodem_Receive ( uint32_t *p_size )
{
  uint32_t i, packet_length, session_done = 0, file_done, errors = 0, session_begin = 0;
  uint32_t flashdestination, ramsource, filesize;
  uint8_t *file_ptr;
  uint8_t file_size[FILE_SIZE_LENGTH], tmp, packets_received;
  COM_StatusTypeDef result = COM_OK;

  /* Initialize flashdestination variable */
  flashdestination = APPLICATION_ADDRESS;

  while ((session_done == 0) && (result == COM_OK))
  {
    packets_received = 0;
    file_done = 0;
    while ((file_done == 0) && (result == COM_OK))
    {
      switch (ReceivePacket(aPacketData, &packet_length, DOWNLOAD_TIMEOUT))
      {
        case HAL_OK:
          errors = 0;
          switch (packet_length)
          {
            case 2:
              /* Abort by sender */
              Serial_PutByte(ACK);
              result = COM_ABORT;
              break;
            case 0:
              /* End of transmission */
              Serial_PutByte(ACK);
              file_done = 1;
              break;
            default:
              /* Normal packet */
              if (aPacketData[PACKET_NUMBER_INDEX] != packets_received)
              {
                Serial_PutByte(NAK);
              }
              else
              {
                if (packets_received == 0)
                {
                  /* File name packet */
                  if (aPacketData[PACKET_DATA_INDEX] != 0)
                  {
                    /* File name extraction */
                    i = 0;
                    file_ptr = aPacketData + PACKET_DATA_INDEX;
                    while ( (*file_ptr != 0) && (i < FILE_NAME_LENGTH))
                    {
                      aFileName[i++] = *file_ptr++;
                    }

                    /* File size extraction */
                    aFileName[i++] = '\0';
                    i = 0;
                    file_ptr ++;
                    while ( (*file_ptr != ' ') && (i < FILE_SIZE_LENGTH))
                    {
                      file_size[i++] = *file_ptr++;
                    }
                    file_size[i++] = '\0';
                    Str2Int(file_size, &filesize);

                    /* Test the size of the image to be sent */
                    /* Image size is greater than Flash size */
                    if (*p_size > (USER_FLASH_SIZE + 1))
                    {
                      /* End session */
                      tmp = CA;
                      HAL_UART_Transmit(&UartHandle, &tmp, 1, NAK_TIMEOUT);
                      HAL_UART_Transmit(&UartHandle, &tmp, 1, NAK_TIMEOUT);
                      result = COM_LIMIT;
                    }
                    /* erase user application area */
                    FLASH_If_Erase(APPLICATION_ADDRESS);
                    *p_size = filesize;

                    Serial_PutByte(ACK);
                    Serial_PutByte(CRC16);
                  }
                  /* File header packet is empty, end session */
                  else
                  {
                    Serial_PutByte(ACK);
                    file_done = 1;
                    session_done = 1;
                    break;
                  }
                }
                else /* Data packet */
                {
                  ramsource = (uint32_t) & aPacketData[PACKET_DATA_INDEX];

                  /* Write received data in Flash */
                  if (FLASH_If_Write(flashdestination, (uint32_t*) ramsource, packet_length/4) == FLASHIF_OK)                   
                  {
                    flashdestination += packet_length;
                    Serial_PutByte(ACK);
                  }
                  else /* An error occurred while writing to Flash memory */
                  {
                    /* End session */
                    Serial_PutByte(CA);
                    Serial_PutByte(CA);
                    result = COM_DATA;
                  }
                }
                packets_received ++;
                session_begin = 1;
              }
              break;
          }
          break;
        case HAL_BUSY: /* Abort actually */
          Serial_PutByte(CA);
          Serial_PutByte(CA);
          result = COM_ABORT;
          break;
        default:
          if (session_begin > 0)
          {
            errors ++;
          }
          if (errors > MAX_ERRORS)
          {
            /* Abort communication */
            Serial_PutByte(CA);
            Serial_PutByte(CA);
          }
          else
          {
            Serial_PutByte(CRC16); /* Ask for a packet */
          }
          break;
      }
    }
  }
  return result;
}
Esempio n. 20
0
/**
  Write data to a FileDescriptor. On success number of bytes written is returned. Zero indicates
  nothing was written. On error -1 is returned.

  @param  FileDescriptor   Device to talk to.
  @param  Buffer           Buffer to hold Count bytes that are to be written
  @param  Count            Number of bytes to transfer.

  @retval -1               Error
  @retval {other}          Number of bytes written.

**/
INTN
GdbWrite (
  IN  INTN          FileDescriptor,
  OUT CONST VOID    *Buffer,
  IN  UINTN         Count
  )
{
  CHAR8   Packet[128];
  UINTN   Size;
  INTN    RetCode;
  UINTN   ErrNo;
  BOOLEAN ReceiveDone = FALSE;

  // Send:
  // #Fwrite,XX,YYYYYYYY,XX$SS
  //
  // XX - FileDescriptor in ASCII
  // YYYYYYYY - Buffer address in ASCII
  // XX - Count in ASCII
  // SS - check sum
  //
  Size = AsciiSPrint (Packet, sizeof (Packet), "Fwrite,%x,%x,%x", FileDescriptor, Buffer, Count);
  // Packet array is too small if you got this ASSERT
  ASSERT (Size < sizeof (Packet));

  SendPacket (Packet);
  Print ((CHAR16 *)L"Packet sent..\n");

  do {
    // Reply:
    ReceivePacket (Packet, sizeof (Packet));
    Print ((CHAR16 *)L"Command received..%c\n", Packet[0]);

    // Process GDB commands
    switch (Packet[0]) {
      //Read memory command.
      //m addr,length.
      case    'm':
        ReadFromMemory (Packet);
        break;

      //Fretcode, errno, Ctrl-C flag
      //retcode - Count read
      case    'F':
        //Once target receives F reply packet that means the previous
        //transactions are finished.
        ReceiveDone = TRUE;
        break;

      //Send empty buffer
      default    :
        SendNotSupported();
        break;
    }
  } while (ReceiveDone == FALSE);

  RetCode = GdbParseFReplyPacket (Packet, &ErrNo);
  Print ((CHAR16 *)L"RetCode: %x..ErrNo: %x..\n", RetCode, ErrNo);

  //Send error to the host if there is any.
  if (ErrNo > 0) {
    SendError((UINT8)ErrNo);
  }

  return RetCode;
}
Esempio n. 21
0
/*
FUNCTION: ReadFromPort
DATE: 11/28/2015
REVISIONS: v4 12/2/2015 - wait state added
DESIGNER: Allen & Dylan & Thomas
PROGRAMMER: Allen & Dylan
INTERFACE: static DWORD WINAPI ReadFromPort(LPVOID lpParam)
			LPVOID lpParam : parameter passed to the thread; intended to be a communications handle
RETURNS: 1

NOTES: This function is intended to be called on a separate thread.
		It has the event driven code to monitor the serial port for INCOMING communications.
		It will send messages to the main window (via WndProc) for OUTGOING communications.
*/
static DWORD WINAPI ReadFromPort(LPVOID lpParam) {
	OVERLAPPED overlapped = { 0 };
	HANDLE hnd = 0;
	BOOL fWaitingOnRead = FALSE;
	overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	CHAR buffer[PACKETLENGTH] = "";
	DWORD dwEvent;
	SetCommMask(lpParam, EV_RXCHAR);

	while (true) {
		switch (state) {
		// Waiting for ENQ ACKnowledgment
		case WENQACK:
			if (!fWaitingOnRead) {
				if (!WaitCommEvent(lpParam, &dwEvent, &overlapped)) {
					if (GetLastError() == ERROR_IO_PENDING) {
						fWaitingOnRead = TRUE;
					}
				}
			}
			else {
				if (Wait(overlapped.hEvent, TIMEOUT)) {
					if (!ReadFile(lpParam, buffer, 1, NULL, &overlapped)) {
						WaitForSingleObject(overlapped.hEvent, TIMEOUT);
					};

					OutputDebugString("Finished reading in WENQACK\n");
					if (buffer[0] == ACK) {
						SendMessage(hMain, WM_COMMAND, ACK_REC, NULL);
						
					}
					else {
						OutputDebugString("Was not ACK, was ");
						OutputDebugString(buffer);
						OutputDebugString("\n");
						state = WAIT;
					}
					fWaitingOnRead = FALSE;
				}
				else {
					state = IDLE;
				}
			}
			break;
		// Waiting for ACKnowledgment for a packet
		case WACK:
			if (!fWaitingOnRead) {
				if (!WaitCommEvent(lpParam, &dwEvent, &overlapped)) {
					if (GetLastError() == ERROR_IO_PENDING) {
						fWaitingOnRead = TRUE;
					}
				}
			}
			else {
				if (Wait(overlapped.hEvent, TIMEOUT)) {
					ReadFile(lpParam, &buffer, 1, NULL, &overlapped);
					if (buffer[0] == ACK) {
						SendMessage(hMain, WM_COMMAND, ACK_REC, NULL);
						buffer[0] = 0;
					}
					fWaitingOnRead = FALSE;
				}
				else {
					state = WAIT;
				}
			}
			break;
		// a backoff state, can only become a receiver for some time
		case WAIT:
		// default state, can move to sending or receiving
		case IDLE:
			if (!fWaitingOnRead) {
				if ((state == WAIT || state == IDLE) && !WaitCommEvent(lpParam, &dwEvent, &overlapped)) {
					if (GetLastError() == ERROR_IO_PENDING) {
						fWaitingOnRead = TRUE;
					}

				}
			}
			else {
				if ((state == WAIT || state == IDLE) && Wait(overlapped.hEvent, TIMEOUT)) {
					ReadFile(lpParam, &buffer, 1, NULL, &overlapped);
					if (buffer[0] == ENQ) {
						startWriting();
						SendAck(lpParam);
						finishWriting();
						state = RECEIVING;
					}
					// this is what you call a hack to get around race conditions
					else if ((state == WENQACK || state == WACK) && buffer[0] == ACK) {
						SendMessage(hMain, WM_COMMAND, ACK_REC, NULL);
					}
		
					fWaitingOnRead = FALSE;
				}
				else {
					state = IDLE;
				}
			}
			break;
		// anticipating a packet
		case RECEIVING:
			if (!fWaitingOnRead) {
				if (!WaitCommEvent(lpParam, &dwEvent, &overlapped)) {
					if (GetLastError() == ERROR_IO_PENDING) {
						fWaitingOnRead = TRUE;
					}

				}
			}
			else {
				if (Wait(overlapped.hEvent, INFINITE)) {
					receiveBuffer = ReceivePacket(lpParam, overlapped);
					if (ErrorCheck(receiveBuffer) || 1) {
						//DoNonReadingStuff(receiveBuffer);
						Depacketize(receiveBuffer);
						startWriting();
						SendAck(lpParam);
						finishWriting();
						packetsReceived++;
						SetStatistics();
						// open the file for writing and reading

						hnd = CreateFile(FileName, FILE_APPEND_DATA | GENERIC_WRITE | GENERIC_READ, NULL, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
						startWriting();
						if (WritePacketToFile(receiveBuffer, hnd)) {
							UpdateWindowFromFile(hReceive, hnd);
						}
						finishWriting();
						CloseHandle(hnd);

						fWaitingOnRead = FALSE;
						state = IDLE;
						buffer[0] = 0;
						free(receiveBuffer);
					}
				}
				else {
					state = IDLE;
				}
			}
			break;
		}
		// if a packet is in the queue and the process is in idle, attempt to send
		if (state == IDLE && packetBuffer[currentPacket][0] != 0) {
			SendMessage(hMain, WM_COMMAND, ASN_ENQ, NULL);
		}
	}
	return 1;
}
Esempio n. 22
0
/**
 * Reciving singlas from ethernet controller -
 * TX - transmited packet
 * RX - recived packet
 * LinkChange - Connected/Diconncted Ethernet Cable
 *
 */
void ethernet_interrupts_simple()
{
    frame *curr_frame = 0;
	int filtered;
	uint8_t interruption =ior(ISR);    //which interruption

    packet_num++;

    iow(IMR, 0);
 //   iow(IMR, PAR_set);
   // printf("ISR 0x%2X \n",interruption);

    if( interruption & 0x01 )      //RX
    {

    	iow(ISR,0x01);
    	curr_frame = get_free_frame();
    	if(curr_frame == 0)
    	{
    		return; //ERROR no more free frames
    	}

    	aaa=ReceivePacket(curr_frame->f_data,&curr_frame->f_len);
    	if(aaa == 0)
    	{
        	filtered =   filter_packiets(curr_frame->f_data,curr_frame->f_len);

        	if (filtered == 0)
        	{
        		printf(" RX:UDP \n");
        		add_rx_frame(curr_frame);

        	}
        	else if (filtered == 10) //arp
        	{
        		printf(" RX:ARP \n");
        		add_rx_frame(curr_frame);
        	}
        	else
        	{
    			release_frame(curr_frame);
    		}
        	curr_frame = 0;

    	}
    	else
    	{
    		printf("%s Recived Bad Frame \n",__FUNCTION__);

    		release_frame(curr_frame);
    		curr_frame = 0;
    	}

    	/* ethernet_header *tmp = (ethernet_header *) RXT;
    	 ether_addr adres =  { 0x01, 0x60, 0x6E, 0x11, 0x01, 0x1F  };


    	 tmp->eth_src_addr = adres;
         TransmitPacket(RXT,rx_len);*/
    }


    if(interruption & 0x02)    //TX
    {
    	iow(ISR,0x02);
    	tx_control = 0;

    }
    if(interruption & 0x20)    //LinkChange
    {
    	iow(ISR,0x20);

/*    	iow(0x00,0x01);  // software reset
    	usleep(10);
    	  enable interrupts to activate DM9000 ~on
    	  iow(IMR, INTR_set2);    IMR REG. FFH PAR=1 only, or + PTM=1& PRM=1 enable RxTx interrupts
    	  iow(0xFF, 0x80);
    	   enable RX (Broadcast/ ALL_MULTICAST) ~go
    	  iow(RCR , RCR_set | RX_ENABLE | PASS_MULTICAST);   RCR REG. 05 RXEN Bit [0] = 1 to enable the RX machine/ filter */

    	//printf(" LinkCHange \n");
    	if(link_control == 0)
    		link_control = 1;
    	else
    		link_control = 0;
    }




    iow(IMR, INTR_set2);
}
Esempio n. 23
0
void CCommunicator::Parcer(unsigned char ucByteNew)
{
  static enum
  {
    eStateStartMark,
    eStateLength,
    eStateData,
    eStateCRC,
    eStateEndMark
  } parceState = eStateStartMark;

  static TPacket tmsgInput;
  static int iDataRemain;
  static unsigned char *pDataStore;

  switch(parceState)
  {
  case eStateStartMark:
    if(BITBUS_MARK == ucByteNew)
      parceState = eStateLength;
    break;

  case eStateLength:
    if((BITBUS_MARK != ucByteNew)&&         // Для ускорения начальной синхронизации
       ((sizeof(TPacket)-2) >= ucByteNew))  // Ограничение маклимальной длины пакета
    { // Инициация приёма новогопакета
      iDataRemain = ucByteNew;
      tmsgInput.ucLength = ucByteNew;
      pDataStore = &tmsgInput.ucPipeAddress;
      parceState = eStateData;
    }
    break;

  case eStateData:
    *pDataStore++ = ucByteNew;
    if(0 >= --iDataRemain)
      parceState = eStateCRC;
    break;

  case eStateCRC:
    // Поле контрольной суммы пока при обмене по USB не заполняется и не анализируется,
    // просто присоединяется к принятым данным
    *pDataStore++ = ucByteNew;
    parceState = eStateEndMark;
    break;

  case eStateEndMark:
    if(BITBUS_MARK == ucByteNew)
    {
      { // Отправка отладочного сообщения о принятом пакете
        QString strData;
        for( int i=0;i<=(tmsgInput.ucLength - 6); i++)
          {
            strData.append(QString("%1").arg(tmsgInput.ucData[i], 2, 16,QLatin1Char( '0' )));
          }
        qDebug() << endl << "Received packet: <-- " << strData;
      }

      // Отправка сигнала о принятом пакете всем подписчикам
      emit ReceivePacket(tmsgInput);
    }
    else
        qDebug() << endl << "Invalid packet";

    parceState = eStateStartMark; // Переход к ожиданию следующего пакета
    break;

  default:
    parceState = eStateStartMark;
    break;
  }
}
Esempio n. 24
0
Comm::ErrorCode Comm::GetData(unsigned long address, unsigned char bytesPerPacket,
                              unsigned char bytesPerAddress, unsigned char bytesPerWord,
                              unsigned long endAddress, unsigned char *pData)
{
    ReadPacket readPacket;
    WritePacket writePacket;
    ErrorCode result;
    unsigned int percentCompletion;
    unsigned int addressesToFetch = endAddress - address;

    //Error check input parameters before using them
    if((pData == NULL) || (bytesPerAddress == 0) || (address > endAddress) || (bytesPerWord == 0))
    {
        qWarning("Bad parameters specified when calling Program() function.");
        return Fail;
    }

    //Check to avoid possible division by zero when computing the percentage completion status.
    if(addressesToFetch == 0)
        addressesToFetch++;


    if(connected) {
        //First error check the input parameters before using them
        if((pData == NULL) || (endAddress < address) || (bytesPerPacket == 0))
        {
            qWarning("Error, bad parameters provided to call of GetData()");
            return Fail;
        }

        // Continue reading from device until the entire programmable region has been read
        while(address < endAddress)
        {
            //Update the progress bar so the user knows things are happening.
            percentCompletion = 100*((float)1 - (float)((float)(endAddress - address)/(float)addressesToFetch));
            if(percentCompletion > 100)
            {
                percentCompletion = 100;
            }
            //Reformat the percent completion so it "fits" in the 33% to 66% region (since erase
            //"completes" 0%-32% of the total erase/program/verify cycle, and verify completes 67%-100%).
            percentCompletion /= 3;
            percentCompletion += 67;
            emit SetProgressBar(percentCompletion);


            // Set up the buffer packet with the appropriate address and with the get data command
            memset((void*)&writePacket, 0x00, sizeof(writePacket));
            writePacket.command = GET_DATA;
            writePacket.address = address;

            //Debug output info.
            qWarning("Fetching packet with address: 0x%x", (unsigned int)writePacket.address);

            // Calculate to see if the entire buffer can be filled with data, or just partially
            if(((endAddress - address) * bytesPerAddress) < bytesPerPacket)
                // If the amount of bytes left over between current address and end address is less than
                //  the max amount of bytes per packet, then make sure the bytesPerPacket info is updated
                writePacket.bytesPerPacket = (endAddress - address) * bytesPerAddress;
            else
                // Otherwise keep it at its maximum
                writePacket.bytesPerPacket = bytesPerPacket;

            // Send the packet
            result = SendPacket((unsigned char*)&writePacket, sizeof(writePacket));

            // If it wasn't successful, then return with error
            if(result != Success)
            {
                qWarning("Error during verify sending packet with address: 0x%x", (unsigned int)writePacket.address);
                return result;
            }

            // Otherwise, read back the packet from the device
            memset((void*)&readPacket, 0x00, sizeof(readPacket));
            result = ReceivePacket((unsigned char*)&readPacket, sizeof(readPacket));

            // If it wasn't successful, then return with error
            if(result != Success)
            {
                qWarning("Error reading packet with address: 0x%x", (unsigned int)readPacket.address);
                return result;
            }

            // Copy contents from packet to data pointer
            memcpy(pData, readPacket.data + 58 - readPacket.bytesPerPacket, readPacket.bytesPerPacket);

            // Increment data pointer
            pData += readPacket.bytesPerPacket;

            // Increment address by however many bytes were received divided by how many bytes per address
            address += readPacket.bytesPerPacket / bytesPerAddress;
        }

        // if successfully received entire region, return success
        return Success;
    }

    // If not connected, return not connected
    return NotConnected;
}
Esempio n. 25
0
void MainLoop(ALport alp, FileDescriptor dacfd, FileDescriptor sockfd, SynthState *v1, SynthState *v2) {
/*    int hwm = 300, lwm = 256; */
    int hwm = 1000, lwm = 800;
    fd_set read_fds, write_fds;

    /* largest file descriptor to search for */    
    int	nfds = BIGGER_OF(dacfd, sockfd) + 1;

    printf("MainLoop: dacfd %d, sockfd %d, nfds %d\n", dacfd, sockfd, nfds);

    time_to_quit = 0;
    sigset(SIGINT, catch_sigint);       /* set sig handler       */

    while(!time_to_quit) {

	/* compute sine wave samples while the sound output buffer is below
	   the high water mark */

	while (ALgetfilled(alp) < hwm) {
	    Synthesize(alp, v1, v2);
	}

	/* Figure out the time tag corresponding to the time in the future that we haven't
	   computed any samples for yet. */
	OSCInvokeAllMessagesThatAreReady(OSCTT_PlusSeconds(OSCTT_CurrentTime(), 
							   ALgetfilled(alp) / the_sample_rate));

	/* set the low water mark, i.e. when we want control from select(2) */
	ALsetfillpoint(alp, OUTPUTQUEUESIZE - lwm);

	/* set up select */
	FD_ZERO(&read_fds);	/* clear read_fds */
	FD_ZERO(&write_fds);	/* clear write_fds */
	FD_SET(dacfd, &write_fds);
	FD_SET(sockfd, &read_fds); 

	FD_SET(0, &read_fds);	/* stdin */

	/* give control back to OS scheduler to put us to sleep until the DAC
	   queue drains and/or a character is available from standard input */

	if (select(nfds, &read_fds, &write_fds, (fd_set * )0, (struct timeval *)0) < 0) {
	    /* select reported an error */
	    perror("bad select"); 
	    goto quit;
	}

	if(FD_ISSET(sockfd, &read_fds)) {
	    ReceivePacket(sockfd);
	}

	/* is there a character in the queue? */
	if (FD_ISSET(0, &read_fds)) {
	    /* this will never block */
	    char c = getchar();

	    if (c == 'q') {
		/* quit */
		break;
	    } else if ((c <= '9') && (c >= '0')) {
		/* tweak frequency */
		v1->f = 440.0 + 100.0 * (c - '0');
	    }
	}
    }
quit:
    ALcloseport(alp);
    closeudp(sockfd);
}
void MainLogic::SendPacket(BettingInput* betInput)
{
    ReceivePacket(betInput);

}
Esempio n. 27
0
int main(void)
{
    SOCKET ClientSockDesc;       // Kliento pagrindinio soketo-klausytojo deskriptorius.
    char UserInput [BUFFLEN] = {0}; // Masyvas vartotojo komandoms nuskaityti.
    int SendResult;              // Siuntimo funkcijos resultatui saugoti.
    int ReceiveResult;              // Siuntimo funkcijos resultatui saugoti.
    char Packet [BUFFLEN] = {0};    // Buferiu masyvas duomenims gauti.
    int jCounter, i;      // Skaitliukai.
    unsigned int ParseResult;    // Komandu analizes rezultatui saugoti.

    fd_set MainSocketSet, TempSet; //pagrindine soketu aibe; soketu aibe, kuri turi duomenu, paruostu nuskaitymui
    unsigned int MaxKnownSocketDesc, iCounter;// maksimalus deskriptoriu kintamasis (soketo nr), skaitliukas (soket�)
    struct timeval TimeVal; // Laiko struktura dirbti su select().

    WSADATA wsaData;
    if(WSAStartup(0x202, &wsaData) == 0)
    {
    }
    else
    {
        printf("ERROR: Initialization failure.\n");
    }

    if ( INVALID_SOCKET == (ClientSockDesc = InitializeClient ()) )
    {
        printf ("CNLabs Client error: client initialization failed.\n");
        goto EXIT;
    }
    // Inicializuoti soketu aibes.
    FD_ZERO(&MainSocketSet);
    FD_ZERO(&TempSet);

    // Inicializuojame laiko struktura. 0 - reiskia, kad select() funkcija turi blokuotis laukdama, kol atsiras bent vienas aktyvus soketas.
    TimeVal.tv_sec = 10; //sekundes
    TimeVal.tv_usec = 500; //tukstantosios

    FD_SET(ClientSockDesc, &MainSocketSet);
    MaxKnownSocketDesc = ClientSockDesc;

    while ( 1 )
    {
        // Kiekvienoje iteracijoje inicializuokime pagalbine soketu aibe pagrindine.
        TempSet = MainSocketSet;

        // Isrenkame is soketu aibes tuos deskriptorius, kurie apraso soketus, turincius duomenu, paruostu skaitymui.
        //select()tinklo primityvo panaudojimas sinchroniniu budu, kada blokuojamasi laukiant aktyviu soketu, turinciu info, kuria per juos galima skaityti is tinklo.
        //tikrina zemesnius uz pirmuoji nr pazymetus, todel +1, pirmos eiles soketu aibe (2,3 eiles soketu aibe), blokavimas ribota laika
        if ( SOCKET_ERROR == select (MaxKnownSocketDesc + 1, &TempSet, NULL, NULL, &TimeVal) )
        {
            exit(EXIT_FAILURE);
        }

        for ( iCounter = 0; iCounter <= MaxKnownSocketDesc; iCounter++ )
        {
            if (FD_ISSET(iCounter, &TempSet))
            {
                if ( SOCKET_ERROR == ReceivePacket (&ClientSockDesc, Packet) )
                {
                    closesocket (ClientSockDesc);
                    return INVALID_SOCKET;
                }
                UnmarshalPacket (Packet);
                printf ("%s\n", Packet);
            }
            else if(FD_ISSET(0, &TempSet))
            {
                //fflush ( stdin );
                memset (UserInput, 0, sizeof (UserInput));
                fgets (UserInput, sizeof (UserInput), stdin);
                UserInput [strlen (UserInput) - 1] = '\0';
                //ParseCommandInput (UserInput);
                MarshalPacket(UserInput);
                SendPacket (&ClientSockDesc, UserInput,strlen(UserInput));
            }

        }
    }
    closesocket (ClientSockDesc);
EXIT:
    WSACleanup();
    return 1;
}