|
|
|
@ -34,9 +34,7 @@ bool PLCDevice::init_plc(PLCDevice* PLCptr)
|
|
|
|
|
|
|
|
|
|
bool PLCDevice::init_plc_tcp(PLCDevice* PLCptr)
|
|
|
|
|
{
|
|
|
|
|
// modbus_connect() 建立连接,成功返回0,错误返回-1
|
|
|
|
|
// modbus_new_rtu 生成RTU的连接,建立成功则返回指向modbus_t结构的指针,否则将返回NULL/0
|
|
|
|
|
|
|
|
|
|
#ifdef __ModebusServer
|
|
|
|
|
PLCptr->g_modbus = modbus_new_tcp("192.168.1.200", 2000);
|
|
|
|
|
modbus_set_debug(PLCptr->g_modbus, 0); // 用flag设置debug调试标志位,flag=1时显示modbus消息的字节
|
|
|
|
|
modbus_set_response_timeout(PLCptr->g_modbus, 1, 0); // 设置响应超时
|
|
|
|
@ -56,7 +54,25 @@ bool PLCDevice::init_plc_tcp(PLCDevice* PLCptr)
|
|
|
|
|
PLCptr->g_plc_ok = true;
|
|
|
|
|
qDebug("TCP connect successful ");
|
|
|
|
|
}
|
|
|
|
|
#endif
|
|
|
|
|
#ifdef __ModebusClient
|
|
|
|
|
|
|
|
|
|
PLCptr->g_modbus = modbus_new_tcp("127.0.0.1", 502);
|
|
|
|
|
modbus_set_debug(PLCptr->g_modbus, 0); // 用flag设置debug调试标志位,flag=1时显示modbus消息的字节
|
|
|
|
|
modbus_set_response_timeout(PLCptr->g_modbus, 1, 0); // 设置响应超时
|
|
|
|
|
// 侦听主站连接
|
|
|
|
|
PLCptr->m_modbusSocket = modbus_tcp_listen(PLCptr->g_modbus, 1); // 最多支持的主机数量 1
|
|
|
|
|
/*设置线圈, 离散输入, 输入寄存器, 保持寄存器个数(数组元素个数))*/
|
|
|
|
|
PLCptr->mapping = modbus_mapping_new(PLCptr->m_numBits, PLCptr->m_numInputBits, PLCptr->m_numInputRegisters, PLCptr->m_numRegisters);
|
|
|
|
|
if (PLCptr->mapping == NULL)
|
|
|
|
|
{
|
|
|
|
|
fprintf(stderr, "Unable to assign mapping:%s\n", modbus_strerror(errno));
|
|
|
|
|
modbus_free(PLCptr->g_modbus);
|
|
|
|
|
PLCptr->m_initialized = false;
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
PLCptr->m_initialized = true;
|
|
|
|
|
#endif
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -106,9 +122,9 @@ int PLCDevice::write_short_2_plc(int addr, int nb, uint16_t* value)
|
|
|
|
|
{
|
|
|
|
|
if (g_plc_ok)
|
|
|
|
|
{
|
|
|
|
|
//g_mutex.lock();
|
|
|
|
|
g_mutex.lock();
|
|
|
|
|
int ret = modbus_write_registers(g_modbus, addr, nb, value);
|
|
|
|
|
//g_mutex.unlock();
|
|
|
|
|
g_mutex.unlock();
|
|
|
|
|
//printf("modbus_write_registers:addr=%d,nb=%d,value=%d,ret=%d\n", addr, nb, *value, ret);
|
|
|
|
|
return ret;
|
|
|
|
|
}
|
|
|
|
@ -133,3 +149,19 @@ int PLCDevice::read_short_from_plc(int addr, int nb, uint16_t* value)
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
int PLCDevice::write_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;
|
|
|
|
|
}
|
|
|
|
|
}
|