#include "stdio.h"
#include "PLCDevice.h"
#include "modbus.h"
#include <iostream>
#include <common.h>
#include <QDebug>

extern SysConf g_sys_conf;

modbus_t * g_modbus = NULL;		//Modbus TCP

bool PLCDevice::init_plc(PLCDevice* PLCptr)
{
	const char* comport= g_sys_conf.ComPort.data();
	qDebug() << "COM:" << comport;
	//连接PLC
	g_modbus = modbus_new_rtu(comport, 9600, 'N', 8, 1);
	modbus_set_debug(g_modbus, 0);

	modbus_set_response_timeout(g_modbus, 1, 0);
	if (g_modbus && modbus_connect(g_modbus) == -1) {
		PLCptr->g_plc_ok = false;
	}
	else {
		modbus_set_slave(g_modbus, 1);
		PLCptr->g_plc_ok = true;
	}
	return true;
}
bool PLCDevice::disconnect_plc(void)
{
	if(g_modbus)
	{
		modbus_close(g_modbus);
		modbus_free(g_modbus);
	}
	return true;
}
int PLCDevice::write_bit_2_plc(int addr, int value)
{
	if (g_plc_ok)
	{
		g_mutex.lock();
		int ret = modbus_write_bit(g_modbus, addr, value);
		g_mutex.unlock();
		//printf("modbus_write_bit:addr=%d,value=%d,ret=%d\n", addr, value, ret);
		return ret;
	}
	else {
		//std::cout << "PLC no ok" << std::endl;
		return false;
	}
}

int PLCDevice::read_bits_from_plc(int addr, int nb,uint8_t* value)
{
	if (g_plc_ok)
	{
		g_mutex.lock();
		int ret = modbus_read_bits(g_modbus, addr, nb ,value);
		g_mutex.unlock();
		//printf("modbus_read_bits:addr=%d,nb=%d,value=%d,ret=%d\n", addr, nb, *value, ret);
		return ret;
	}
	else {
		//std::cout << "PLC no ok" << std::endl;
		return false;
	}
}

int PLCDevice::write_short_2_plc(int addr, int nb, uint16_t *value)
{
	if (g_plc_ok)
	{
		g_mutex.lock();
		int ret = modbus_write_registers(g_modbus, addr, nb, value);
		g_mutex.unlock();
		//printf("modbus_write_registers:addr=%d,nb=%d,value=%d,ret=%d\n", addr, nb, *value, ret);
		return ret;
	}
	else {
		//std::cout << "PLC no ok" << std::endl;
		return false;
	}
}

int PLCDevice::read_short_from_plc(int addr, int nb, uint16_t *value)
{
	if (g_plc_ok)
	{
		g_mutex.lock();
		int ret = modbus_read_registers(g_modbus, addr, nb, value);
		g_mutex.unlock();
		//printf("modbus_read_registers:addr=%d,nb=%d,value=%d,ret=%d\n", addr, nb, *value ,ret);
		return ret;
	}
	else {
		//std::cout << "PLC no ok" << std::endl;
		return false;
	}
}