Skip to content
Snippets Groups Projects
sendDefinition.mustache 2.32 KiB
private Runnable {{parentTypeName}}.{{sender}} = null;
private byte[] {{parentTypeName}}.{{lastValue}} = null;

public boolean {{parentTypeName}}.{{connectMethod}}(String {{connectParameterName}}, boolean writeCurrentValue) throws java.io.IOException {
  {{>handleUri}}
  switch (scheme) {
  {{#usesMqtt}}
    case "mqtt":
      final MqttHandler handler = {{mqttHandlerAttribute}}().resolveHandler(uri);
      final String topic = {{mqttHandlerAttribute}}().extractTopic(uri);
      {{sender}} = () -> {
        {{#loggingEnabledForWrites}}
        System.out.println("[Send] {{tokenName}} = " + get{{tokenName}}() + " -> " + {{connectParameterName}});
        {{/loggingEnabledForWrites}}
        handler.publish(topic, {{lastValue}});
      };
      {{updateMethod}}();
      if (writeCurrentValue) {
        {{writeMethod}}();
      }
      break;
  {{/usesMqtt}}
  {{#usesRest}}
    case "rest":
      ConnectToken connectToken = {{restHandlerAttribute}}().newGETConnection(uri, () -> {
        {{updateMethod}}();
        return new String({{lastValue}});
      });
      if (connectToken == null) {
        return false;
      }
      connectTokens.computeIfAbsent(this, astNode -> new java.util.HashMap<java.net.URI, ConnectToken>())
                   .put(uri, connectToken);
      break;
  {{/usesRest}}
    default:
      System.err.println("Unknown protocol '" + scheme + "'.");
      return false;
  }
  return true;
}

public boolean {{parentTypeName}}.{{disconnectMethod}}(String {{connectParameterName}}) throws java.io.IOException {
  {{>handleUri}}
  switch (scheme) {
  {{#usesMqtt}}
    case "mqtt":
      {{sender}} = null;
      {{lastValue}} = null;
      break;
  {{/usesMqtt}}
  {{#usesRest}}
    case "rest":
      {{restHandlerAttribute}}().disconnect(connectTokens.get(this).get(uri));
      break;
  {{/usesRest}}
    default:
      System.err.println("Unknown protocol '" + scheme + "'.");
      return false;
  }
  return true;
}

protected boolean {{parentTypeName}}.{{updateMethod}}() {
  {{^shouldSendValue}}
  {{tokenResetMethod}}();
  {{/shouldSendValue}}
  {{> mappingApplication}}
  {{lastValue}} = {{lastResult}};
  // normally we would return true here. unless no connect method was called so far to initialize {{sender}} yet