/**
 * 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.library.types.OnOffType;

import com.tinkerforge.BrickIMU;
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 IMU Brick.
 * @author Erik Fleckstein - Initial contribution
 */
@NonNullByDefault
public class BrickIMUWrapper extends BrickIMU implements DeviceWrapper {
    public static final DeviceInfo DEVICE_INFO = new DeviceInfo(BrickIMU.DEVICE_DISPLAY_NAME, "brickimu", BrickIMU.DEVICE_IDENTIFIER, BrickIMUWrapper.class, BrickIMUActions.class, "2.3.5", false);

    public BrickIMUWrapper(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(BrickIMUWrapper.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);
        BrickIMUConfig cfg = (BrickIMUConfig) config.as(BrickIMUConfig.class);
        if(cfg.enableOrientation) {
this.addOrientationListener(this.reg((roll, pitch, yaw) -> {if(true) {updateStateFn.accept("BrickIMUOrientationRoll", transformBrickIMUOrientationRollCallback0(roll, pitch, yaw, cfg));}}, this::removeOrientationListener));}
		if(cfg.enableOrientation) {
this.addOrientationListener(this.reg((roll, pitch, yaw) -> {if(true) {updateStateFn.accept("BrickIMUOrientationPitch", transformBrickIMUOrientationPitchCallback0(roll, pitch, yaw, cfg));}}, this::removeOrientationListener));}
		if(cfg.enableOrientation) {
this.addOrientationListener(this.reg((roll, pitch, yaw) -> {if(true) {updateStateFn.accept("BrickIMUOrientationYaw", transformBrickIMUOrientationYawCallback0(roll, pitch, yaw, cfg));}}, this::removeOrientationListener));}
		this.addQuaternionListener(this.reg((x, y, z, w) -> {if(true) {updateStateFn.accept("BrickIMUQuaternionX", transformBrickIMUQuaternionXCallback0(x, y, z, w, cfg));}}, this::removeQuaternionListener));
		this.addQuaternionListener(this.reg((x, y, z, w) -> {if(true) {updateStateFn.accept("BrickIMUQuaternionY", transformBrickIMUQuaternionYCallback0(x, y, z, w, cfg));}}, this::removeQuaternionListener));
		this.addQuaternionListener(this.reg((x, y, z, w) -> {if(true) {updateStateFn.accept("BrickIMUQuaternionZ", transformBrickIMUQuaternionZCallback0(x, y, z, w, cfg));}}, this::removeQuaternionListener));
		this.addQuaternionListener(this.reg((x, y, z, w) -> {if(true) {updateStateFn.accept("BrickIMUQuaternionW", transformBrickIMUQuaternionWCallback0(x, y, z, w, cfg));}}, this::removeQuaternionListener));
		this.addAccelerationListener(this.reg((x, y, z) -> {if(true) {updateStateFn.accept("BrickIMUAccelerationX", transformBrickIMUAccelerationXCallback0(x, y, z, cfg));}}, this::removeAccelerationListener));
		this.addAccelerationListener(this.reg((x, y, z) -> {if(true) {updateStateFn.accept("BrickIMUAccelerationY", transformBrickIMUAccelerationYCallback0(x, y, z, cfg));}}, this::removeAccelerationListener));
		this.addAccelerationListener(this.reg((x, y, z) -> {if(true) {updateStateFn.accept("BrickIMUAccelerationZ", transformBrickIMUAccelerationZCallback0(x, y, z, cfg));}}, this::removeAccelerationListener));
		this.addMagneticFieldListener(this.reg((x, y, z) -> {if(true) {updateStateFn.accept("BrickIMUMagneticFieldX", transformBrickIMUMagneticFieldXCallback0(x, y, z, cfg));}}, this::removeMagneticFieldListener));
		this.addMagneticFieldListener(this.reg((x, y, z) -> {if(true) {updateStateFn.accept("BrickIMUMagneticFieldY", transformBrickIMUMagneticFieldYCallback0(x, y, z, cfg));}}, this::removeMagneticFieldListener));
		this.addMagneticFieldListener(this.reg((x, y, z) -> {if(true) {updateStateFn.accept("BrickIMUMagneticFieldZ", transformBrickIMUMagneticFieldZCallback0(x, y, z, cfg));}}, this::removeMagneticFieldListener));
		this.addAngularVelocityListener(this.reg((x, y, z) -> {if(true) {updateStateFn.accept("BrickIMUAngularVelocityX", transformBrickIMUAngularVelocityXCallback0(x, y, z, cfg));}}, this::removeAngularVelocityListener));
		this.addAngularVelocityListener(this.reg((x, y, z) -> {if(true) {updateStateFn.accept("BrickIMUAngularVelocityY", transformBrickIMUAngularVelocityYCallback0(x, y, z, cfg));}}, this::removeAngularVelocityListener));
		this.addAngularVelocityListener(this.reg((x, y, z) -> {if(true) {updateStateFn.accept("BrickIMUAngularVelocityZ", transformBrickIMUAngularVelocityZCallback0(x, y, z, cfg));}}, this::removeAngularVelocityListener));
        if(cfg.enableOrientation) {{
		        this.orientationCalculationOn();
		        this.setOrientationPeriod(cfg.orientationUpdateInterval);
		    }} else {{
		        this.orientationCalculationOff();
		        this.setOrientationPeriod(0);
		    }}
		    this.setConvergenceSpeed(cfg.convergenceSpeed);
		    this.setQuaternionPeriod(cfg.quaternionUpdateInterval);
		    this.setAccelerationPeriod(cfg.accelerationUpdateInterval);
		    this.setMagneticFieldPeriod(cfg.magneticFieldUpdateInterval);
		    this.setAngularVelocityPeriod(cfg.angularVelocityUpdateInterval);
		    
		if(cfg.statusLEDConfig) {
		                this.enableStatusLED();
		            } else {
		                this.disableStatusLED();
		            }
		this.setSPITFPBaudrateConfig(cfg.spitfpEnableDynamicBaudrate, cfg.spitfpMinimumDynamicBaudrate);
		this.setSPITFPBaudrate('a', cfg.spitfpBaudratePortA);
		            this.setSPITFPBaudrate('b', cfg.spitfpBaudratePortB);
    }

    @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{
        BrickIMUConfig cfg = (BrickIMUConfig) config.as(BrickIMUConfig.class);
List<String> result = new ArrayList<String>();
        if (cfg.enableOrientation) {
                result.add("BrickIMUOrientationRoll");
            }
		if (cfg.enableOrientation) {
                result.add("BrickIMUOrientationPitch");
            }
		if (cfg.enableOrientation) {
                result.add("BrickIMUOrientationYaw");
            }
		result.add("BrickIMUQuaternionX");
		result.add("BrickIMUQuaternionY");
		result.add("BrickIMUQuaternionZ");
		result.add("BrickIMUQuaternionW");
		result.add("BrickIMUEnableLEDs");
		result.add("BrickIMUAccelerationX");
		result.add("BrickIMUAccelerationY");
		result.add("BrickIMUAccelerationZ");
		result.add("BrickIMUMagneticFieldX");
		result.add("BrickIMUMagneticFieldY");
		result.add("BrickIMUMagneticFieldZ");
		result.add("BrickIMUAngularVelocityX");
		result.add("BrickIMUAngularVelocityY");
		result.add("BrickIMUAngularVelocityZ");
        return result;
    }

    public static @Nullable ChannelType getChannelType(ChannelTypeUID channelTypeUID) {
        switch(channelTypeUID.getId()) {
            case "BrickIMUOrientation":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickIMUOrientation"), "NOT USED", "Number:Angle").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickIMUOrientation")).withDescription("The current orientation (roll, pitch, yaw) of the IMU Brick as Euler angles in °. Note that Euler angles always experience a gimbal lock.<br/><br/>We recommend that you use quaternions instead.<br/><br/>The order to sequence in which the orientation values should be applied is roll, yaw, pitch.")
.withStateDescription(StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.valueOf(-180)).withMaximum(BigDecimal.valueOf(180)).withStep(BigDecimal.valueOf(0.01)).withPattern("%.2f %unit%").withReadOnly(true).build().toStateDescription()).build();
            case "BrickIMUQuaternion":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickIMUQuaternion"), "NOT USED", "Number:Dimensionless").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickIMUQuaternion")).withDescription("The current orientation (x, y, z, w) of the IMU as quaternions.")
.withStateDescription(StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.valueOf(-1)).withMaximum(BigDecimal.valueOf(1)).withStep(BigDecimal.valueOf(1)).withPattern("%f").withReadOnly(true).build().toStateDescription()).build();
            case "BrickIMUAcceleration":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickIMUAcceleration"), "NOT USED", "Number:Acceleration").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickIMUAcceleration")).withDescription("The calibrated acceleration from the accelerometer for the x, y and z axis in g (1g = 9.80665m/s²).")
.withStateDescription(StateDescriptionFragmentBuilder.create().withPattern("%.3f %unit%").withReadOnly(true).build().toStateDescription()).build();
            case "BrickIMUMagneticField":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickIMUMagneticField"), "NOT USED", "Number:MagneticFluxDensity").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickIMUMagneticField")).withDescription("The calibrated magnetic field from the magnetometer for the x, y and z axis in Tesla.")
.withStateDescription(StateDescriptionFragmentBuilder.create().withPattern("%.7f %unit%").withReadOnly(true).build().toStateDescription()).build();
            case "BrickIMUAngularVelocity":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickIMUAngularVelocity"), "NOT USED", "Number:Dimensionless").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickIMUAngularVelocity")).withDescription("The calibrated angular velocity from the gyroscope for the x, y and z axis in °/s.")
.withStateDescription(StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.valueOf(-2000)).withMaximum(BigDecimal.valueOf(2000)).withStep(BigDecimal.valueOf(0.06956521739130435)).withPattern("%.2f").withReadOnly(true).build().toStateDescription()).build();
            case "BrickIMUEnableLEDs":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickIMUEnableLEDs"), "Enable LEDs", "Switch").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickIMUEnableLEDs")).withDescription("Enable/disable the orientation and direction LEDs of the IMU Brick.").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 IMU Brick").isListed(false).withSupportedBridgeTypeUIDs(Arrays.asList(TinkerforgeBindingConstants.THING_TYPE_BRICK_DAEMON.toString())).withConfigDescriptionURI(URI.create("thing-type:tinkerforge:" + thingTypeUID.getId())).withDescription("Full fledged AHRS with 9 degrees of freedom").withChannelDefinitions(Arrays.asList(new ChannelDefinitionBuilder("BrickIMUOrientationRoll", new ChannelTypeUID("tinkerforge", "BrickIMUOrientation")).withLabel("Orientation - Roll").build(), new ChannelDefinitionBuilder("BrickIMUOrientationPitch", new ChannelTypeUID("tinkerforge", "BrickIMUOrientation")).withLabel("Orientation - Pitch").build(), new ChannelDefinitionBuilder("BrickIMUOrientationYaw", new ChannelTypeUID("tinkerforge", "BrickIMUOrientation")).withLabel("Orientation - Yaw").build(), new ChannelDefinitionBuilder("BrickIMUQuaternionX", new ChannelTypeUID("tinkerforge", "BrickIMUQuaternion")).withLabel("Quaternion - X").build(), new ChannelDefinitionBuilder("BrickIMUQuaternionY", new ChannelTypeUID("tinkerforge", "BrickIMUQuaternion")).withLabel("Quaternion - Y").build(), new ChannelDefinitionBuilder("BrickIMUQuaternionZ", new ChannelTypeUID("tinkerforge", "BrickIMUQuaternion")).withLabel("Quaternion - Z").build(), new ChannelDefinitionBuilder("BrickIMUQuaternionW", new ChannelTypeUID("tinkerforge", "BrickIMUQuaternion")).withLabel("Quaternion - W").build(), new ChannelDefinitionBuilder("BrickIMUEnableLEDs", new ChannelTypeUID("tinkerforge", "BrickIMUEnableLEDs")).withLabel("Enable LEDs").build(), new ChannelDefinitionBuilder("BrickIMUAccelerationX", new ChannelTypeUID("tinkerforge", "BrickIMUAcceleration")).withLabel("Acceleration - X").build(), new ChannelDefinitionBuilder("BrickIMUAccelerationY", new ChannelTypeUID("tinkerforge", "BrickIMUAcceleration")).withLabel("Acceleration - Y").build(), new ChannelDefinitionBuilder("BrickIMUAccelerationZ", new ChannelTypeUID("tinkerforge", "BrickIMUAcceleration")).withLabel("Acceleration - Z").build(), new ChannelDefinitionBuilder("BrickIMUMagneticFieldX", new ChannelTypeUID("tinkerforge", "BrickIMUMagneticField")).withLabel("Magnetic Field - X").build(), new ChannelDefinitionBuilder("BrickIMUMagneticFieldY", new ChannelTypeUID("tinkerforge", "BrickIMUMagneticField")).withLabel("Magnetic Field - Y").build(), new ChannelDefinitionBuilder("BrickIMUMagneticFieldZ", new ChannelTypeUID("tinkerforge", "BrickIMUMagneticField")).withLabel("Magnetic Field - Z").build(), new ChannelDefinitionBuilder("BrickIMUAngularVelocityX", new ChannelTypeUID("tinkerforge", "BrickIMUAngularVelocity")).withLabel("Angular Velocity - X").build(), new ChannelDefinitionBuilder("BrickIMUAngularVelocityY", new ChannelTypeUID("tinkerforge", "BrickIMUAngularVelocity")).withLabel("Angular Velocity - Y").build(), new ChannelDefinitionBuilder("BrickIMUAngularVelocityZ", new ChannelTypeUID("tinkerforge", "BrickIMUAngularVelocity")).withLabel("Angular Velocity - Z").build())).withProperties(props).build();
    }

    public static @Nullable ConfigDescription getConfigDescription(URI uri) {
        switch(uri.toASCIIString()) {
            case "thing-type:tinkerforge:brickimu":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList(ConfigDescriptionParameterBuilder.create("enableOrientation", Type.BOOLEAN).withDefault("true").withDescription("Turns the orientation calculation of the IMU Brick on or off. The trigonometric functions that are needed to calculate the orientation are very expensive. We recommend to turn the orientation calculation off if the orientation is not needed, to free calculation time for the sensor fusion algorithm.").withLabel("Enable Orientation").build(), ConfigDescriptionParameterBuilder.create("convergenceSpeed", Type.INTEGER).withDefault("30").withDescription("Sets the convergence speed of the IMU Brick in °/s. The convergence speed determines how the different sensor measurements are fused.<br/><br/>If the orientation of the IMU Brick is off by 10° and the convergence speed is set to 20°/s, it will take 0.5s until the orientation is corrected. However, if the correct orientation is reached and the convergence speed is too high, the orientation will fluctuate with the fluctuations of the accelerometer and the magnetometer.<br/><br/>If you set the convergence speed to 0, practically only the gyroscope is used to calculate the orientation. This gives very smooth movements, but errors of the gyroscope will not be corrected. If you set the convergence speed to something above 500, practically only the magnetometer and the accelerometer are used to calculate the orientation. In this case the movements are abrupt and the values will fluctuate, but there won't be any errors that accumulate over time.<br/><br/>In an application with high angular velocities, we recommend a high convergence speed, so the errors of the gyroscope can be corrected fast. In applications with only slow movements we recommend a low convergence speed. You can change the convergence speed on the fly. So it is possible (and recommended) to increase the convergence speed before an abrupt movement and decrease it afterwards again.<br/><br/>You might want to play around with the convergence speed in the Brick Viewer to get a feeling for a good value for your application.<br/><br/>The default value is 30.").withLabel("Convergence Speed").withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(65535)).build(), ConfigDescriptionParameterBuilder.create("orientationUpdateInterval", Type.INTEGER).withDefault("1000").withDescription("Specifies the update interval for the orientation as euler angles in milliseconds. A value of 0 disables automatic updates.").withGroupName("update_intervals").withLabel("Orientation Update Interval").withUnit("ms").withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(4294967295L)).build(), ConfigDescriptionParameterBuilder.create("quaternionUpdateInterval", Type.INTEGER).withDefault("1000").withDescription("Specifies the update interval for the orientation as quaternion in milliseconds. A value of 0 disables automatic updates.").withGroupName("update_intervals").withLabel("Quaternion Update Interval").withUnit("ms").withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(4294967295L)).build(), ConfigDescriptionParameterBuilder.create("accelerationUpdateInterval", Type.INTEGER).withDefault("1000").withDescription("Specifies the update interval for the acceleration in milliseconds. A value of 0 disables automatic updates.").withGroupName("update_intervals").withLabel("Acceleration Update Interval").withUnit("ms").withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(4294967295L)).build(), ConfigDescriptionParameterBuilder.create("magneticFieldUpdateInterval", Type.INTEGER).withDefault("1000").withDescription("Specifies the update interval for the magnetic field in milliseconds. A value of 0 disables automatic updates.").withGroupName("update_intervals").withLabel("Magnetic Field Update Interval").withUnit("ms").withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(4294967295L)).build(), ConfigDescriptionParameterBuilder.create("angularVelocityUpdateInterval", Type.INTEGER).withDefault("1000").withDescription("Specifies the update interval for the angular velocity in milliseconds. A value of 0 disables automatic updates.").withGroupName("update_intervals").withLabel("Angular Velocity Update Interval").withUnit("ms").withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(4294967295L)).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:BrickIMUOrientation":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickIMUQuaternion":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickIMUAcceleration":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickIMUMagneticField":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickIMUAngularVelocity":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickIMUEnableLEDs":
                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 {
        BrickIMUConfig cfg = (BrickIMUConfig) config.as(BrickIMUConfig.class);
switch(channel) {
            case "BrickIMUOrientationRoll":
                   {
            BrickIMU.Orientation value = this.getOrientation();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUOrientationRollGetter0(value, cfg));
        }
                   return;
            case "BrickIMUOrientationPitch":
                   {
            BrickIMU.Orientation value = this.getOrientation();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUOrientationPitchGetter0(value, cfg));
        }
                   return;
            case "BrickIMUOrientationYaw":
                   {
            BrickIMU.Orientation value = this.getOrientation();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUOrientationYawGetter0(value, cfg));
        }
                   return;
            case "BrickIMUQuaternionX":
                   {
            BrickIMU.Quaternion value = this.getQuaternion();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUQuaternionXGetter0(value, cfg));
        }
                   return;
            case "BrickIMUQuaternionY":
                   {
            BrickIMU.Quaternion value = this.getQuaternion();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUQuaternionYGetter0(value, cfg));
        }
                   return;
            case "BrickIMUQuaternionZ":
                   {
            BrickIMU.Quaternion value = this.getQuaternion();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUQuaternionZGetter0(value, cfg));
        }
                   return;
            case "BrickIMUQuaternionW":
                   {
            BrickIMU.Quaternion value = this.getQuaternion();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUQuaternionWGetter0(value, cfg));
        }
                   return;
            case "BrickIMUEnableLEDs":
                   {
            boolean value = this.areLedsOn();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUEnableLEDsGetter0(value, cfg));
        }
                   return;
            case "BrickIMUAccelerationX":
                   {
            BrickIMU.Acceleration value = this.getAcceleration();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUAccelerationXGetter0(value, cfg));
        }
                   return;
            case "BrickIMUAccelerationY":
                   {
            BrickIMU.Acceleration value = this.getAcceleration();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUAccelerationYGetter0(value, cfg));
        }
                   return;
            case "BrickIMUAccelerationZ":
                   {
            BrickIMU.Acceleration value = this.getAcceleration();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUAccelerationZGetter0(value, cfg));
        }
                   return;
            case "BrickIMUMagneticFieldX":
                   {
            BrickIMU.MagneticField value = this.getMagneticField();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUMagneticFieldXGetter0(value, cfg));
        }
                   return;
            case "BrickIMUMagneticFieldY":
                   {
            BrickIMU.MagneticField value = this.getMagneticField();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUMagneticFieldYGetter0(value, cfg));
        }
                   return;
            case "BrickIMUMagneticFieldZ":
                   {
            BrickIMU.MagneticField value = this.getMagneticField();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUMagneticFieldZGetter0(value, cfg));
        }
                   return;
            case "BrickIMUAngularVelocityX":
                   {
            BrickIMU.AngularVelocity value = this.getAngularVelocity();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUAngularVelocityXGetter0(value, cfg));
        }
                   return;
            case "BrickIMUAngularVelocityY":
                   {
            BrickIMU.AngularVelocity value = this.getAngularVelocity();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUAngularVelocityYGetter0(value, cfg));
        }
                   return;
            case "BrickIMUAngularVelocityZ":
                   {
            BrickIMU.AngularVelocity value = this.getAngularVelocity();
            if(true)
                updateStateFn.accept(channel, transformBrickIMUAngularVelocityZGetter0(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 "BrickIMUEnableLEDs":
                if (command instanceof OnOffType) {
                    OnOffType cmd = (OnOffType) command;
if(cmd == OnOffType.ON) {
    this.ledsOn();
}
                }
        
if (command instanceof OnOffType) {
                    OnOffType cmd = (OnOffType) command;
if(cmd == OnOffType.OFF) {
    this.ledsOff();
}
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of OnOffType, OnOffType.", command.getClass().getName(), channel);
                }
                
                break;
default:
                logger.warn("Command for unknown channel {}", channel);
        }
        return result;
    }

        private org.eclipse.smarthome.core.types.State transformBrickIMUOrientationRollCallback0(short roll, short pitch, short yaw, BrickIMUConfig cfg) {
        return new QuantityType<>(roll / 100.0, SmartHomeUnits.DEGREE_ANGLE);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUOrientationPitchCallback0(short roll, short pitch, short yaw, BrickIMUConfig cfg) {
        return new QuantityType<>(pitch / 100.0, SmartHomeUnits.DEGREE_ANGLE);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUOrientationYawCallback0(short roll, short pitch, short yaw, BrickIMUConfig cfg) {
        return new QuantityType<>(yaw / 100.0, SmartHomeUnits.DEGREE_ANGLE);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUQuaternionXCallback0(float x, float y, float z, float w, BrickIMUConfig cfg) {
        return new DecimalType(x);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUQuaternionYCallback0(float x, float y, float z, float w, BrickIMUConfig cfg) {
        return new DecimalType(y);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUQuaternionZCallback0(float x, float y, float z, float w, BrickIMUConfig cfg) {
        return new DecimalType(z);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUQuaternionWCallback0(float x, float y, float z, float w, BrickIMUConfig cfg) {
        return new DecimalType(w);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUAccelerationXCallback0(short x, short y, short z, BrickIMUConfig cfg) {
        return new QuantityType<>(x / 1000.0, SmartHomeUnits.STANDARD_GRAVITY);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUAccelerationYCallback0(short x, short y, short z, BrickIMUConfig cfg) {
        return new QuantityType<>(y / 1000.0, SmartHomeUnits.STANDARD_GRAVITY);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUAccelerationZCallback0(short x, short y, short z, BrickIMUConfig cfg) {
        return new QuantityType<>(z / 1000.0, SmartHomeUnits.STANDARD_GRAVITY);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUMagneticFieldXCallback0(short x, short y, short z, BrickIMUConfig cfg) {
        return new QuantityType<>(x / 10000000.0, SmartHomeUnits.TESLA);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUMagneticFieldYCallback0(short x, short y, short z, BrickIMUConfig cfg) {
        return new QuantityType<>(y / 10000000.0, SmartHomeUnits.TESLA);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUMagneticFieldZCallback0(short x, short y, short z, BrickIMUConfig cfg) {
        return new QuantityType<>(z / 10000000.0, SmartHomeUnits.TESLA);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUAngularVelocityXCallback0(short x, short y, short z, BrickIMUConfig cfg) {
        return new DecimalType(x / 14.375);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUAngularVelocityYCallback0(short x, short y, short z, BrickIMUConfig cfg) {
        return new DecimalType(y / 14.375);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUAngularVelocityZCallback0(short x, short y, short z, BrickIMUConfig cfg) {
        return new DecimalType(z / 14.375);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUOrientationRollGetter0(BrickIMU.Orientation value, BrickIMUConfig cfg) {
        return new QuantityType<>(value.roll / 100.0, SmartHomeUnits.DEGREE_ANGLE);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUOrientationPitchGetter0(BrickIMU.Orientation value, BrickIMUConfig cfg) {
        return new QuantityType<>(value.pitch / 100.0, SmartHomeUnits.DEGREE_ANGLE);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUOrientationYawGetter0(BrickIMU.Orientation value, BrickIMUConfig cfg) {
        return new QuantityType<>(value.yaw / 100.0, SmartHomeUnits.DEGREE_ANGLE);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUQuaternionXGetter0(BrickIMU.Quaternion value, BrickIMUConfig cfg) {
        return new DecimalType(value.x);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUQuaternionYGetter0(BrickIMU.Quaternion value, BrickIMUConfig cfg) {
        return new DecimalType(value.y);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUQuaternionZGetter0(BrickIMU.Quaternion value, BrickIMUConfig cfg) {
        return new DecimalType(value.z);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUQuaternionWGetter0(BrickIMU.Quaternion value, BrickIMUConfig cfg) {
        return new DecimalType(value.w);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUEnableLEDsGetter0(boolean value, BrickIMUConfig cfg) {
        return value? OnOffType.ON : OnOffType.OFF;
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUAccelerationXGetter0(BrickIMU.Acceleration value, BrickIMUConfig cfg) {
        return new QuantityType<>(value.x / 1000.0, SmartHomeUnits.STANDARD_GRAVITY);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUAccelerationYGetter0(BrickIMU.Acceleration value, BrickIMUConfig cfg) {
        return new QuantityType<>(value.y / 1000.0, SmartHomeUnits.STANDARD_GRAVITY);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUAccelerationZGetter0(BrickIMU.Acceleration value, BrickIMUConfig cfg) {
        return new QuantityType<>(value.z / 1000.0, SmartHomeUnits.STANDARD_GRAVITY);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUMagneticFieldXGetter0(BrickIMU.MagneticField value, BrickIMUConfig cfg) {
        return new QuantityType<>(value.x / 10000000.0, SmartHomeUnits.TESLA);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUMagneticFieldYGetter0(BrickIMU.MagneticField value, BrickIMUConfig cfg) {
        return new QuantityType<>(value.y / 10000000.0, SmartHomeUnits.TESLA);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUMagneticFieldZGetter0(BrickIMU.MagneticField value, BrickIMUConfig cfg) {
        return new QuantityType<>(value.z / 10000000.0, SmartHomeUnits.TESLA);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUAngularVelocityXGetter0(BrickIMU.AngularVelocity value, BrickIMUConfig cfg) {
        return new DecimalType(value.x / 14.375);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUAngularVelocityYGetter0(BrickIMU.AngularVelocity value, BrickIMUConfig cfg) {
        return new DecimalType(value.y / 14.375);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickIMUAngularVelocityZGetter0(BrickIMU.AngularVelocity value, BrickIMUConfig cfg) {
        return new DecimalType(value.z / 14.375);
    }

}