org.eclipse.californium.core.network.config.NetworkConfig Java Examples

The following examples show how to use org.eclipse.californium.core.network.config.NetworkConfig. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CoapStack.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public CoapStack(NetworkConfig config, Outbox outbox) {
	this.top = new StackTopAdapter();
	this.outbox = outbox;
	
	ReliabilityLayer reliabilityLayer;
	if (config.getBoolean(NetworkConfig.Keys.USE_CONGESTION_CONTROL) == true) {
		reliabilityLayer = CongestionControlLayer.newImplementation(config);
		LOGGER.config("Enabling congestion control: " + reliabilityLayer.getClass().getSimpleName());
	} else {
		reliabilityLayer = new ReliabilityLayer(config);
	}
	
	this.layers = 
			new Layer.TopDownBuilder()
			.add(top)
			.add(new ObserveLayer(config))
			.add(new BlockwiseLayer(config))
			.add(reliabilityLayer)
			.add(bottom = new StackBottomAdapter())
			.create();
	
	// make sure the endpoint sets a MessageDeliverer
}
 
Example #2
Source File: CoapStack.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public CoapStack(NetworkConfig config, Outbox outbox) {
	this.top = new StackTopAdapter();
	this.outbox = outbox;
	
	ReliabilityLayer reliabilityLayer;
	if (config.getBoolean(NetworkConfig.Keys.USE_CONGESTION_CONTROL) == true) {
		reliabilityLayer = CongestionControlLayer.newImplementation(config);
		LOGGER.config("Enabling congestion control: " + reliabilityLayer.getClass().getSimpleName());
	} else {
		reliabilityLayer = new ReliabilityLayer(config);
	}
	
	this.layers = 
			new Layer.TopDownBuilder()
			.add(top)
			.add(new ObserveLayer(config))
			.add(new BlockwiseLayer(config))
			.add(reliabilityLayer)
			.add(bottom = new StackBottomAdapter())
			.create();
	
	// make sure the endpoint sets a MessageDeliverer
}
 
Example #3
Source File: BlockwiseLayer.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Constructs a new blockwise layer.
 * Changes to the configuration are observed and automatically applied.
 * @param config the configuration
 */
public BlockwiseLayer(NetworkConfig config) {
	this.config = config;
	max_message_size = config.getInt(NetworkConfig.Keys.MAX_MESSAGE_SIZE);
	preferred_block_size = config.getInt(NetworkConfig.Keys.PREFERRED_BLOCK_SIZE);
	block_timeout = config.getInt(NetworkConfig.Keys.BLOCKWISE_STATUS_LIFETIME);
	
	LOGGER.config("BlockwiseLayer uses MAX_MESSAGE_SIZE="+max_message_size+", DEFAULT_BLOCK_SIZE="+preferred_block_size+", and BLOCKWISE_STATUS_LIFETIME="+block_timeout);

	observer = new NetworkConfigObserverAdapter() {
		@Override
		public void changed(String key, int value) {
			if (NetworkConfig.Keys.MAX_MESSAGE_SIZE.equals(key))
				max_message_size = value;
			if (NetworkConfig.Keys.PREFERRED_BLOCK_SIZE.equals(key))
				preferred_block_size = value;
			if (NetworkConfig.Keys.BLOCKWISE_STATUS_LIFETIME.equals(key))
				block_timeout = value;
		}
	};
	config.addConfigObserver(observer);
}
 
Example #4
Source File: TestCoapClientTarget.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  int port =  TestHttpClientTarget.getFreePort();
  coapServer = new CoapServer(NetworkConfig.createStandardWithoutFile(), port);
  coapServer.add(new CoapResource("test") {
    @Override
    public void handlePOST(CoapExchange exchange) {
      serverRequested = true;
      if (returnErrorResponse) {
        exchange.respond(CoAP.ResponseCode.INTERNAL_SERVER_ERROR);
        return;
      }
      requestPayload = new String(exchange.getRequestPayload());
      exchange.respond(CoAP.ResponseCode.VALID);
    }
  });
  resourceURl = "coap://localhost:" + port + "/test";
  coapServer.start();
}
 
Example #5
Source File: CoapIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testCoapComponent() throws Exception {
    NetworkConfig.createStandardWithoutFile();

    String coapConsumerUri = String.format("coap://localhost:%d/hello", AvailablePortFinder.getNextAvailable());

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            fromF(coapConsumerUri)
            .convertBodyTo(String.class)
            .setBody(simple("Hello ${body}"));
        }
    });

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        String result = template.requestBody(coapConsumerUri, "Kermit", String.class);
        Assert.assertEquals("Hello Kermit", result);
    } finally {
        camelctx.close();
    }
}
 
Example #6
Source File: CoapReceiverServer.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public List<Stage.ConfigIssue> init(Stage.Context context) {
  List<Stage.ConfigIssue> issues = new ArrayList<>();
  NetworkConfig networkConfig = NetworkConfig.createStandardWithoutFile();
  networkConfig.set(NetworkConfig.Keys.DEDUPLICATOR, NetworkConfig.Keys.NO_DEDUPLICATOR);
  networkConfig.set(NetworkConfig.Keys.PROTOCOL_STAGE_THREAD_COUNT, coAPServerConfigs.maxConcurrentRequests);
  networkConfig.set(NetworkConfig.Keys.NETWORK_STAGE_RECEIVER_THREAD_COUNT, coAPServerConfigs.maxConcurrentRequests);
  if (coAPServerConfigs.networkConfigs != null) {
    for (String key: coAPServerConfigs.networkConfigs.keySet()) {
      networkConfig.set(key, coAPServerConfigs.networkConfigs.get(key));
    }
  }
  coapServer = new CoapServer(networkConfig, coAPServerConfigs.port);
  coapReceiverResource = new CoapReceiverResource(context, receiver, errorQueue);
  coapServer.add(coapReceiverResource);
  coapServer.start();
  return issues;
}
 
Example #7
Source File: SweepDeduplicator.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Iterate through all entries and remove the obsolete ones.
 */
private void sweep() {
	int lifecycle = config.getInt(NetworkConfig.Keys.EXCHANGE_LIFETIME);
	long oldestAllowed = System.currentTimeMillis() - lifecycle;
	
	// Notice that the guarantees from the ConcurrentHashMap guarantee
	// the correctness for this iteration.
	for (Map.Entry<?,Exchange> entry:incommingMessages.entrySet()) {
		Exchange exchange = entry.getValue();
		if (exchange.getTimestamp() < oldestAllowed) {
			//TODO check if exchange of observe relationship is periodically created and sweeped
			LOGGER.finer("Mark-And-Sweep removes "+entry.getKey());
			incommingMessages.remove(entry.getKey());
		}
	}
}
 
Example #8
Source File: SweepDeduplicator.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Iterate through all entries and remove the obsolete ones.
 */
private void sweep() {
	int lifecycle = config.getInt(NetworkConfig.Keys.EXCHANGE_LIFETIME);
	long oldestAllowed = System.currentTimeMillis() - lifecycle;
	
	// Notice that the guarantees from the ConcurrentHashMap guarantee
	// the correctness for this iteration.
	for (Map.Entry<?,Exchange> entry:incommingMessages.entrySet()) {
		Exchange exchange = entry.getValue();
		if (exchange.getTimestamp() < oldestAllowed) {
			//TODO check if exchange of observe relationship is periodically created and sweeped
			LOGGER.finer("Mark-And-Sweep removes "+entry.getKey());
			incommingMessages.remove(entry.getKey());
		}
	}
}
 
Example #9
Source File: BlockwiseLayer.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Constructs a new blockwise layer.
 * Changes to the configuration are observed and automatically applied.
 * @param config the configuration
 */
public BlockwiseLayer(NetworkConfig config) {
	this.config = config;
	max_message_size = config.getInt(NetworkConfig.Keys.MAX_MESSAGE_SIZE);
	preferred_block_size = config.getInt(NetworkConfig.Keys.PREFERRED_BLOCK_SIZE);
	block_timeout = config.getInt(NetworkConfig.Keys.BLOCKWISE_STATUS_LIFETIME);
	
	LOGGER.config("BlockwiseLayer uses MAX_MESSAGE_SIZE="+max_message_size+", DEFAULT_BLOCK_SIZE="+preferred_block_size+", and BLOCKWISE_STATUS_LIFETIME="+block_timeout);

	observer = new NetworkConfigObserverAdapter() {
		@Override
		public void changed(String key, int value) {
			if (NetworkConfig.Keys.MAX_MESSAGE_SIZE.equals(key))
				max_message_size = value;
			if (NetworkConfig.Keys.PREFERRED_BLOCK_SIZE.equals(key))
				preferred_block_size = value;
			if (NetworkConfig.Keys.BLOCKWISE_STATUS_LIFETIME.equals(key))
				block_timeout = value;
		}
	};
	config.addConfigObserver(observer);
}
 
Example #10
Source File: ManagerTradfri.java    From helloiot with GNU General Public License v3.0 6 votes vote down vote up
void connectBridge() {

        DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder();
        builder.setAddress(new InetSocketAddress(0));
        builder.setPskStore(new StaticPskStore(identity, psk.getBytes()));
        DTLSConnector dtlsConnector = new DTLSConnector(builder.build());
        CoapEndpoint.CoapEndpointBuilder coapbuilder = new CoapEndpoint.CoapEndpointBuilder();
        coapbuilder.setConnector(dtlsConnector);
        coapbuilder.setNetworkConfig(NetworkConfig.getStandard());
        coapEndPoint = coapbuilder.build();
    }
 
Example #11
Source File: TradfriGatewayHandler.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void establishConnection() {
    TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);

    this.gatewayURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + DEVICES;
    this.gatewayInfoURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + GATEWAY + "/"
            + GATEWAY_DETAILS;
    try {
        URI uri = new URI(gatewayURI);
        deviceClient = new TradfriCoapClient(uri);
    } catch (URISyntaxException e) {
        logger.error("Illegal gateway URI '{}': {}", gatewayURI, e.getMessage());
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
        return;
    }

    DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder(new InetSocketAddress(0));
    builder.setPskStore(new StaticPskStore(configuration.identity, configuration.preSharedKey.getBytes()));
    dtlsConnector = new DTLSConnector(builder.build(), new InMemoryConnectionStore(100, 60));
    endPoint = new TradfriCoapEndpoint(dtlsConnector, NetworkConfig.getStandard());
    deviceClient.setEndpoint(endPoint);
    updateStatus(ThingStatus.UNKNOWN);

    // schedule a new scan every minute
    scanJob = scheduler.scheduleWithFixedDelay(this::startScan, 0, 1, TimeUnit.MINUTES);
}
 
Example #12
Source File: AbstractVertxBasedCoapAdapter.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Loads Californium configuration properties from a file.
 *
 * @param fileName The absolute path to the properties file.
 * @param networkConfig The configuration to apply the properties to.
 * @return The updated configuration.
 */
protected Future<NetworkConfig> loadNetworkConfig(final String fileName, final NetworkConfig networkConfig) {

    if (fileName != null && !fileName.isEmpty()) {
        getVertx().fileSystem().readFile(fileName, readAttempt -> {
            if (readAttempt.succeeded()) {
                try (InputStream is = new ByteArrayInputStream(readAttempt.result().getBytes())) {
                    networkConfig.load(is);
                } catch (final IOException e) {
                    log.warn("skipping malformed NetworkConfig properties [{}]", fileName);
                }
            } else {
                log.warn("error reading NetworkConfig file [{}]", fileName, readAttempt.cause());
            }
        });
    }
    return Future.succeededFuture(networkConfig);
}
 
Example #13
Source File: ExternalCommandsDriver.java    From SoftwarePilot with MIT License 6 votes vote down vote up
public ExternalCommandsDriver() {
		//ecdLogger.log(Level.FINEST, "In Constructor");
		try {
				NetworkConfig nc = new NetworkConfig();
				cs = new CoapServer(nc); //create a new coapserver
				InetSocketAddress bindToAddress = new InetSocketAddress( LISTEN_PORT);
				cs.addEndpoint(new CoapEndpoint(bindToAddress));//Adds an Endpoint to the server.
				driverPort = bindToAddress.getPort();

				cs.add(new ecdResource());//Add a resource to the server
		}
		catch(Exception e) {
		}



}
 
Example #14
Source File: AbstractVertxBasedCoapAdapter.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private NetworkConfig newDefaultNetworkConfig() {
    final NetworkConfig networkConfig = new NetworkConfig();
    networkConfig.setInt(Keys.PROTOCOL_STAGE_THREAD_COUNT, getConfig().getCoapThreads());
    networkConfig.setInt(Keys.NETWORK_STAGE_RECEIVER_THREAD_COUNT, getConfig().getConnectorThreads());
    networkConfig.setInt(Keys.NETWORK_STAGE_SENDER_THREAD_COUNT, getConfig().getConnectorThreads());
    networkConfig.setInt(Keys.MAX_RESOURCE_BODY_SIZE, getConfig().getMaxPayloadSize());
    networkConfig.setInt(Keys.EXCHANGE_LIFETIME, getConfig().getExchangeLifetime());
    networkConfig.setBoolean(Keys.USE_MESSAGE_OFFLOADING, getConfig().isMessageOffloadingEnabled());
    final int maxConnections = getConfig().getMaxConnections();
    if (maxConnections == 0) {
        final MemoryBasedConnectionLimitStrategy limits = new MemoryBasedConnectionLimitStrategy(MINIMAL_MEMORY, MEMORY_PER_CONNECTION);
        networkConfig.setInt(Keys.MAX_ACTIVE_PEERS, limits.getRecommendedLimit());
    } else {
        networkConfig.setInt(Keys.MAX_ACTIVE_PEERS, maxConnections);
    }
    return networkConfig;
}
 
Example #15
Source File: DeduplicatorFactory.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Creates a new deduplicator according to the specified configuration.
 * @param config the configuration
 * @return the deduplicator
 */
public Deduplicator createDeduplicator(NetworkConfig config) {
	String type = config.getString(NetworkConfig.Keys.DEDUPLICATOR);
	if (NetworkConfig.Keys.DEDUPLICATOR_MARK_AND_SWEEP.equals(type)) return new SweepDeduplicator(config);
	else if (NetworkConfig.Keys.DEDUPLICATOR_CROP_ROTATION.equals(type)) return new CropRotation(config);
	else if (NetworkConfig.Keys.NO_DEDUPLICATOR.equals(type)) return new NoDeduplicator();
	else {
		LOGGER.warning("Unknown deduplicator type: " + type);
		return new NoDeduplicator();
	}
}
 
Example #16
Source File: CoapServer.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Constructs a server with the specified configuration that listens to the
 * specified ports after method {@link #start()} is called.
 *
 * @param config the configuration, if <code>null</code> the configuration returned by
 * {@link NetworkConfig#getStandard()} is used.
 * @param ports the ports to bind to
 */
public CoapServer(NetworkConfig config, int... ports) {
	
	// global configuration that is passed down (can be observed for changes)
	if (config != null) {
		this.config = config;
	} else {
		this.config = NetworkConfig.getStandard();
	}
	
	// resources
	this.root = createRoot();
	this.deliverer = new ServerMessageDeliverer(root);
	
	CoapResource well_known = new CoapResource(".well-known");
	well_known.setVisible(false);
	well_known.add(new DiscoveryResource(root));
	root.add(well_known);
	
	// endpoints
	this.endpoints = new ArrayList<Endpoint>();
	// sets the central thread pool for the protocol stage over all endpoints
	this.executor = Executors.newScheduledThreadPool( config.getInt(NetworkConfig.Keys.PROTOCOL_STAGE_THREAD_COUNT) );
	// create endpoint for each port
	for (int port:ports)
		addEndpoint(new CoapEndpoint(port, this.config));
}
 
Example #17
Source File: CoapServer.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Starts the server by starting all endpoints this server is assigned to.
 * Each endpoint binds to its port. If no endpoint is assigned to the
 * server, an endpoint is started on the port defined in the config.
 */
@Override
public void start() {
	
	LOGGER.info("Starting server");
	
	if (endpoints.isEmpty()) {
		// servers should bind to the configured port (while clients should use an ephemeral port through the default endpoint)
		int port = config.getInt(NetworkConfig.Keys.COAP_PORT);
		LOGGER.info("No endpoints have been defined for server, setting up server endpoint on default port " + port);
		addEndpoint(new CoapEndpoint(port, this.config));
	}
	
	int started = 0;
	for (Endpoint ep:endpoints) {
		try {
			ep.start();
			// only reached on success
			++started;
		} catch (IOException e) {
			LOGGER.severe(e.getMessage() + " at " + ep.getAddress());
		}
	}
	if (started==0) {
		throw new IllegalStateException("None of the server endpoints could be started");
	}
}
 
Example #18
Source File: RemoteEndpoint.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public RemoteEndpoint(int remotePort, InetAddress remoteAddress, NetworkConfig config){
	Address = remoteAddress;
	Port = remotePort;
	
	// Fill Array with initial values
	overallRTO = new long[RTOARRAYSIZE];
	for(int i=0; i < RTOARRAYSIZE; i++){
		overallRTO[i] = config.getInt(NetworkConfig.Keys.ACK_TIMEOUT) ;
	}
	currentRTO =  config.getInt(NetworkConfig.Keys.ACK_TIMEOUT);

	xRTO = new long[3];
	xRTT = new long[3];
	xRTTVAR = new long[3];
	RTOupdateTimestamp = new long[3];	
	
	for(int i=0; i <= 2; i++){
		setEstimatorValues(config.getInt(NetworkConfig.Keys.ACK_TIMEOUT), 0, 0, i);
		setRTOtimestamp(System.currentTimeMillis(), i);
	}
	meanOverallRTO = config.getInt(NetworkConfig.Keys.ACK_TIMEOUT);
	
	currentArrayElement = 0;
	nonConfirmableCounter = 7;
	
	usesBlindEstimator = true;
	isBlindStrong = true;
	isBlindWeak = true;
	
	processingNON = false;
	
	exchangeInfoMap = new ConcurrentHashMap<Exchange, exchangeInfo>();

	confirmableQueue = new LinkedList<Exchange>();
    nonConfirmableQueue = new LinkedList<Exchange>();
}
 
Example #19
Source File: CoapServer.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Starts the server by starting all endpoints this server is assigned to.
 * Each endpoint binds to its port. If no endpoint is assigned to the
 * server, an endpoint is started on the port defined in the config.
 */
@Override
public void start() {
	
	LOGGER.info("Starting server");
	
	if (endpoints.isEmpty()) {
		// servers should bind to the configured port (while clients should use an ephemeral port through the default endpoint)
		int port = config.getInt(NetworkConfig.Keys.COAP_PORT);
		LOGGER.info("No endpoints have been defined for server, setting up server endpoint on default port " + port);
		addEndpoint(new CoapEndpoint(port, this.config));
	}
	
	int started = 0;
	for (Endpoint ep:endpoints) {
		try {
			ep.start();
			// only reached on success
			++started;
		} catch (IOException e) {
			LOGGER.severe(e.getMessage() + " at " + ep.getAddress());
		}
	}
	if (started==0) {
		throw new IllegalStateException("None of the server endpoints could be started");
	}
}
 
Example #20
Source File: Cocoa.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * CoCoA applies a variable backoff factor (VBF) to retransmissions, depending on the RTO value of the first transmission
 * of the CoAP request.
 * @param rto the initial RTO
 * @return the new VBF
 */
public double calculateVBF(long rto) {
	if (rto > UPPERVBFLIMIT) {
		return VBFHIGH;
	}
	if (rto < LOWERVBFLIMIT) {
		return VBFLOW;
	}
	return config.getFloat(NetworkConfig.Keys.ACK_TIMEOUT_SCALE);
}
 
Example #21
Source File: CoapEndpoint.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Instantiates a new endpoint with the specified connector and
 * configuration.
 *
 * @param connector the connector
 * @param config the config
 */
public CoapEndpoint(Connector connector, NetworkConfig config) {
	this.config = config;
	this.connector = connector;
	this.serializer = new Serializer();
	this.matcher = new Matcher(config);		
	this.coapstack = new CoapStack(config, new OutboxImpl());
	this.connector.setRawDataReceiver(new InboxImpl());
}
 
Example #22
Source File: DeduplicatorFactory.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Creates a new deduplicator according to the specified configuration.
 * @param config the configuration
 * @return the deduplicator
 */
public Deduplicator createDeduplicator(NetworkConfig config) {
	String type = config.getString(NetworkConfig.Keys.DEDUPLICATOR);
	if (NetworkConfig.Keys.DEDUPLICATOR_MARK_AND_SWEEP.equals(type)) return new SweepDeduplicator(config);
	else if (NetworkConfig.Keys.DEDUPLICATOR_CROP_ROTATION.equals(type)) return new CropRotation(config);
	else if (NetworkConfig.Keys.NO_DEDUPLICATOR.equals(type)) return new NoDeduplicator();
	else {
		LOGGER.warning("Unknown deduplicator type: " + type);
		return new NoDeduplicator();
	}
}
 
Example #23
Source File: CropRotation.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public CropRotation(NetworkConfig config) {
	this.rotation = new Rotation();
	maps = new ExchangeMap[3];
	maps[0] = new ExchangeMap();
	maps[1] = new ExchangeMap();
	maps[2] = new ExchangeMap();
	first = 0;
	second = 1;
	period = config.getInt(NetworkConfig.Keys.CROP_ROTATION_PERIOD);
}
 
Example #24
Source File: ReliabilityLayer.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Constructs a new reliability layer.
 * Changes to the configuration are observed and automatically applied.
 * @param config the configuration
 */
public ReliabilityLayer(NetworkConfig config) {
	this.config = config;
	ack_timeout = config.getInt(NetworkConfig.Keys.ACK_TIMEOUT);
	ack_random_factor = config.getFloat(NetworkConfig.Keys.ACK_RANDOM_FACTOR);
	ack_timeout_scale = config.getFloat(NetworkConfig.Keys.ACK_TIMEOUT_SCALE);
	max_retransmit = config.getInt(NetworkConfig.Keys.MAX_RETRANSMIT);
	
	LOGGER.config("ReliabilityLayer uses ACK_TIMEOUT="+ack_timeout+", ACK_RANDOM_FACTOR="+ack_random_factor+", and ACK_TIMEOUT_SCALE="+ack_timeout_scale);

	observer = new NetworkConfigObserverAdapter() {
		@Override
		public void changed(String key, int value) {
			if (NetworkConfig.Keys.ACK_TIMEOUT.equals(key))
				ack_timeout = value;
			if (NetworkConfig.Keys.MAX_RETRANSMIT.equals(key))
				max_retransmit = value;
		}
		@Override
		public void changed(String key, float value) {
			if (NetworkConfig.Keys.ACK_RANDOM_FACTOR.equals(key))
				ack_random_factor = value;
			if (NetworkConfig.Keys.ACK_TIMEOUT_SCALE.equals(key))
				ack_timeout_scale = value;
		}
	};
	config.addConfigObserver(observer);
}
 
Example #25
Source File: CongestionControlLayer.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Constructs a new congestion control layer.
 * @param config the configuration
 */
public CongestionControlLayer(NetworkConfig config) {
	super(config);
	this.config = config;
    this.remoteEndpointmanager = new RemoteEndpointManager(config);
    setDithering(false);
}
 
Example #26
Source File: CongestionControlLayer.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * The following method overrides the method provided by the reliability layer to include the advanced RTO calculation values
 * when determining the RTO.
 */
@Override
protected void prepareRetransmission(Exchange exchange, RetransmissionTask task) {
	int timeout;
	//System.out.println("TXCount: " + exchange.getFailedTransmissionCount());
	if (exchange.getFailedTransmissionCount() == 0) {
		timeout = (int)getRemoteEndpoint(exchange).getRTO();	
		if(appliesDithering()){
			//TODO: Workaround to force CoCoA (-Strong) not to use the same RTO after backing off several times
			//System.out.println("Applying dithering, matching RTO");
			getRemoteEndpoint(exchange).matchCurrentRTO();
			timeout = (int)getRemoteEndpoint(exchange).getRTO();
			// Apply dithering by randomly choosing RTO from [RTO, RTO * 1.5]
			float ack_random_factor = config.getFloat(NetworkConfig.Keys.ACK_RANDOM_FACTOR);
			timeout = getRandomTimeout(timeout, (int) (timeout*ack_random_factor));
		}
		//System.out.println("meanrto:" + timeout + ";" + System.currentTimeMillis());
	} else {
			int tempTimeout= (int)(getRemoteEndpoint(exchange).getExchangeVBF(exchange) * exchange.getCurrentTimeout());
			timeout = (tempTimeout < MAX_RTO) ? tempTimeout : MAX_RTO;
			getRemoteEndpoint(exchange).setCurrentRTO(timeout);
			//System.out.println("RTX");
	}
	exchange.setCurrentTimeout(timeout);
	//expectedmaxduration = calculateMaxTransactionDuration(exchange); //FIXME what was this for?
	//System.out.println("Sending MSG (timeout;timestamp:" + timeout + ";" + System.currentTimeMillis() + ")");
	ScheduledFuture<?> f = executor.schedule(task , timeout, TimeUnit.MILLISECONDS);
	exchange.setRetransmissionHandle(f);	
}
 
Example #27
Source File: CongestionControlLayer.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static CongestionControlLayer newImplementation(NetworkConfig config) {
	final String implementation = config.getString(NetworkConfig.Keys.CONGESTION_CONTROL_ALGORITHM);
	if ("Cocoa".equals(implementation)) return new Cocoa(config);
	else if ("CocoaStrong".equals(implementation)) return new CocoaStrong(config);
	else if ("BasicRto".equals(implementation)) return new BasicRto(config);
	else if ("LinuxRto".equals(implementation)) return new LinuxRto(config);
	else if ("PeakhopperRto".equals(implementation)) return new PeakhopperRto(config);
	else {
		LOGGER.config("Unknown CONGESTION_CONTROL_ALGORITHM (" + implementation + "), using Cocoa");
		return new Cocoa(config);
	}
}
 
Example #28
Source File: Cocoa.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * CoCoA applies a variable backoff factor (VBF) to retransmissions, depending on the RTO value of the first transmission
 * of the CoAP request.
 * @param rto the initial RTO
 * @return the new VBF
 */
public double calculateVBF(long rto) {
	if (rto > UPPERVBFLIMIT) {
		return VBFHIGH;
	}
	if (rto < LOWERVBFLIMIT) {
		return VBFLOW;
	}
	return config.getFloat(NetworkConfig.Keys.ACK_TIMEOUT_SCALE);
}
 
Example #29
Source File: RemoteEndpoint.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public RemoteEndpoint(int remotePort, InetAddress remoteAddress, NetworkConfig config){
	Address = remoteAddress;
	Port = remotePort;
	
	// Fill Array with initial values
	overallRTO = new long[RTOARRAYSIZE];
	for(int i=0; i < RTOARRAYSIZE; i++){
		overallRTO[i] = config.getInt(NetworkConfig.Keys.ACK_TIMEOUT) ;
	}
	currentRTO =  config.getInt(NetworkConfig.Keys.ACK_TIMEOUT);

	xRTO = new long[3];
	xRTT = new long[3];
	xRTTVAR = new long[3];
	RTOupdateTimestamp = new long[3];	
	
	for(int i=0; i <= 2; i++){
		setEstimatorValues(config.getInt(NetworkConfig.Keys.ACK_TIMEOUT), 0, 0, i);
		setRTOtimestamp(System.currentTimeMillis(), i);
	}
	meanOverallRTO = config.getInt(NetworkConfig.Keys.ACK_TIMEOUT);
	
	currentArrayElement = 0;
	nonConfirmableCounter = 7;
	
	usesBlindEstimator = true;
	isBlindStrong = true;
	isBlindWeak = true;
	
	processingNON = false;
	
	exchangeInfoMap = new ConcurrentHashMap<Exchange, exchangeInfo>();

	confirmableQueue = new LinkedList<Exchange>();
    nonConfirmableQueue = new LinkedList<Exchange>();
}
 
Example #30
Source File: CoapEndpoint.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Instantiates a new endpoint with the specified connector and
 * configuration.
 *
 * @param connector the connector
 * @param config the config
 */
public CoapEndpoint(Connector connector, NetworkConfig config) {
	this.config = config;
	this.connector = connector;
	this.serializer = new Serializer();
	this.matcher = new Matcher(config);		
	this.coapstack = new CoapStack(config, new OutboxImpl());
	this.connector.setRawDataReceiver(new InboxImpl());
}