<commit_before>/**
 * Copyright (c) 2010-2015, openHAB.org and others.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package org.openhab.binding.modbus.internal;

import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import net.wimpi.modbus.procimg.InputRegister;
import net.wimpi.modbus.util.BitVector;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.openhab.binding.modbus.ModbusBindingProvider;
import org.openhab.binding.modbus.internal.ModbusGenericBindingProvider.ModbusBindingConfig;
import org.openhab.core.binding.AbstractActiveBinding;
import org.openhab.core.binding.BindingProvider;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Modbus binding allows to connect to multiple Modbus slaves as TCP master.
 * This implementation works with coils (boolean values) only.
 * 
 * @author <NAME>
 * @since 1.1.0
 */
public class ModbusBinding extends AbstractActiveBinding<ModbusBindingProvider> implements ManagedService {
	
	private static final Logger logger = LoggerFactory.getLogger(ModbusBinding.class);

	private static final String UDP_PREFIX = "udp";
	private static final String TCP_PREFIX = "tcp";
	private static final String SERIAL_PREFIX = "serial";

	private static final String VALID_COFIG_KEYS = "connection|id|start|length|type|valuetype|rawdatamultiplier|writemultipleregisters";
	private static final Pattern EXTRACT_MODBUS_CONFIG_PATTERN =
		Pattern.compile("^("+TCP_PREFIX+"|"+UDP_PREFIX+"|"+SERIAL_PREFIX+"|)\\.(.*?)\\.(" + VALID_COFIG_KEYS + ")$");

	/** Stores instances of all the slaves defined in cfg file */
	private static Map<String, ModbusSlave> modbusSlaves = new ConcurrentHashMap<String, ModbusSlave>();

	/** slaves update interval in milliseconds, defaults to 200ms */
	public static int pollInterval = 200;

	
	public void activate() {
	}

	public void deactivate() {
	}
	
	
	@Override
	protected long getRefreshInterval() {
		return 	pollInterval;
	}

	@Override
	protected String getName() {
		return "Modbus Polling Service";
	}
	

	/**
	 * Parses configuration creating Modbus slave instances defined in cfg file
	 * {@inheritDoc}
	 */
	protected void internalReceiveCommand(String itemName, Command command) {
		for (ModbusBindingProvider provider : providers) {
			if (provider.providesBindingFor(itemName)) {
				ModbusBindingConfig config = provider.getConfig(itemName);
				ModbusSlave slave = modbusSlaves.get(config.slaveName);
				slave.executeCommand(command, config.readRegister, config.writeRegister);
			}
		}
	}

	/**
	 * Posts update event to OpenHAB bus for "holding" type slaves
	 * @param binding ModbusBinding to get item configuration from BindingProviding
	 * @param registers data received from slave device in the last pollInterval
	 * @param itemName item to update
	 */
	protected void internalUpdateItem(String slaveName, InputRegister[] registers,
			String itemName) {
		for (ModbusBindingProvider provider : providers) {
			if ( !provider.providesBindingFor(itemName) ) {
				continue;
			}
			ModbusBindingConfig config = provider.getConfig(itemName);
			if ( !config.slaveName.equals(slaveName)) {
				continue;
			}

			String slaveValueType = modbusSlaves.get(slaveName).getValueType();
			double rawDataMultiplier = modbusSlaves.get(slaveName).getRawDataMultiplier();

			State newState = extractStateFromRegisters(registers, config.readRegister, slaveValueType);
			/* receive data manipulation */
			if (config.getItem() instanceof SwitchItem) {
				newState = newState.equals(DecimalType.ZERO) ? OnOffType.OFF : OnOffType.ON;
			}
			if (( rawDataMultiplier != 1 ) && (config.getItem() instanceof NumberItem)) {
				double tmpValue = (double)((DecimalType)newState).doubleValue() * rawDataMultiplier;
				newState =  new DecimalType( String.valueOf(tmpValue) );
			}

			State currentState = config.getItemState();
			if (! newState.equals(currentState)) {
				eventPublisher.postUpdate(itemName, newState);
			}
		}
	}

	private DecimalType extractStateFromRegisters(InputRegister[] registers, int index, String type) {
		if (type.equals(ModbusBindingProvider.VALUE_TYPE_BIT)) {
			return new DecimalType((registers[index / 16].toUnsignedShort() >> (index % 16)) & 1);
		}
		else if (type.equals(ModbusBindingProvider.VALUE_TYPE_INT8)) {
			return new DecimalType(registers[index / 2].toBytes()[1 - (index % 2)]);
		}
		else if (type.equals(ModbusBindingProvider.VALUE_TYPE_UINT8)) {
			return new DecimalType((registers[index / 2].toUnsignedShort() >> (8 * (index % 2))) & 0xff);
		}
		else if (type.equals(ModbusBindingProvider.VALUE_TYPE_INT16)) {
			ByteBuffer buff = ByteBuffer.allocate(2);
			buff.put(registers[index].toBytes());
			return new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getShort(0));
		}
		else if (type.equals(ModbusBindingProvider.VALUE_TYPE_UINT16)) {
			return new DecimalType(registers[index].toUnsignedShort());
		}
		else if (type.equals(ModbusBindingProvider.VALUE_TYPE_INT32)) {
			ByteBuffer buff = ByteBuffer.allocate(4);
			buff.put(registers[index * 2 + 0].toBytes());
			buff.put(registers[index * 2 + 1].toBytes());
			return new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getInt(0));
		}
		else if (type.equals(ModbusBindingProvider.VALUE_TYPE_UINT32)) {
			ByteBuffer buff = ByteBuffer.allocate(8);
			buff.position(4);
			buff.put(registers[index * 2 + 0].toBytes());
			buff.put(registers[index * 2 + 1].toBytes());
			return new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getLong(0));
		}
		else if (type.equals(ModbusBindingProvider.VALUE_TYPE_FLOAT32)) {
			ByteBuffer buff = ByteBuffer.allocate(4);
			buff.put(registers[index * 2 + 0].toBytes());
			buff.put(registers[index * 2 + 1].toBytes());
			return new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getFloat(0));
		}
		else {
			throw new IllegalArgumentException();
		}
	}

	/**
	 * Posts update event to OpenHAB bus for "coil" type slaves
	 * @param binding ModbusBinding to get item configuration from BindingProviding
	 * @param registers data received from slave device in the last pollInterval
	 * @param item item to update<commit_msg>Fix word ordering issue when combinign two 16-bit registers into a single int32<commit_after>/**
 * Copyright (c) 2010-2015, openHAB.org and others.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
package org.openhab.binding.modbus.internal;

import java.util.Collection;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import net.wimpi.modbus.procimg.InputRegister;
import net.wimpi.modbus.util.BitVector;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.openhab.binding.modbus.ModbusBindingProvider;
import org.openhab.binding.modbus.internal.ModbusGenericBindingProvider.ModbusBindingConfig;
import org.openhab.core.binding.AbstractActiveBinding;
import org.openhab.core.binding.BindingProvider;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * Modbus binding allows to connect to multiple Modbus slaves as TCP master.
 * This implementation works with coils (boolean values) only.
 * 
 * @author <NAME>
 * @since 1.1.0
 */
public class ModbusBinding extends AbstractActiveBinding<ModbusBindingProvider> implements ManagedService {
	
	private static final Logger logger = LoggerFactory.getLogger(ModbusBinding.class);

	private static final String UDP_PREFIX = "udp";
	private static final String TCP_PREFIX = "tcp";
	private static final String SERIAL_PREFIX = "serial";

	private static final String VALID_COFIG_KEYS = "connection|id|start|length|type|valuetype|rawdatamultiplier|writemultipleregisters";
	private static final Pattern EXTRACT_MODBUS_CONFIG_PATTERN =
		Pattern.compile("^("+TCP_PREFIX+"|"+UDP_PREFIX+"|"+SERIAL_PREFIX+"|)\\.(.*?)\\.(" + VALID_COFIG_KEYS + ")$");

	/** Stores instances of all the slaves defined in cfg file */
	private static Map<String, ModbusSlave> modbusSlaves = new ConcurrentHashMap<String, ModbusSlave>();

	/** slaves update interval in milliseconds, defaults to 200ms */
	public static int pollInterval = 200;

	
	public void activate() {
	}

	public void deactivate() {
	}
	
	
	@Override
	protected long getRefreshInterval() {
		return 	pollInterval;
	}

	@Override
	protected String getName() {
		return "Modbus Polling Service";
	}
	

	/**
	 * Parses configuration creating Modbus slave instances defined in cfg file
	 * {@inheritDoc}
	 */
	protected void internalReceiveCommand(String itemName, Command command) {
		for (ModbusBindingProvider provider : providers) {
			if (provider.providesBindingFor(itemName)) {
				ModbusBindingConfig config = provider.getConfig(itemName);
				ModbusSlave slave = modbusSlaves.get(config.slaveName);
				slave.executeCommand(command, config.readRegister, config.writeRegister);
			}
		}
	}

	/**
	 * Posts update event to OpenHAB bus for "holding" type slaves
	 * @param binding ModbusBinding to get item configuration from BindingProviding
	 * @param registers data received from slave device in the last pollInterval
	 * @param itemName item to update
	 */
	protected void internalUpdateItem(String slaveName, InputRegister[] registers,
			String itemName) {
		for (ModbusBindingProvider provider : providers) {
			if ( !provider.providesBindingFor(itemName) ) {
				continue;
			}
			ModbusBindingConfig config = provider.getConfig(itemName);
			if ( !config.slaveName.equals(slaveName)) {
				continue;
			}

			String slaveValueType = modbusSlaves.get(slaveName).getValueType();
			double rawDataMultiplier = modbusSlaves.get(slaveName).getRawDataMultiplier();

			State newState = extractStateFromRegisters(registers, config.readRegister, slaveValueType);
			/* receive data manipulation */
			if (config.getItem() instanceof SwitchItem) {
				newState = newState.equals(DecimalType.ZERO) ? OnOffType.OFF : OnOffType.ON;
			}
			if (( rawDataMultiplier != 1 ) && (config.getItem() instanceof NumberItem)) {
				double tmpValue = (double)((DecimalType)newState).doubleValue() * rawDataMultiplier;
				newState =  new DecimalType( String.valueOf(tmpValue) );
			}

			State currentState = config.getItemState();
			if (! newState.equals(currentState)) {
				eventPublisher.postUpdate(itemName, newState);
			}
		}
	}

	private DecimalType extractStateFromRegisters(InputRegister[] registers, int index, String type) {
		if (type.equals(ModbusBindingProvider.VALUE_TYPE_BIT)) {
			return new DecimalType((registers[index / 16].toUnsignedShort() >> (index % 16)) & 1);
		}
		else if (type.equals(ModbusBindingProvider.VALUE_TYPE_INT8)) {
			return new DecimalType(registers[index / 2].toBytes()[1 - (index % 2)]);
		}
		else if (type.equals(ModbusBindingProvider.VALUE_TYPE_UINT8)) {
			return new DecimalType((registers[index / 2].toUnsignedShort() >> (8 * (index % 2))) & 0xff);
		}
		else if (type.equals(ModbusBindingProvider.VALUE_TYPE_INT16)) {
			ByteBuffer buff = ByteBuffer.allocate(2);
			buff.put(registers[index].toBytes());
			return new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getShort(0));
		}
		else if (type.equals(ModbusBindingProvider.VALUE_TYPE_UINT16)) {
			return new DecimalType(registers[index].toUnsignedShort());
		}
		else if (type.equals(ModbusBindingProvider.VALUE_TYPE_INT32)) {
			ByteBuffer buff = ByteBuffer.allocate(4);
			buff.put(registers[index * 2 + 1].toBytes());
			buff.put(registers[index * 2 + 0].toBytes());
			return new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getInt(0));
		}
		else if (type.equals(ModbusBindingProvider.VALUE_TYPE_UINT32)) {
			ByteBuffer buff = ByteBuffer.allocate(8);
			buff.position(4);
			buff.put(registers[index * 2 + 0].toBytes());
			buff.put(registers[index * 2 + 1].toBytes());
			return new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getLong(0));
		}
		else if (type.equals(ModbusBindingProvider.VALUE_TYPE_FLOAT32)) {
			ByteBuffer buff = ByteBuffer.allocate(4);
			buff.put(registers[index * 2 + 0].toBytes());
			buff.put(registers[index * 2 + 1].toBytes());
			return new DecimalType(buff.order(ByteOrder.BIG_ENDIAN).getFloat(0));
		}
		else {
			throw new IllegalArgumentException();
		}
	}

	/**
	 * Posts update event to OpenHAB bus for "coil" type slaves
	 * @param binding ModbusBinding to get item configuration from BindingProviding
	 * @param registers data received from slave device in the last pollInterval
	 * @param item item to update
{'fraction_non_alphanumeric': 0.11253398197166976, 'fraction_numerical': 0.010158821004435542, 'mean_word_length': 4.979041916167665, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3878953', 'n_tokens_mistral': 4659, 'n_tokens_neox': 4205, 'n_words': 981}