/**
 * Copyright (c) 2010-2020 Contributors to the openHAB project
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0
 *
 * SPDX-License-Identifier: EPL-2.0
 */

 /* ***********************************************************
 * This file was automatically generated on 2022-01-03.      *
 *                                                           *
 * openHAB Bindings Version 2.0.0                            *
 *                                                           *
 * If you have a bugfix for this file and want to commit it, *
 * please fix the bug in the generator. You can find a link  *
 * to the generators git repository on tinkerforge.com       *
 *************************************************************/

package org.openhab.binding.tinkerforge.internal.device;

import java.net.URI;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import org.eclipse.smarthome.config.core.Configuration;
import org.eclipse.smarthome.config.core.ConfigDescription;
import org.eclipse.smarthome.config.core.ConfigDescriptionBuilder;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameter.Type;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameterBuilder;
import org.eclipse.smarthome.config.core.ConfigDescriptionParameterGroup;
import org.eclipse.smarthome.config.core.ParameterOption;
import org.eclipse.smarthome.core.types.State;
import org.eclipse.smarthome.core.types.StateOption;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.CommandDescriptionBuilder;
import org.eclipse.smarthome.core.types.CommandOption;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.binding.BaseThingHandler;
import org.eclipse.smarthome.core.thing.type.ChannelDefinitionBuilder;
import org.eclipse.smarthome.core.thing.type.ChannelType;
import org.eclipse.smarthome.core.thing.type.ChannelTypeBuilder;
import org.eclipse.smarthome.core.thing.type.ChannelTypeUID;
import org.eclipse.smarthome.core.types.RefreshType;
import org.eclipse.smarthome.core.thing.type.ThingType;
import org.eclipse.smarthome.core.thing.type.ThingTypeBuilder;
import org.eclipse.smarthome.core.types.StateDescriptionFragmentBuilder;
import org.openhab.binding.tinkerforge.internal.TinkerforgeBindingConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.eclipse.smarthome.core.library.types.DecimalType;
import org.eclipse.smarthome.core.library.types.QuantityType;
import org.eclipse.smarthome.core.library.unit.MetricPrefix;
import org.eclipse.smarthome.core.library.unit.SIUnits;
import org.eclipse.smarthome.core.library.unit.SmartHomeUnits;
import org.eclipse.smarthome.core.thing.CommonTriggerEvents;
import org.eclipse.smarthome.core.library.types.OnOffType;
import org.eclipse.smarthome.core.library.types.StringType;

import com.tinkerforge.BrickDC;
import com.tinkerforge.IPConnection;
import com.tinkerforge.TinkerforgeException;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;

/**
 * Wraps the Java Bindings of the DC Brick.
 * @author Erik Fleckstein - Initial contribution
 */
@NonNullByDefault
public class BrickDCWrapper extends BrickDC implements DeviceWrapper {
    public static final DeviceInfo DEVICE_INFO = new DeviceInfo(BrickDC.DEVICE_DISPLAY_NAME, "brickdc", BrickDC.DEVICE_IDENTIFIER, BrickDCWrapper.class, BrickDCActions.class, "2.3.5", false);

    public BrickDCWrapper(String uid, IPConnection ipcon) {
        super(uid, ipcon);
    }

    private List<ScheduledFuture<?>> manualChannelUpdates = new ArrayList<>();
    private List<ListenerReg<?>> listenerRegs = new ArrayList<>();

    public void cancelManualUpdates() {
        manualChannelUpdates.forEach(f -> f.cancel(true));
    }

    public <T> T reg(T listener, Consumer<T> toRemove) {
        listenerRegs.add(new ListenerReg<T>(listener, toRemove));
        return listener;
    }

    
    private final Logger logger = LoggerFactory.getLogger(BrickDCWrapper.class);

    @Override
    public void initialize(org.eclipse.smarthome.config.core.Configuration config, Function<String, org.eclipse.smarthome.config.core.Configuration> getChannelConfigFn, BiConsumer<String, org.eclipse.smarthome.core.types.State> updateStateFn, BiConsumer<String, String> triggerChannelFn, ScheduledExecutorService scheduler, BaseThingHandler handler) throws TinkerforgeException {
        this.setResponseExpectedAll(true);
        BrickDCConfig cfg = (BrickDCConfig) config.as(BrickDCConfig.class);
        this.addVelocityReachedListener(this.reg((velocity) -> {if(true) {triggerChannelFn.accept("BrickDCVelocityReached", transformBrickDCVelocityReachedCallback0(velocity, cfg));}}, this::removeVelocityReachedListener));
		this.addEmergencyShutdownListener(this.reg(() -> {if(true) {triggerChannelFn.accept("BrickDCEmergencyShutdown", transformBrickDCEmergencyShutdownCallback0(cfg));}}, this::removeEmergencyShutdownListener));
		this.addUnderVoltageListener(this.reg((voltage) -> {if(true) {triggerChannelFn.accept("BrickDCUnderVoltage", transformBrickDCUnderVoltageCallback0(voltage, cfg));}}, this::removeUnderVoltageListener));
		this.addCurrentVelocityListener(this.reg((velocity) -> {if(true) {updateStateFn.accept("BrickDCCurrentVelocity", transformBrickDCCurrentVelocityCallback0(velocity, cfg));}}, this::removeCurrentVelocityListener));
        this.setMinimumVoltage((int)(cfg.minimumVoltage.doubleValue() * 1000.0));
		if(cfg.statusLEDConfig) {
		                this.enableStatusLED();
		            } else {
		                this.disableStatusLED();
		            }
		this.setSPITFPBaudrateConfig(cfg.spitfpEnableDynamicBaudrate, cfg.spitfpMinimumDynamicBaudrate);
		this.setSPITFPBaudrate('a', cfg.spitfpBaudratePortA);
		            this.setSPITFPBaudrate('b', cfg.spitfpBaudratePortB);
		{
		BrickDCCurrentVelocityConfig channelCfg = getChannelConfigFn.apply("BrickDCCurrentVelocity").as(BrickDCCurrentVelocityConfig.class);
		this.setCurrentVelocityPeriod(channelCfg.updateInterval);
		}
		{
		BrickDCStackInputVoltageConfig channelCfg = getChannelConfigFn.apply("BrickDCStackInputVoltage").as(BrickDCStackInputVoltageConfig.class);
		
		if(channelCfg.updateInterval > 0) {
    this.manualChannelUpdates.add(scheduler.scheduleWithFixedDelay(() -> {if(handler.getThing().getStatus() == ThingStatus.ONLINE) {handler.handleCommand(new ChannelUID(handler.getThing().getUID(), "BrickDCStackInputVoltage"), RefreshType.REFRESH);}}, channelCfg.updateInterval, channelCfg.updateInterval, TimeUnit.MILLISECONDS));
}
		}
		{
		BrickDCExternalInputVoltageConfig channelCfg = getChannelConfigFn.apply("BrickDCExternalInputVoltage").as(BrickDCExternalInputVoltageConfig.class);
		
		if(channelCfg.updateInterval > 0) {
    this.manualChannelUpdates.add(scheduler.scheduleWithFixedDelay(() -> {if(handler.getThing().getStatus() == ThingStatus.ONLINE) {handler.handleCommand(new ChannelUID(handler.getThing().getUID(), "BrickDCExternalInputVoltage"), RefreshType.REFRESH);}}, channelCfg.updateInterval, channelCfg.updateInterval, TimeUnit.MILLISECONDS));
}
		}
		{
		BrickDCCurrentConsumptionConfig channelCfg = getChannelConfigFn.apply("BrickDCCurrentConsumption").as(BrickDCCurrentConsumptionConfig.class);
		
		if(channelCfg.updateInterval > 0) {
    this.manualChannelUpdates.add(scheduler.scheduleWithFixedDelay(() -> {if(handler.getThing().getStatus() == ThingStatus.ONLINE) {handler.handleCommand(new ChannelUID(handler.getThing().getUID(), "BrickDCCurrentConsumption"), RefreshType.REFRESH);}}, channelCfg.updateInterval, channelCfg.updateInterval, TimeUnit.MILLISECONDS));
}
		}
    }

    @Override
    public void dispose(org.eclipse.smarthome.config.core.Configuration config) throws TinkerforgeException {
        listenerRegs.forEach(ListenerReg::deregister);

        
        
    }

    @Override
    public List<String> getEnabledChannels(org.eclipse.smarthome.config.core.Configuration config) throws TinkerforgeException{
        List<String> result = new ArrayList<String>();
        result.add("BrickDCVelocityReached");
		result.add("BrickDCEmergencyShutdown");
		result.add("BrickDCUnderVoltage");
		result.add("BrickDCCurrentVelocity");
		result.add("BrickDCVelocity");
		result.add("BrickDCAcceleration");
		result.add("BrickDCPWMFrequency");
		result.add("BrickDCEnabled");
		result.add("BrickDCFullBrake");
		result.add("BrickDCStackInputVoltage");
		result.add("BrickDCExternalInputVoltage");
		result.add("BrickDCCurrentConsumption");
		result.add("BrickDCFreewheeling");
        return result;
    }

    public static @Nullable ChannelType getChannelType(ChannelTypeUID channelTypeUID) {
        switch(channelTypeUID.getId()) {
            case "BrickDCCurrentVelocity":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickDCCurrentVelocity"), "Current Velocity", "Number:Dimensionless").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickDCCurrentVelocity")).withDescription("The current velocity of the motor. This value is different from the target velocity whenever the motor is currently accelerating to a goal set by the target velocity channel.")
.withStateDescription(StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.valueOf(-100)).withMaximum(BigDecimal.valueOf(100)).withStep(BigDecimal.valueOf(0.0030518509475997192)).withPattern("%.3f %unit%").withReadOnly(true).build().toStateDescription()).build();
            case "BrickDCVelocity":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickDCVelocity"), "Target Velocity", "Number:Dimensionless").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickDCVelocity")).withDescription("The target velocity of the motor. Depending on the acceleration, the motor is not immediately brought to the velocity but smoothly accelerated.<br/><br/>The velocity describes the duty cycle of the PWM with which the motor is controlled, e.g. a velocity of 10% sets a PWM with a 10% duty cycle. You can not only control the duty cycle of the PWM but also the frequency.")
.withStateDescription(StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.valueOf(-100)).withMaximum(BigDecimal.valueOf(100)).withStep(BigDecimal.valueOf(0.0030518509475997192)).withPattern("%.3f %unit%").withReadOnly(false).build().toStateDescription()).build();
            case "BrickDCAcceleration":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickDCAcceleration"), "Acceleration", "Number:Dimensionless").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickDCAcceleration")).withDescription("The acceleration of the motor. It is given in velocity/s. An acceleration of 30%/s means, that every second the velocity is increased by 30% duty cycle.<br/><br/>For example: If the current velocity is 0 and you want to accelerate to a velocity of 50% in 10 seconds, you should set an acceleration of 5%/s.<br/><br/>If acceleration is set to 0, there is no speed ramping, i.e. a new velocity is immediately given to the motor.")
.withStateDescription(StateDescriptionFragmentBuilder.create().withPattern("%.3f %%/s").withReadOnly(false).build().toStateDescription()).build();
            case "BrickDCPWMFrequency":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickDCPWMFrequency"), "PWM Frequency", "Number:Frequency").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickDCPWMFrequency")).withDescription("The frequency of the PWM with which the motor is driven. Often a high frequency is less noisy and the motor runs smoother. However, with a low frequency there are less switches and therefore fewer switching losses. Also with most motors lower frequencies enable higher torque.<br/><br/>If you have no idea what all this means, just ignore this function and use the default frequency of 15000Hz, it will very likely work fine.")
.withStateDescription(StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.valueOf(1)).withMaximum(BigDecimal.valueOf(20000)).withStep(BigDecimal.valueOf(1)).withPattern("%d %unit%").withReadOnly(false).build().toStateDescription()).build();
            case "BrickDCEnabled":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickDCEnabled"), "Enabled", "Switch").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickDCEnabled")).withDescription("Enables/Disables the driver chip. The driver parameters can be configured (velocity, acceleration, etc) before it is enabled. When disabled, the configuration is kept (velocity, acceleration, etc) but the motor is not driven until it is enabled again.<br/><br/>Warning<br/><br/>Disabling the driver chip while the motor is still turning can damage the driver chip. The motor should be stopped by setting the velocity to 0 before disabling the motor power. You have to explicitly wait for the appropriate time after setting the velocity before disabling the driver chip function.").build();
            case "BrickDCFullBrake":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickDCFullBrake"), "Full Brake", "String").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickDCFullBrake")).withDescription("Executes an active full brake.<br/><br/>Warning<br/><br/>This function is for emergency purposes, where an immediate brake is necessary. Depending on the current velocity and the strength of the motor, a full brake can be quite violent.<br/><br/>Set the velocity to 0 if you just want to stop the motor.")
.withCommandDescription(CommandDescriptionBuilder.create().withCommandOption(new CommandOption("FULL BRAKE", "Full Brake")).build()).build();
            case "BrickDCStackInputVoltage":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickDCStackInputVoltage"), "Stack Input Voltage", "Number:ElectricPotential").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickDCStackInputVoltage")).withDescription("The stack input voltage is the voltage that is supplied via the stack, i.e. it is given by a Step-Down or Step-Up Power Supply.")
.withStateDescription(StateDescriptionFragmentBuilder.create().withPattern("%.3f %unit%").withReadOnly(true).build().toStateDescription()).build();
            case "BrickDCExternalInputVoltage":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickDCExternalInputVoltage"), "External Input Voltage", "Number:ElectricPotential").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickDCExternalInputVoltage")).withDescription("The external input voltage is given via the black power input connector on the DC Brick.<br/><br/>If there is an external input voltage and a stack input voltage, the motor will be driven by the external input voltage. If there is only a stack voltage present, the motor will be driven by this voltage.<br/><br/>Warning<br/><br/>This means, if you have a high stack voltage and a low external voltage, the motor will be driven with the low external voltage. If you then remove the external connection, it will immediately be driven by the high stack voltage.")
.withStateDescription(StateDescriptionFragmentBuilder.create().withPattern("%.3f %unit%").withReadOnly(true).build().toStateDescription()).build();
            case "BrickDCCurrentConsumption":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickDCCurrentConsumption"), "Current Consumption", "Number:ElectricCurrent").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickDCCurrentConsumption")).withDescription("The current consumption of the motor")
.withStateDescription(StateDescriptionFragmentBuilder.create().withPattern("%.3f %unit%").withReadOnly(true).build().toStateDescription()).build();
            case "BrickDCFreewheeling":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickDCFreewheeling"), "Free-wheeling", "Switch").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickDCFreewheeling")).withDescription("Enables/disables free-wheeling: If disabled, the motor is always either driving or braking. There is no freewheeling. Advantages are: A more linear correlation between PWM and velocity, more exact accelerations and the possibility to drive with slower velocities. If enabled, the motor is always either driving or freewheeling. Advantages are: Less current consumption and less demands on the motor and driver chip.").build();
default:
                break;
        }

        return null;
    }

    public static ThingType getThingType(ThingTypeUID thingTypeUID) {
             Map<String, String> thingTypeProperties = ThingTypeBuilder.instance(thingTypeUID, "unused").build().getProperties();
             Map<String, String> props = new HashMap<String, String>(thingTypeProperties);
             props.putIfAbsent(TinkerforgeBindingConstants.PROPERTY_MINIMUM_FIRMWARE_VERSION, DEVICE_INFO.minimumFWVersion);
        return ThingTypeBuilder.instance(thingTypeUID, "Tinkerforge DC Brick").isListed(false).withSupportedBridgeTypeUIDs(Arrays.asList(TinkerforgeBindingConstants.THING_TYPE_BRICK_DAEMON.toString())).withConfigDescriptionURI(URI.create("thing-type:tinkerforge:" + thingTypeUID.getId())).withDescription("Drives one brushed DC motor with up to 28V and 5A (peak)").withChannelDefinitions(Arrays.asList(new ChannelDefinitionBuilder("BrickDCVelocityReached", new ChannelTypeUID("system", "trigger")).withLabel("Velocity Reached").withDescription("This channel is triggered whenever a set velocity is reached. For example: If a velocity of 0 is present, acceleration is set to 50%/s and velocity to 100%, the channel will be triggered after about 2 seconds, when the set velocity is actually reached.<br/><br/>Note<br/><br/>Since we can't get any feedback from the DC motor, this only works if the acceleration is set smaller or equal to the maximum acceleration of the motor. Otherwise the motor will lag behind the control value and the listener will be triggered too early.").build(), new ChannelDefinitionBuilder("BrickDCEmergencyShutdown", new ChannelTypeUID("system", "trigger")).withLabel("Emergency Shutdown").withDescription("This channel is triggered if either the current consumption is too high (above 5A) or the temperature of the driver chip is too high (above 175°C). These two possibilities are essentially the same, since the temperature will reach this threshold immediately if the motor consumes too much current. In case of a voltage below 3.3V (external or stack) this listener is triggered as well.<br/><br/>If this listener is triggered, the driver chip gets disabled at the same time. That means, the enable-action has to be called to drive the motor again.<br/><br/>Note<br/><br/>This listener only works in Drive/Brake mode. In Drive/Coast mode it is unfortunately impossible to reliably read the overcurrent/overtemperature signal from the driver chip.").build(), new ChannelDefinitionBuilder("BrickDCUnderVoltage", new ChannelTypeUID("system", "trigger")).withLabel("Under Voltage").withDescription("This channel is triggered when the input voltage drops below the configured minimum voltage. The parameter is the current voltage.").build(), new ChannelDefinitionBuilder("BrickDCCurrentVelocity", new ChannelTypeUID("tinkerforge", "BrickDCCurrentVelocity")).withLabel("Current Velocity").build(), new ChannelDefinitionBuilder("BrickDCVelocity", new ChannelTypeUID("tinkerforge", "BrickDCVelocity")).withLabel("Target Velocity").build(), new ChannelDefinitionBuilder("BrickDCAcceleration", new ChannelTypeUID("tinkerforge", "BrickDCAcceleration")).withLabel("Acceleration").build(), new ChannelDefinitionBuilder("BrickDCPWMFrequency", new ChannelTypeUID("tinkerforge", "BrickDCPWMFrequency")).withLabel("PWM Frequency").build(), new ChannelDefinitionBuilder("BrickDCEnabled", new ChannelTypeUID("tinkerforge", "BrickDCEnabled")).withLabel("Enabled").build(), new ChannelDefinitionBuilder("BrickDCFullBrake", new ChannelTypeUID("tinkerforge", "BrickDCFullBrake")).withLabel("Full Brake").build(), new ChannelDefinitionBuilder("BrickDCStackInputVoltage", new ChannelTypeUID("tinkerforge", "BrickDCStackInputVoltage")).withLabel("Stack Input Voltage").build(), new ChannelDefinitionBuilder("BrickDCExternalInputVoltage", new ChannelTypeUID("tinkerforge", "BrickDCExternalInputVoltage")).withLabel("External Input Voltage").build(), new ChannelDefinitionBuilder("BrickDCCurrentConsumption", new ChannelTypeUID("tinkerforge", "BrickDCCurrentConsumption")).withLabel("Current Consumption").build(), new ChannelDefinitionBuilder("BrickDCFreewheeling", new ChannelTypeUID("tinkerforge", "BrickDCFreewheeling")).withLabel("Free-wheeling").build())).withProperties(props).build();
    }

    public static @Nullable ConfigDescription getConfigDescription(URI uri) {
        switch(uri.toASCIIString()) {
            case "thing-type:tinkerforge:brickdc":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList(ConfigDescriptionParameterBuilder.create("minimumVoltage", Type.DECIMAL).withDefault("6").withDescription("The minimum voltage in V, below which the Under Voltage channel is triggered. The minimum possible value that works with the DC Brick is 5V. You can use this function to detect the discharge of a battery that is used to drive the stepper motor. If you have a fixed power supply, you likely do not need this functionality. The default value is 5V.").withLabel("Minimum Voltage").withUnit("V").withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(65.535)).build(), ConfigDescriptionParameterBuilder.create("statusLEDConfig", Type.BOOLEAN).withDefault("true").withDescription("The status LED is the blue LED next to the USB connector. If enabled is is on and it flickers if data is transfered. If disabled it is always off.").withLabel("Status LED Configuration").build(), ConfigDescriptionParameterBuilder.create("spitfpEnableDynamicBaudrate", Type.BOOLEAN).withDefault("true").withDescription("The SPITF protocol can be used with a dynamic baudrate. If the dynamic baudrate is enabled, the Brick will try to adapt the baudrate for the communication between Bricks and Bricklets according to the amount of data that is transferred.<br/><br/>The baudrate will be increased exponentially if lots of data is sent/received and decreased linearly if little data is sent/received.<br/><br/>This lowers the baudrate in applications where little data is transferred (e.g. a weather station) and increases the robustness. If there is lots of data to transfer (e.g. Thermal Imaging Bricklet) it automatically increases the baudrate as needed.<br/><br/>In cases where some data has to transferred as fast as possible every few seconds (e.g. RS485 Bricklet with a high baudrate but small payload) you may want to turn the dynamic baudrate off to get the highest possible performance.<br/><br/>The maximum value of the baudrate can be set per port. If the dynamic baudrate is disabled, the maximum baudrate will be used statically.").withLabel("SPITFP Enable Dynamic Baudrate").withAdvanced(true).build(), ConfigDescriptionParameterBuilder.create("spitfpMinimumDynamicBaudrate", Type.INTEGER).withDefault("400000").withDescription("See SPITFP Enable Dynamic Baudrate").withLabel("SPITFP Minimum Dynamic Baudrate").withAdvanced(true).withMinimum(BigDecimal.valueOf(400000)).withMaximum(BigDecimal.valueOf(2000000)).build(), ConfigDescriptionParameterBuilder.create("spitfpBaudratePortA", Type.INTEGER).withDefault("1400000").withDescription("The baudrate for Bricklet port A.<br/><br/>If you want to increase the throughput of Bricklets you can increase the baudrate. If you get a high error count because of high interference you can decrease the baudrate.<br/><br/>If the dynamic baudrate feature is enabled, this is the maximum baudrate.<br/><br/>Regulatory testing is done with the default baudrate. If CE compatibility or similar is necessary in your applications we recommend to not change the baudrate.").withLabel("(Maximum) SPITFP Baudrate Port A").withAdvanced(true).withMinimum(BigDecimal.valueOf(400000)).withMaximum(BigDecimal.valueOf(2000000)).build(), ConfigDescriptionParameterBuilder.create("spitfpBaudratePortB", Type.INTEGER).withDefault("1400000").withDescription("The baudrate for Bricklet port B.<br/><br/>If you want to increase the throughput of Bricklets you can increase the baudrate. If you get a high error count because of high interference you can decrease the baudrate.<br/><br/>If the dynamic baudrate feature is enabled, this is the maximum baudrate.<br/><br/>Regulatory testing is done with the default baudrate. If CE compatibility or similar is necessary in your applications we recommend to not change the baudrate.").withLabel("(Maximum) SPITFP Baudrate Port B").withAdvanced(true).withMinimum(BigDecimal.valueOf(400000)).withMaximum(BigDecimal.valueOf(2000000)).build())).withParameterGroups(Arrays.asList(new ConfigDescriptionParameterGroup("update_intervals", "null", true, "Update Intervals", "Update Intervals"))).build();
            case "channel-type:tinkerforge:BrickDCCurrentVelocity":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList(ConfigDescriptionParameterBuilder.create("updateInterval", Type.INTEGER).withDefault("1000").withDescription("Specifies the update interval in milliseconds. A value of 0 disables automatic updates.").withGroupName("update_intervals").withLabel("Update Interval").withUnit("ms").withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(65535)).build())).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickDCVelocity":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickDCAcceleration":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickDCPWMFrequency":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickDCEnabled":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickDCFullBrake":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickDCStackInputVoltage":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList(ConfigDescriptionParameterBuilder.create("updateInterval", Type.INTEGER).withDefault("1000").withDescription("Specifies the update interval in milliseconds. A value of 0 disables automatic updates.").withLabel("Update Interval").withUnit("ms").build())).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickDCExternalInputVoltage":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList(ConfigDescriptionParameterBuilder.create("updateInterval", Type.INTEGER).withDefault("1000").withDescription("Specifies the update interval in milliseconds. A value of 0 disables automatic updates.").withLabel("Update Interval").withUnit("ms").build())).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickDCCurrentConsumption":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList(ConfigDescriptionParameterBuilder.create("updateInterval", Type.INTEGER).withDefault("1000").withDescription("Specifies the update interval in milliseconds. A value of 0 disables automatic updates.").withLabel("Update Interval").withUnit("ms").build())).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickDCFreewheeling":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            default:
                break;
        }
        return null;
    }

        @Override
    public void refreshValue(String channel, org.eclipse.smarthome.config.core.Configuration config, org.eclipse.smarthome.config.core.Configuration channelConfig, BiConsumer<String, org.eclipse.smarthome.core.types.State> updateStateFn, BiConsumer<String, String> triggerChannelFn) throws TinkerforgeException {
        BrickDCConfig cfg = (BrickDCConfig) config.as(BrickDCConfig.class);
switch(channel) {
            case "BrickDCVelocityReached":
               return;
            case "BrickDCEmergencyShutdown":
               return;
            case "BrickDCUnderVoltage":
               return;
            case "BrickDCCurrentVelocity":
                   {
            short value = this.getCurrentVelocity();
            if(true)
                updateStateFn.accept(channel, transformBrickDCCurrentVelocityGetter0(value, cfg));
        }
                   return;
            case "BrickDCVelocity":
                   {
            short value = this.getVelocity();
            if(true)
                updateStateFn.accept(channel, transformBrickDCVelocityGetter0(value, cfg));
        }
                   return;
            case "BrickDCAcceleration":
                   {
            int value = this.getAcceleration();
            if(true)
                updateStateFn.accept(channel, transformBrickDCAccelerationGetter0(value, cfg));
        }
                   return;
            case "BrickDCPWMFrequency":
                   {
            int value = this.getPWMFrequency();
            if(true)
                updateStateFn.accept(channel, transformBrickDCPWMFrequencyGetter0(value, cfg));
        }
                   return;
            case "BrickDCEnabled":
                   {
            boolean value = this.isEnabled();
            if(true)
                updateStateFn.accept(channel, transformBrickDCEnabledGetter0(value, cfg));
        }
                   return;
            case "BrickDCFullBrake":
               return;
            case "BrickDCStackInputVoltage":
                   {
            int value = this.getStackInputVoltage();
            if(true)
                updateStateFn.accept(channel, transformBrickDCStackInputVoltageGetter0(value, cfg));
        }
                   return;
            case "BrickDCExternalInputVoltage":
                   {
            int value = this.getExternalInputVoltage();
            if(true)
                updateStateFn.accept(channel, transformBrickDCExternalInputVoltageGetter0(value, cfg));
        }
                   return;
            case "BrickDCCurrentConsumption":
                   {
            int value = this.getCurrentConsumption();
            if(true)
                updateStateFn.accept(channel, transformBrickDCCurrentConsumptionGetter0(value, cfg));
        }
                   return;
            case "BrickDCFreewheeling":
                   {
            short value = this.getDriveMode();
            if(true)
                updateStateFn.accept(channel, transformBrickDCFreewheelingGetter0(value, cfg));
        }
                   return;
default:
                logger.warn("Refresh for unknown channel {}", channel);
                break;
        }
    }
    

        @Override
    public List<SetterRefresh> handleCommand(org.eclipse.smarthome.config.core.Configuration config, org.eclipse.smarthome.config.core.Configuration channelConfig, String channel, Command command) throws TinkerforgeException {
        List<SetterRefresh> result = Collections.emptyList();
        
        switch(channel) {
            case "BrickDCVelocity":
                if (command instanceof Number) {
                    Number cmd = (Number) command;
this.setVelocity((short)(cmd.doubleValue() * 327.67));
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of Number.", command.getClass().getName(), channel);
                }
                
                break;
            case "BrickDCAcceleration":
                if (command instanceof Number) {
                    Number cmd = (Number) command;
this.setAcceleration((int)(cmd.intValue() * 327.67));
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of Number.", command.getClass().getName(), channel);
                }
                
                break;
            case "BrickDCPWMFrequency":
                if (command instanceof Number) {
                    Number cmd = (Number) command;
this.setPWMFrequency((int)(cmd.intValue()));
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of Number.", command.getClass().getName(), channel);
                }
                
                break;
            case "BrickDCEnabled":
                if (command instanceof OnOffType) {
                    OnOffType cmd = (OnOffType) command;
if(cmd == OnOffType.ON) {
    this.enable();
}
                }
        
if (command instanceof OnOffType) {
                    OnOffType cmd = (OnOffType) command;
if(cmd == OnOffType.OFF) {
    this.disable();
}
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of OnOffType, OnOffType.", command.getClass().getName(), channel);
                }
                
                break;
            case "BrickDCFullBrake":
                if (command instanceof StringType) {
                    this.fullBrake();
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of StringType.", command.getClass().getName(), channel);
                }
                
                break;
            case "BrickDCFreewheeling":
                if (command instanceof OnOffType) {
                    OnOffType cmd = (OnOffType) command;
this.setDriveMode(cmd == OnOffType.ON ? (short)1 : (short)0);
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of OnOffType.", command.getClass().getName(), channel);
                }
                
                break;
default:
                logger.warn("Command for unknown channel {}", channel);
        }
        return result;
    }

        private String transformBrickDCVelocityReachedCallback0(short velocity, BrickDCConfig cfg) {
        return "";
    }
	    private String transformBrickDCEmergencyShutdownCallback0(BrickDCConfig cfg) {
        return "";
    }
	    private String transformBrickDCUnderVoltageCallback0(int voltage, BrickDCConfig cfg) {
        return "";
    }
	    private org.eclipse.smarthome.core.types.State transformBrickDCCurrentVelocityCallback0(short velocity, BrickDCConfig cfg) {
        return new QuantityType<>(velocity / 327.67, SmartHomeUnits.PERCENT);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickDCCurrentVelocityGetter0(short value, BrickDCConfig cfg) {
        return new QuantityType<>(value / 327.67, SmartHomeUnits.PERCENT);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickDCVelocityGetter0(short value, BrickDCConfig cfg) {
        return new QuantityType<>(value / 327.67, SmartHomeUnits.PERCENT);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickDCAccelerationGetter0(int value, BrickDCConfig cfg) {
        return new DecimalType(value / 327.67);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickDCPWMFrequencyGetter0(int value, BrickDCConfig cfg) {
        return new QuantityType<>(value, SmartHomeUnits.HERTZ);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickDCEnabledGetter0(boolean value, BrickDCConfig cfg) {
        return value ? OnOffType.ON : OnOffType.OFF;
    }
	    private org.eclipse.smarthome.core.types.State transformBrickDCStackInputVoltageGetter0(int value, BrickDCConfig cfg) {
        return new QuantityType<>(value / 1000.0, SmartHomeUnits.VOLT);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickDCExternalInputVoltageGetter0(int value, BrickDCConfig cfg) {
        return new QuantityType<>(value / 1000.0, SmartHomeUnits.VOLT);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickDCCurrentConsumptionGetter0(int value, BrickDCConfig cfg) {
        return new QuantityType<>(value / 1000.0, SmartHomeUnits.AMPERE);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickDCFreewheelingGetter0(short value, BrickDCConfig cfg) {
        return value == 1 ? OnOffType.ON : OnOffType.OFF;
    }

}