/**
 * 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.StringType;

import com.tinkerforge.BrickletRS485;
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 RS485 Bricklet.
 * @author Erik Fleckstein - Initial contribution
 */
@NonNullByDefault
public class BrickletRS485Wrapper extends BrickletRS485 implements CoMCUFlashable, DeviceWrapper {
    public static final DeviceInfo DEVICE_INFO = new DeviceInfo(BrickletRS485.DEVICE_DISPLAY_NAME, "brickletrs485", BrickletRS485.DEVICE_IDENTIFIER, BrickletRS485Wrapper.class, BrickletRS485Actions.class, "2.0.5", true);

    public BrickletRS485Wrapper(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(BrickletRS485Wrapper.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);
        BrickletRS485Config cfg = (BrickletRS485Config) config.as(BrickletRS485Config.class);
        this.addFrameReadableListener(this.reg((frameCount) -> {if(true) {triggerChannelFn.accept("BrickletRS485FrameReadable", transformBrickletRS485FrameReadableCallback0(frameCount, cfg));}}, this::removeFrameReadableListener));
		this.addErrorCountListener(this.reg((overrunErrorCount, parityErrorCount) -> {if(true) {updateStateFn.accept("BrickletRS485OverrunErrorCount", transformBrickletRS485OverrunErrorCountCallback0(overrunErrorCount, parityErrorCount, cfg));}}, this::removeErrorCountListener));
		this.addErrorCountListener(this.reg((overrunErrorCount, parityErrorCount) -> {if(true) {updateStateFn.accept("BrickletRS485ParityErrorCount", transformBrickletRS485ParityErrorCountCallback0(overrunErrorCount, parityErrorCount, cfg));}}, this::removeErrorCountListener));
        this.setRS485Configuration(cfg.baudRate, cfg.parity, cfg.stopBits, cfg.wordLength, cfg.duplex);
		    this.setBufferConfig(cfg.sendBufferSize, 10240 - cfg.sendBufferSize);
		    this.setMode(cfg.mode);
		    this.setModbusConfiguration(1, cfg.masterRequestTimeout);
		    this.setFrameReadableCallbackConfiguration(cfg.frameSize);
		    this.setCommunicationLEDConfig(cfg.communicationLEDConfig);
		    this.setErrorLEDConfig(cfg.errorLEDConfig);
		this.setStatusLEDConfig(cfg.statusLEDConfig);
		if (cfg.mode != 0) {
		BrickletRS485ModbusErrorConfig channelCfg = getChannelConfigFn.apply("BrickletRS485TimeoutErrorCount").as(BrickletRS485ModbusErrorConfig.class);
		
		if(channelCfg.updateInterval > 0) {
    this.manualChannelUpdates.add(scheduler.scheduleWithFixedDelay(() -> {if(handler.getThing().getStatus() == ThingStatus.ONLINE) {handler.handleCommand(new ChannelUID(handler.getThing().getUID(), "BrickletRS485TimeoutErrorCount"), RefreshType.REFRESH);}}, channelCfg.updateInterval, channelCfg.updateInterval, TimeUnit.MILLISECONDS));
}
		}
		if (cfg.mode != 0) {
		BrickletRS485ModbusErrorConfig channelCfg = getChannelConfigFn.apply("BrickletRS485ChecksumErrorCount").as(BrickletRS485ModbusErrorConfig.class);
		
		if(channelCfg.updateInterval > 0) {
    this.manualChannelUpdates.add(scheduler.scheduleWithFixedDelay(() -> {if(handler.getThing().getStatus() == ThingStatus.ONLINE) {handler.handleCommand(new ChannelUID(handler.getThing().getUID(), "BrickletRS485ChecksumErrorCount"), RefreshType.REFRESH);}}, channelCfg.updateInterval, channelCfg.updateInterval, TimeUnit.MILLISECONDS));
}
		}
		if (cfg.mode != 0) {
		BrickletRS485ModbusErrorConfig channelCfg = getChannelConfigFn.apply("BrickletRS485FrameTooBigErrorCount").as(BrickletRS485ModbusErrorConfig.class);
		
		if(channelCfg.updateInterval > 0) {
    this.manualChannelUpdates.add(scheduler.scheduleWithFixedDelay(() -> {if(handler.getThing().getStatus() == ThingStatus.ONLINE) {handler.handleCommand(new ChannelUID(handler.getThing().getUID(), "BrickletRS485FrameTooBigErrorCount"), RefreshType.REFRESH);}}, channelCfg.updateInterval, channelCfg.updateInterval, TimeUnit.MILLISECONDS));
}
		}
		if (cfg.mode != 0) {
		BrickletRS485ModbusErrorConfig channelCfg = getChannelConfigFn.apply("BrickletRS485IllegalFunctionErrorCount").as(BrickletRS485ModbusErrorConfig.class);
		
		if(channelCfg.updateInterval > 0) {
    this.manualChannelUpdates.add(scheduler.scheduleWithFixedDelay(() -> {if(handler.getThing().getStatus() == ThingStatus.ONLINE) {handler.handleCommand(new ChannelUID(handler.getThing().getUID(), "BrickletRS485IllegalFunctionErrorCount"), RefreshType.REFRESH);}}, channelCfg.updateInterval, channelCfg.updateInterval, TimeUnit.MILLISECONDS));
}
		}
		if (cfg.mode != 0) {
		BrickletRS485ModbusErrorConfig channelCfg = getChannelConfigFn.apply("BrickletRS485IllegalDataAddressErrorCount").as(BrickletRS485ModbusErrorConfig.class);
		
		if(channelCfg.updateInterval > 0) {
    this.manualChannelUpdates.add(scheduler.scheduleWithFixedDelay(() -> {if(handler.getThing().getStatus() == ThingStatus.ONLINE) {handler.handleCommand(new ChannelUID(handler.getThing().getUID(), "BrickletRS485IllegalDataAddressErrorCount"), RefreshType.REFRESH);}}, channelCfg.updateInterval, channelCfg.updateInterval, TimeUnit.MILLISECONDS));
}
		}
		if (cfg.mode != 0) {
		BrickletRS485ModbusErrorConfig channelCfg = getChannelConfigFn.apply("BrickletRS485IllegalDataValueErrorCount").as(BrickletRS485ModbusErrorConfig.class);
		
		if(channelCfg.updateInterval > 0) {
    this.manualChannelUpdates.add(scheduler.scheduleWithFixedDelay(() -> {if(handler.getThing().getStatus() == ThingStatus.ONLINE) {handler.handleCommand(new ChannelUID(handler.getThing().getUID(), "BrickletRS485IllegalDataValueErrorCount"), RefreshType.REFRESH);}}, channelCfg.updateInterval, channelCfg.updateInterval, TimeUnit.MILLISECONDS));
}
		}
		if (cfg.mode != 0) {
		BrickletRS485ModbusErrorConfig channelCfg = getChannelConfigFn.apply("BrickletRS485SlaveDeviceFailureErrorCount").as(BrickletRS485ModbusErrorConfig.class);
		
		if(channelCfg.updateInterval > 0) {
    this.manualChannelUpdates.add(scheduler.scheduleWithFixedDelay(() -> {if(handler.getThing().getStatus() == ThingStatus.ONLINE) {handler.handleCommand(new ChannelUID(handler.getThing().getUID(), "BrickletRS485SlaveDeviceFailureErrorCount"), RefreshType.REFRESH);}}, channelCfg.updateInterval, channelCfg.updateInterval, TimeUnit.MILLISECONDS));
}
		}
		{
		BrickletRS485SendBufferUsedConfig channelCfg = getChannelConfigFn.apply("BrickletRS485SendBufferUsed").as(BrickletRS485SendBufferUsedConfig.class);
		
		if(channelCfg.updateInterval > 0) {
    this.manualChannelUpdates.add(scheduler.scheduleWithFixedDelay(() -> {if(handler.getThing().getStatus() == ThingStatus.ONLINE) {handler.handleCommand(new ChannelUID(handler.getThing().getUID(), "BrickletRS485SendBufferUsed"), RefreshType.REFRESH);}}, channelCfg.updateInterval, channelCfg.updateInterval, TimeUnit.MILLISECONDS));
}
		}
		{
		BrickletRS485ReceiveBufferUsedConfig channelCfg = getChannelConfigFn.apply("BrickletRS485ReceiveBufferUsed").as(BrickletRS485ReceiveBufferUsedConfig.class);
		
		if(channelCfg.updateInterval > 0) {
    this.manualChannelUpdates.add(scheduler.scheduleWithFixedDelay(() -> {if(handler.getThing().getStatus() == ThingStatus.ONLINE) {handler.handleCommand(new ChannelUID(handler.getThing().getUID(), "BrickletRS485ReceiveBufferUsed"), 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{
        BrickletRS485Config cfg = (BrickletRS485Config) config.as(BrickletRS485Config.class);
List<String> result = new ArrayList<String>();
        result.add("BrickletRS485FrameReadable");
		result.add("BrickletRS485OverrunErrorCount");
		result.add("BrickletRS485ParityErrorCount");
		if (cfg.mode != 0) {
                result.add("BrickletRS485TimeoutErrorCount");
            }
		if (cfg.mode != 0) {
                result.add("BrickletRS485ChecksumErrorCount");
            }
		if (cfg.mode != 0) {
                result.add("BrickletRS485FrameTooBigErrorCount");
            }
		if (cfg.mode != 0) {
                result.add("BrickletRS485IllegalFunctionErrorCount");
            }
		if (cfg.mode != 0) {
                result.add("BrickletRS485IllegalDataAddressErrorCount");
            }
		if (cfg.mode != 0) {
                result.add("BrickletRS485IllegalDataValueErrorCount");
            }
		if (cfg.mode != 0) {
                result.add("BrickletRS485SlaveDeviceFailureErrorCount");
            }
		result.add("BrickletRS485SendBufferUsed");
		result.add("BrickletRS485ReceiveBufferUsed");
		if (cfg.errorLEDConfig == 3) {
                result.add("BrickletRS485ClearErrorLED");
            }
        return result;
    }

    public static @Nullable ChannelType getChannelType(ChannelTypeUID channelTypeUID) {
        switch(channelTypeUID.getId()) {
            case "BrickletRS485OverrunErrorCount":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletRS485OverrunErrorCount"), "Overrun Error Count", "Number:Dimensionless").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletRS485OverrunErrorCount")).withDescription("The current number of overrun errors")
.withStateDescription(StateDescriptionFragmentBuilder.create().withPattern("%d").withReadOnly(true).build().toStateDescription()).build();
            case "BrickletRS485ParityErrorCount":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletRS485ParityErrorCount"), "Framing Error Count", "Number:Dimensionless").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletRS485ParityErrorCount")).withDescription("The current number of parity errors")
.withStateDescription(StateDescriptionFragmentBuilder.create().withPattern("%d").withReadOnly(true).build().toStateDescription()).build();
            case "BrickletRS485ModbusError":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletRS485ModbusError"), "NOT USED", "Number:Dimensionless").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletRS485ModbusError")).withDescription("NOT USED")
.withStateDescription(StateDescriptionFragmentBuilder.create().withPattern("%d").withReadOnly(true).build().toStateDescription()).build();
            case "BrickletRS485SendBufferUsed":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletRS485SendBufferUsed"), "Send Buffer Used", "Number:DataAmount").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletRS485SendBufferUsed")).withDescription("The number of bytes currently in the send buffer")
.withStateDescription(StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(9216)).withStep(BigDecimal.valueOf(1)).withPattern("%d %unit%").withReadOnly(true).build().toStateDescription()).build();
            case "BrickletRS485ReceiveBufferUsed":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletRS485ReceiveBufferUsed"), "Receive Buffer Used", "Number:DataAmount").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletRS485ReceiveBufferUsed")).withDescription("The number of bytes currently in the receive buffer")
.withStateDescription(StateDescriptionFragmentBuilder.create().withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(9216)).withStep(BigDecimal.valueOf(1)).withPattern("%d %unit%").withReadOnly(true).build().toStateDescription()).build();
            case "BrickletRS485ClearErrorLED":
                return ChannelTypeBuilder.state(new ChannelTypeUID("tinkerforge", "BrickletRS485ClearErrorLED"), "Clear Error LED", "String").withConfigDescriptionURI(URI.create("channel-type:tinkerforge:BrickletRS485ClearErrorLED")).withDescription("Clears the error LED.")
.withCommandDescription(CommandDescriptionBuilder.create().withCommandOption(new CommandOption("CLEAR", "Clear")).build()).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 RS485 Bricklet").isListed(false).withSupportedBridgeTypeUIDs(Arrays.asList(TinkerforgeBindingConstants.THING_TYPE_BRICK_DAEMON.toString())).withConfigDescriptionURI(URI.create("thing-type:tinkerforge:" + thingTypeUID.getId())).withDescription("Communicates with RS485/Modbus devices with full- or half-duplex").withChannelDefinitions(Arrays.asList(new ChannelDefinitionBuilder("BrickletRS485FrameReadable", new ChannelTypeUID("system", "trigger")).withLabel("Frame Readable").withDescription("This channel is triggered in when a new frame was received and can be read out. The channel will only trigger again if the frame was read.").build(), new ChannelDefinitionBuilder("BrickletRS485OverrunErrorCount", new ChannelTypeUID("tinkerforge", "BrickletRS485OverrunErrorCount")).withLabel("Overrun Error Count").build(), new ChannelDefinitionBuilder("BrickletRS485ParityErrorCount", new ChannelTypeUID("tinkerforge", "BrickletRS485ParityErrorCount")).withLabel("Parity Error Count").build(), new ChannelDefinitionBuilder("BrickletRS485TimeoutErrorCount", new ChannelTypeUID("tinkerforge", "BrickletRS485ModbusError")).withLabel("Timeout Error Count").withDescription("Number of timeouts occurred.").build(), new ChannelDefinitionBuilder("BrickletRS485ChecksumErrorCount", new ChannelTypeUID("tinkerforge", "BrickletRS485ModbusError")).withLabel("Checksum Error Count").withDescription("Number of failures due to Modbus frame CRC16 checksum mismatch.").build(), new ChannelDefinitionBuilder("BrickletRS485FrameTooBigErrorCount", new ChannelTypeUID("tinkerforge", "BrickletRS485ModbusError")).withLabel("Frame Too Big Error Count").withDescription("Number of times frames were rejected because they exceeded maximum Modbus frame size which is 256 bytes.").build(), new ChannelDefinitionBuilder("BrickletRS485IllegalFunctionErrorCount", new ChannelTypeUID("tinkerforge", "BrickletRS485ModbusError")).withLabel("Illegal Function Error Count").withDescription("Number of errors when an unimplemented or illegal function is requested. This corresponds to Modbus exception code 1.").build(), new ChannelDefinitionBuilder("BrickletRS485IllegalDataAddressErrorCount", new ChannelTypeUID("tinkerforge", "BrickletRS485ModbusError")).withLabel("Illegal Data Address Error Count").withDescription("Number of errors due to invalid data address. This corresponds to Modbus exception code 2.").build(), new ChannelDefinitionBuilder("BrickletRS485IllegalDataValueErrorCount", new ChannelTypeUID("tinkerforge", "BrickletRS485ModbusError")).withLabel("Illegal Data Value Error Count").withDescription("Number of errors due to invalid data value. This corresponds to Modbus exception code 3.").build(), new ChannelDefinitionBuilder("BrickletRS485SlaveDeviceFailureErrorCount", new ChannelTypeUID("tinkerforge", "BrickletRS485ModbusError")).withLabel("Slave Device Failure Error Count").withDescription("Number of errors occurred on the slave device which were unrecoverable. This corresponds to Modbus exception code 4.").build(), new ChannelDefinitionBuilder("BrickletRS485SendBufferUsed", new ChannelTypeUID("tinkerforge", "BrickletRS485SendBufferUsed")).withLabel("Send Buffer Used").build(), new ChannelDefinitionBuilder("BrickletRS485ReceiveBufferUsed", new ChannelTypeUID("tinkerforge", "BrickletRS485ReceiveBufferUsed")).withLabel("Receive Buffer Used").build(), new ChannelDefinitionBuilder("BrickletRS485ClearErrorLED", new ChannelTypeUID("tinkerforge", "BrickletRS485ClearErrorLED")).withLabel("Clear Error LED").build())).withProperties(props).build();
    }

    public static @Nullable ConfigDescription getConfigDescription(URI uri) {
        switch(uri.toASCIIString()) {
            case "thing-type:tinkerforge:brickletrs485":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList(ConfigDescriptionParameterBuilder.create("mode", Type.INTEGER).withDefault("0").withDescription("The mode of the Bricklet in which it operates.").withLabel("Mode").withLimitToOptions(true).withOptions(Arrays.asList(new ParameterOption("0", "RS485"), new ParameterOption("1", "Modbus Master RTU"))).build(), ConfigDescriptionParameterBuilder.create("baudRate", Type.INTEGER).withDefault("115200").withDescription("The baud rate to send/receive with.").withGroupName("RS485").withLabel("Baud Rate").withMinimum(BigDecimal.valueOf(100)).withMaximum(BigDecimal.valueOf(2000000)).build(), ConfigDescriptionParameterBuilder.create("parity", Type.INTEGER).withDefault("0").withDescription("The parity mode to use. See here: https://en.wikipedia.org/wiki/Serial_port#Parity.").withGroupName("RS485").withLabel("Parity").withLimitToOptions(true).withOptions(Arrays.asList(new ParameterOption("0", "None"), new ParameterOption("1", "Odd"), new ParameterOption("2", "Even"))).build(), ConfigDescriptionParameterBuilder.create("stopBits", Type.INTEGER).withDefault("1").withDescription("The number of stop bits to send/expect.").withGroupName("RS485").withLabel("Stop Bits").withLimitToOptions(true).withOptions(Arrays.asList(new ParameterOption("1", "1"), new ParameterOption("2", "2"))).build(), ConfigDescriptionParameterBuilder.create("wordLength", Type.INTEGER).withDefault("8").withDescription("The length of a serial word. Typically one byte.").withGroupName("RS485").withLabel("Word Length").withLimitToOptions(true).withOptions(Arrays.asList(new ParameterOption("5", "5"), new ParameterOption("6", "6"), new ParameterOption("7", "7"), new ParameterOption("8", "8"))).build(), ConfigDescriptionParameterBuilder.create("duplex", Type.INTEGER).withDefault("0").withDescription("The flow control mechanism to use. Software uses control characters in-band. Hardware uses the RTS and CTS lines.").withGroupName("RS485").withLabel("Duplex").withLimitToOptions(true).withOptions(Arrays.asList(new ParameterOption("0", "Half"), new ParameterOption("1", "Full"))).build(), ConfigDescriptionParameterBuilder.create("sendBufferSize", Type.INTEGER).withDefault("5120").withDescription("The send buffer size in bytes. In total the send and receive buffers are 10240 byte (10 KiB) in size. The minimum buffer size is 1024 byte (1 KiB) each. The binding will configure the read buffer size accordingly. The send buffer holds data that is given by the user and can not be written to RS232 yet. The receive buffer holds data that is received through RS232 but could not yet be send to the user.").withLabel("Send Buffer Size").withAdvanced(true).withMinimum(BigDecimal.valueOf(1024)).withMaximum(BigDecimal.valueOf(9216)).build(), ConfigDescriptionParameterBuilder.create("frameSize", Type.INTEGER).withDefault("1").withDescription("The size of receivable data frames in bytes. Set this to something other than 1, if you want to receive data with a fix frame size. The frame readable channel will trigger every time a frame of this size is ready to be read, but will wait until this frame is read before triggering again. This means, you can use this channel as a trigger in a rule, that will read exactly one frame.").withGroupName("RS485").withLabel("Frame Size").withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(9216)).build(), ConfigDescriptionParameterBuilder.create("masterRequestTimeout", Type.INTEGER).withDefault("1000").withDescription("Time in milliseconds that the master should wait for a response from a slave when in Modbus master mode.").withGroupName("Modbus Master").withLabel("Request Timeout").withMinimum(BigDecimal.valueOf(0)).withMaximum(BigDecimal.valueOf(4294967295L)).build(), ConfigDescriptionParameterBuilder.create("communicationLEDConfig", Type.INTEGER).withDefault("3").withDescription("By default the LED shows RS485 communication traffic by flickering. You can also turn the LED permanently on/off or show a heartbeat. If the Bricklet is in bootloader mode, the LED is off.").withLabel("Communication LED Configuration").withAdvanced(true).withLimitToOptions(true).withOptions(Arrays.asList(new ParameterOption("0", "Off"), new ParameterOption("1", "On"), new ParameterOption("2", "Show Heartbeat"), new ParameterOption("3", "Show Communication"))).build(), ConfigDescriptionParameterBuilder.create("errorLEDConfig", Type.INTEGER).withDefault("3").withDescription("By default the error LED turns on if there is any error (see FrameErrorCountListener callback). You can also turn the LED permanently on/off or show a heartbeat. If the Bricklet is in bootloader mode, the LED is off.").withLabel("Error LED Configuration").withAdvanced(true).withLimitToOptions(true).withOptions(Arrays.asList(new ParameterOption("0", "Off"), new ParameterOption("1", "On"), new ParameterOption("2", "Show Heartbeat"), new ParameterOption("3", "Show Error"))).build(), ConfigDescriptionParameterBuilder.create("statusLEDConfig", Type.INTEGER).withDefault("3").withDescription("The status LED configuration. By default the LED shows communication traffic between Brick and Bricklet, it flickers once for every 10 received data packets.<br/><br/>You can also turn the LED permanently on/off or show a heartbeat.<br/><br/>If the Bricklet is in bootloader mode, the LED is will show heartbeat by default.").withLabel("Status LED Configuration").withAdvanced(true).withLimitToOptions(true).withOptions(Arrays.asList(new ParameterOption("0", "Off"), new ParameterOption("1", "On"), new ParameterOption("2", "Show Heartbeat"), new ParameterOption("3", "Show Status"))).build())).withParameterGroups(Arrays.asList(new ConfigDescriptionParameterGroup("update_intervals", "null", true, "Update Intervals", "Update Intervals"), new ConfigDescriptionParameterGroup("RS485", "null", false, "RS485", "Settings only used in RS485 mode"), new ConfigDescriptionParameterGroup("Modbus Master", "null", false, "Modbus Master", "Settings only used in Modbus Master RTU mode"))).build();
            case "channel-type:tinkerforge:BrickletRS485OverrunErrorCount":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickletRS485ParityErrorCount":
                return ConfigDescriptionBuilder.create(uri).withParameters(Arrays.asList()).withParameterGroups(Arrays.asList()).build();
            case "channel-type:tinkerforge:BrickletRS485ModbusError":
                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:BrickletRS485SendBufferUsed":
                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:BrickletRS485ReceiveBufferUsed":
                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:BrickletRS485ClearErrorLED":
                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 {
        BrickletRS485Config cfg = (BrickletRS485Config) config.as(BrickletRS485Config.class);
switch(channel) {
            case "BrickletRS485FrameReadable":
               return;
            case "BrickletRS485OverrunErrorCount":
                   {
            BrickletRS485.ErrorCount value = this.getErrorCount();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS485OverrunErrorCountGetter0(value, cfg));
        }
                   return;
            case "BrickletRS485ParityErrorCount":
                   {
            BrickletRS485.ErrorCount value = this.getErrorCount();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS485ParityErrorCountGetter0(value, cfg));
        }
                   return;
            case "BrickletRS485TimeoutErrorCount":
                   {
            BrickletRS485.ModbusCommonErrorCount value = this.getModbusCommonErrorCount();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS485TimeoutErrorCountGetter0(value, cfg));
        }
                   return;
            case "BrickletRS485ChecksumErrorCount":
                   {
            BrickletRS485.ModbusCommonErrorCount value = this.getModbusCommonErrorCount();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS485ChecksumErrorCountGetter0(value, cfg));
        }
                   return;
            case "BrickletRS485FrameTooBigErrorCount":
                   {
            BrickletRS485.ModbusCommonErrorCount value = this.getModbusCommonErrorCount();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS485FrameTooBigErrorCountGetter0(value, cfg));
        }
                   return;
            case "BrickletRS485IllegalFunctionErrorCount":
                   {
            BrickletRS485.ModbusCommonErrorCount value = this.getModbusCommonErrorCount();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS485IllegalFunctionErrorCountGetter0(value, cfg));
        }
                   return;
            case "BrickletRS485IllegalDataAddressErrorCount":
                   {
            BrickletRS485.ModbusCommonErrorCount value = this.getModbusCommonErrorCount();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS485IllegalDataAddressErrorCountGetter0(value, cfg));
        }
                   return;
            case "BrickletRS485IllegalDataValueErrorCount":
                   {
            BrickletRS485.ModbusCommonErrorCount value = this.getModbusCommonErrorCount();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS485IllegalDataValueErrorCountGetter0(value, cfg));
        }
                   return;
            case "BrickletRS485SlaveDeviceFailureErrorCount":
                   {
            BrickletRS485.ModbusCommonErrorCount value = this.getModbusCommonErrorCount();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS485SlaveDeviceFailureErrorCountGetter0(value, cfg));
        }
                   return;
            case "BrickletRS485SendBufferUsed":
                   {
            BrickletRS485.BufferStatus value = this.getBufferStatus();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS485SendBufferUsedGetter0(value, cfg));
        }
                   return;
            case "BrickletRS485ReceiveBufferUsed":
                   {
            BrickletRS485.BufferStatus value = this.getBufferStatus();
            if(true)
                updateStateFn.accept(channel, transformBrickletRS485ReceiveBufferUsedGetter0(value, cfg));
        }
                   return;
            case "BrickletRS485ClearErrorLED":
               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 "BrickletRS485ClearErrorLED":
                if (command instanceof StringType) {
                    this.setErrorLEDConfig(3);
                }
        
                else {
                    logger.warn("Command type {} not supported for channel {}. Please use one of StringType.", command.getClass().getName(), channel);
                }
                
                break;
default:
                logger.warn("Command for unknown channel {}", channel);
        }
        return result;
    }

        private String transformBrickletRS485FrameReadableCallback0(int frameCount, BrickletRS485Config cfg) {
        return "";
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS485OverrunErrorCountCallback0(long overrunErrorCount, long parityErrorCount, BrickletRS485Config cfg) {
        return new DecimalType(overrunErrorCount);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS485ParityErrorCountCallback0(long overrunErrorCount, long parityErrorCount, BrickletRS485Config cfg) {
        return new DecimalType(parityErrorCount);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS485OverrunErrorCountGetter0(BrickletRS485.ErrorCount value, BrickletRS485Config cfg) {
        return new DecimalType(value.overrunErrorCount);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS485ParityErrorCountGetter0(BrickletRS485.ErrorCount value, BrickletRS485Config cfg) {
        return new DecimalType(value.parityErrorCount);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS485TimeoutErrorCountGetter0(BrickletRS485.ModbusCommonErrorCount value, BrickletRS485Config cfg) {
        return new DecimalType(value.timeoutErrorCount);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS485ChecksumErrorCountGetter0(BrickletRS485.ModbusCommonErrorCount value, BrickletRS485Config cfg) {
        return new DecimalType(value.checksumErrorCount);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS485FrameTooBigErrorCountGetter0(BrickletRS485.ModbusCommonErrorCount value, BrickletRS485Config cfg) {
        return new DecimalType(value.frameTooBigErrorCount);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS485IllegalFunctionErrorCountGetter0(BrickletRS485.ModbusCommonErrorCount value, BrickletRS485Config cfg) {
        return new DecimalType(value.illegalFunctionErrorCount);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS485IllegalDataAddressErrorCountGetter0(BrickletRS485.ModbusCommonErrorCount value, BrickletRS485Config cfg) {
        return new DecimalType(value.illegalDataAddressErrorCount);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS485IllegalDataValueErrorCountGetter0(BrickletRS485.ModbusCommonErrorCount value, BrickletRS485Config cfg) {
        return new DecimalType(value.illegalDataValueErrorCount);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS485SlaveDeviceFailureErrorCountGetter0(BrickletRS485.ModbusCommonErrorCount value, BrickletRS485Config cfg) {
        return new DecimalType(value.slaveDeviceFailureErrorCount);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS485SendBufferUsedGetter0(BrickletRS485.BufferStatus value, BrickletRS485Config cfg) {
        return new QuantityType<>(value.sendBufferUsed, SmartHomeUnits.BYTE);
    }
	    private org.eclipse.smarthome.core.types.State transformBrickletRS485ReceiveBufferUsedGetter0(BrickletRS485.BufferStatus value, BrickletRS485Config cfg) {
        return new QuantityType<>(value.receiveBufferUsed, SmartHomeUnits.BYTE);
    }

}