コード例 #1
0
ファイル: main.c プロジェクト: snow4life/PicHomeAutomation
void main(void)
{
	/* Configure the oscillator for the device */
	ConfigureOscillator();



	/* Initialize I/O and Peripherals for application */
	 InitApp();

	W5200_nRESET = 0;
	__delay_us(5);
	W5200_nRESET = 1;
	__delay_ms(50);
	__delay_ms(50);
	__delay_ms(50);
	__delay_ms(50);
	
	/* Initialize application settings */
	InitSettings();
	
	/* Initialize TCP server */
	initServer(&macAddress, &gateway, &netmask);
	startServer(&localEndpoint);

        LED = 1;

    while(1)
    {
		if(clientConnected())
		{
			if(dataAvailable())
			{
				uint16_t length = getReceivedLength();
				if(length > MAX_BUFFER)
				{
					// Limit maximum buffer size to avoid ram saturation due to packet flooding, a normal communication is shorter anyway
					length = MAX_BUFFER;
				}
				
				uint8_t buffer[MAX_BUFFER];
				getReceivedData(buffer, length);
				
				parseCommand(buffer[0], buffer, length);
				
				stopServer();
				startServer(&localEndpoint);
			}
			checkClientDisconnection();
		}		
    }

}
コード例 #2
0
ファイル: multi_server.cpp プロジェクト: ch2i/RadioHead
/* ======================================================================
Function: main
Purpose : not sure ;)
Input   : command line parameters
Output  : -
Comments: -
====================================================================== */
int main (int argc, const char* argv[] )
{
  // LED blink ms timer saving
  unsigned long led_blink[NB_MODULES] = {0,0,0};
  
  // caught CTRL-C to do clean-up
  signal(SIGINT, sig_handler);
  
  // Display app name
  printf( "%s\n", __BASEFILE__);
  for (uint8_t i=0; i<strlen(__BASEFILE__); i++) {
    printf( "=");
  }
  printf("\n");

  // Init GPIO bcm
  if (!bcm2835_init()) {
    fprintf( stderr, "bcm2835_init() Failed\n\n" );
    return 1;
  }

  //save driver instances pointer
  drivers[IDX_MOD1] = &rf95_1;
  drivers[IDX_MOD2] = &rf95_2;
  drivers[IDX_MOD3] = &rf69_3;

  // light onboard LEDs 
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);

  // configure all modules I/O CS pins to 1 before anything else
  // to avoid any problem with SPI sharing
  for (uint8_t i=0 ; i<NB_MODULES; i++) {
    // CS Ping as output and set to 1
    pinMode(CSN_pins[i], OUTPUT);
    digitalWrite(CSN_pins[i], HIGH);
  }

  // configure all modules I/O pins 
  for (uint8_t i=0 ; i<NB_MODULES; i++) {
    // configure all modules
    if (!initRadioModule(i)){
      force_exit = true;
    }
  }

  // All init went fine, continue specific init if any
  if (!force_exit) {
    // Set all modules in receive mode
    rf95_1.setModeRx();
    rf95_2.setModeRx();
    rf69_3.setModeRx();
    printf( "Listening for incoming packets...\n" );
  }

  // Begin the main loop code 
  // ========================
  while (!force_exit) { 
    // Loop thru modules
    for (uint8_t idx=0 ; idx<NB_MODULES ; idx++) {
      // Rising edge fired ?
      if (bcm2835_gpio_eds(IRQ_pins[idx])) {
        // Now clear the eds flag by setting it to 1
        bcm2835_gpio_set_eds(IRQ_pins[idx]);
        //printf("Packet Received, Rising event detect for pin GPIO%d\n", IRQ_pins[idx]);
  
        // Start associated led blink
        led_blink[idx] = millis();
        digitalWrite(LED_pins[idx], HIGH);
        getReceivedData(idx); 
      } // has IRQ

      // A module led blink timer expired ? Light off
      if (led_blink[idx] && millis()-led_blink[idx]>LED_BLINK_MS) {
        led_blink[idx] = 0;
        digitalWrite(LED_pins[idx], LOW);
      } // Led timer expired

      getReceivedData(idx); 

    } // For Modules
    
    // On board led blink (500ms off / 500ms On)
    digitalWrite(LED_PIN, (millis()%1000)<500?LOW:HIGH);

    // Let OS doing other tasks
    // For timed critical appliation receiver, you can reduce or delete
    // this delay, but this will charge CPU usage, take care and monitor
    bcm2835_delay(5);
  }

  // We're here because we need to exit, do it clean
  // Light off on board LED
  digitalWrite(LED_PIN, LOW);
  // All module LEDs off, all modules CS line High
  for (uint8_t i=0 ; i<NB_MODULES; i++) {
    digitalWrite(LED_pins[i], LOW);
    digitalWrite(CSN_pins[i], HIGH);
  }
  printf( "\n%s, done my job!\n", __BASEFILE__ );
  bcm2835_close();
  return 0;
}
コード例 #3
0
void UpnpPortMapping::mapPort(const std::string& gateway, const std::string& client, uint16_t port, PortType type, bool enable)
{
	{
		std::lock_guard<std::mutex> guard(state->stateMutex);

		for (auto it = state->pendingRequests.begin(); it != state->pendingRequests.end(); it++)
		{
			if ((*it)->getHostname() == gateway)
			{
				UpnpMappingState::TodoMapping todo;
				todo.mapping = { gateway, port, type };
				todo.client = client;
				todo.enable = enable;
				todo.blockingStream = (*it).get();
				state->waitingMapping.push_back(todo);
				return;
			}
		}	
	}

	std::string portStr = std::to_string(port);
	std::string portType = type == PortType::Tcp ? "TCP" : "UDP";

	auto request = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
		"<s:Envelope xmlns:s =\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n"
		"<s:Body>\n"
		"<u:AddPortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\n"
		"<NewRemoteHost></NewRemoteHost>\n"
		"<NewExternalPort>" + portStr + "</NewExternalPort>\n"
		"<NewProtocol>" + portType + "</NewProtocol>\n"
		"<NewInternalPort>" + portStr + "</NewInternalPort>\n"
		"<NewInternalClient>" + client + "</NewInternalClient>\n"
		"<NewEnabled>" + std::string(enable ? "1" : "0") + "</NewEnabled>\n"
		"<NewPortMappingDescription>mtTorrent UPnP " + portStr + " " + portType + "</NewPortMappingDescription>\n"
		"<NewLeaseDuration>0</NewLeaseDuration>\n"
		"</u:AddPortMapping>\n"
		"</s:Body>\n"
		"</s:Envelope>\r\n";

	auto httpHeader = createUpnpHttpHeader(gateway + ":1900", request.length(), "urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping");

	auto stream = std::make_shared<TcpAsyncStream>(io);
	state->pendingRequests.push_back(stream);
	auto streamPtr = stream.get();
	auto upnpState = state;

	stream->onConnectCallback = [streamPtr, httpHeader, request]()
	{
		DataBuffer buffer;	
		buffer.assign(httpHeader.begin(), httpHeader.end());
		buffer.insert(buffer.end(), request.begin(), request.end());

		streamPtr->write(buffer);
	};

	stream->onReceiveCallback = [streamPtr, upnpState, gateway, port, type]()
	{
		auto data = streamPtr->getReceivedData();
		auto header = HttpHeaderInfo::readFromBuffer(data);

		if (header.valid && data.size() >= (header.dataStart + header.dataSize))
		{
			streamPtr->consumeData(header.dataStart + header.dataSize);

			std::lock_guard<std::mutex> guard(upnpState->stateMutex);

			if (header.success)
			{
				upnpState->mappedPorts.push_back({ gateway, port, type });
			}
		}
	};

	stream->onCloseCallback = [streamPtr, upnpState, this](int code)
	{
		{
			std::lock_guard<std::mutex> guard(upnpState->stateMutex);

			for (auto it = upnpState->pendingRequests.begin(); it != upnpState->pendingRequests.end(); it++)
			{
				if ((*it).get() == streamPtr)
				{
					upnpState->pendingRequests.erase(it);
					break;
				}
			}
		}

		if (upnpState->active)
		{
			checkPendingMapping(streamPtr);
		}
	};

	stream->connect(gateway, 1900);
}
コード例 #4
0
void UpnpPortMapping::unmapPort(const std::string& gateway, uint16_t port, PortType type)
{
	std::string portStr = std::to_string(port);
	std::string portType = type == PortType::Tcp ? "TCP" : "UDP";

	auto request = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
		"<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\n"
		"<s:Body>\n"
		"<u:DeletePortMapping xmlns:u=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\n"
		"<NewRemoteHost></NewRemoteHost>\n"
		"<NewProtocol>" + portType + "</NewProtocol>\n"
		"<NewExternalPort>" + portStr + "</NewExternalPort>\n"
		"</u:DeletePortMapping>\n"
		"</s:Body>\n"
		"</s:Envelope>\r\n";

	auto httpHeader = createUpnpHttpHeader(gateway + ":1900", request.length(), "urn:schemas-upnp-org:service:WANIPConnection:1#DeletePortMapping");

	auto stream = std::make_shared<TcpAsyncStream>(io);
	auto streamPtr = stream.get();
	state->pendingRequests.push_back(stream);
	auto upnpState = state;

	stream->onConnectCallback = [streamPtr, upnpState, httpHeader, request]()
	{
		DataBuffer buffer;
		buffer.assign(httpHeader.begin(), httpHeader.end());
		buffer.insert(buffer.end(), request.begin(), request.end());

		std::lock_guard<std::mutex> guard(upnpState->stateMutex);
		streamPtr->write(buffer);
	};

	stream->onReceiveCallback = [streamPtr, upnpState, gateway, port, type]()
	{
		auto data = streamPtr->getReceivedData();
		auto header = HttpHeaderInfo::readFromBuffer(data);

		if (header.valid && data.size() >= (header.dataStart + header.dataSize))
		{
			streamPtr->consumeData(header.dataStart + header.dataSize);

			std::lock_guard<std::mutex> guard(upnpState->stateMutex);

			if (header.success)
			{
				for (auto it = upnpState->mappedPorts.begin(); it != upnpState->mappedPorts.end(); it++)
				{
					if (it->gateway == gateway && it->port == port && it->type == type)
					{
						upnpState->mappedPorts.erase(it);
						break;
					}
				}
			}
		}
	};

	stream->onCloseCallback = [streamPtr, upnpState](int code)
	{
		std::lock_guard<std::mutex> guard(upnpState->stateMutex);

		for (auto it = upnpState->pendingRequests.begin(); it != upnpState->pendingRequests.end(); it++)
		{
			if ((*it).get() == streamPtr)
			{
				upnpState->pendingRequests.erase(it);
				break;
			}
		}
	};

	stream->connect(gateway, 1900);
}