QT c++ open Serial port more than once - serial-port

I search an example to open multiple serial ports in qt.
My open port function settings forward from other class
void MainWindow::openSerialPort(){
SettingsDialog::Settings p = settings->settings();
serial->setPortName(p.name);
serial->setBaudRate(QSerialPort::Baud9600);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::NoFlowControl);
if (serial->open(QIODevice::ReadWrite)) {
ui->connectAction->setEnabled(false);
ui->disconnectAction->setEnabled(true);
ui->settingsAction->setEnabled(false);
showStatusMessage(tr("Connected to %1 : OK")
.arg(p.name));
} else { //gdy sie nie udalo error
QMessageBox::critical(this, tr("Error"), serial->errorString());
showStatusMessage(tr("Open error"));
}
}

As far as I remember single instance of QSerialPort if opened does it exclusively so no other instance has access to this port. I guess creating other QSP and opening other port would do the thing.

Related

Dubs Connman wifi connect Qt

I'am working on an imx6, and i'am trying to connect to a wifi network through Dbus with a Qt application.
The application connect correctly to connman via Dbus and i recieve correctly the wifi services.
The problem is that when i try to connect to a wiif network i catch this error :
"Method "Connect" with signature "ss" on interface "net.connman.Service" doesn't exist
The code that i'am using in Qt application to coonect to a wifi network is:
QDBusInterface *iface =
new QDBusInterface("net.connman","/net/connman/technology/wifi","net.connman.Service",QDBusConnection::systemBus());
if (!iface->isValid())
{
qDebug() << Q_FUNC_INFO << "Fail to connect to the Connman Technology interface: " << QDBusConnection::systemBus().lastError().message();
}
QDBusReply<void> reply = iface->call("Connect","/net/connman/service/wifi_88da1a4db14c_41684179_managed_psk","password");
if (!reply.isValid())
{
qDebug() << "Call connect result: " << reply.error().message();
}
When i try to connect to the wifi network with shell commands using connmanctl it works like a charm.
I had the same problem on imx6. The solution which works for me is creating a configuration file for network before invoking Connect method.
The file should be in /var/lib/connman and name [SSID].config .
File content:
[service_wifi_PUT_SERVICE_NAME]
Name = PUT_SSID
Type = wifi
Passphrase = PUT_PASSWORD
And try connecting in this way:
QDBusInterface *iface = new QDBusInterface("net.connman", QString{"/net/connman/service/%1"}.arg(SERVICE_NAME), "net.connman.Service", QDBusConnection::systemBus());
QDBusReply<void> reply = iface->call("Connect");
if(!reply.isValid() {
...

write and read data to terminal from serial port without connecting any hardware devices to serialport

actually i have Qt code. so i need to send data of packets from serial port to terminal and display the data in terminal and also from terminal i need to read data and display it in Qt window page. main problem is, for serial communication to terminal, does we really require serial port should connect to some hardware devices and also.. can we write and read data to terminal without connecting any serial port to hardware devices.
the code from Transceiver layer to serial port
Transceiver::Transceiver(QObject *parent)
:
QObject(parent),
mSerial(new QSerialPort(this))
{
mSerial->setPortName(QString("COM1"));
qint32 baudRate = 9600;
mSerial->setBaudRate(baudRate);
mSerial->setDataBits(QSerialPort::Data8);
mSerial->setParity(QSerialPort::NoParity);
mSerial->setStopBits(QSerialPort::OneStop);
connect
(
mSerial,
&QSerialPort::readyRead,
[ this ]()
{
QByteArray data = mSerial->readAll();
OnDataReceived( data );
qDebug()<<data;
}
);
}
Transceiver::~Transceiver()
{
mSerial->close();
}
void
Transceiver::Send_Data(const QByteArray & inDataStream )
{
qDebug()<<"Data_in_Transceiver_layer :"<<inDataStream;
mSerial->write(inDataStream);
}
bool
Transceiver::OpenConnection()
{
mSerial->open(QIODevice::ReadWrite);
QSerialPort::SerialPortError error = m`enter code here`Serial->error();
return error == QSerialPort::NoError;
// connect(mSerial, SIGNAL(readyRead()), this, SLOT(read_data()));
}
when i run this it shows
QIODevice::write (QSerialPort): device not open

QTcpSocket - Connection Refused until Port Changed

I apologize, I was not sure how to deliver a concise title for this issue.
Background: I am using QTcpSocket to connect to a PLC Simulator application. Previously I was using PLCQTLIB to connect to the simulator and everything was working fine. The library did not offer enough functionality for my project so I have created my own library for interfacing Qt with the libnodave library.
The simulator runs on IP Address 192.168.32.1 and Port 102
Current Issue: I enter the IP (192.168.32.1) and Port (102) and press connect. I receive:
TCP Error = QAbstractSocket::ConnectionRefusedError
TCP Error = QAbstractSocket::SocketTimeoutError
If I change the port to 80 and press connect, the connection is successful. However the connection to the PLC Simulator will fail because it is not listening on Port 80.
Now that a successful connection has been established to 192.168.32.1 and the current state of the connection is disconnected, I can enter the correct port 102 and connect successfully.
Question: Why does the TCP Socket not establish a connection to Port 102 until after a connection has been previously opened on Port 80? No firewalls exist and all communication is occurring on the local machine.
Declared in Header:
QTcpSocket *tcp;
Source File:
PLCLibNoDave::PLCLibNoDave()
{
tcp = new QTcpSocket();
connect(tcp, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
this, SLOT(tcpStateChanged(QAbstractSocket::SocketState)));
connect(tcp, SIGNAL(error(QAbstractSocket::SocketError)),
this, SLOT(tcpErrorHandler(QAbstractSocket::SocketError)));
connect(tcp, SIGNAL(hostFound()), this, SLOT(tcpHostFound()));
connect(tcp, SIGNAL(connected()), this, SLOT(tcpConnected()));
connect(tcp, SIGNAL(disconnected()), this, SLOT(tcpDisconnected()));
}
void PLCLibNoDave::connectTCP(int port, QString ip)
{
tcp->connectToHost(ip,port);
if(!tcp->waitForConnected(3000)){
tcp->disconnectFromHost();
return;
}
tcpHandle = tcp->socketDescriptor();
if(tcpHandle == -1){
tcp->disconnectFromHost();
qDebug() << "Invalid Socket Descriptor on Connect";
return;
}
return;
}
void PLCLibNoDave::disconnectTCP()
{
tcp->disconnectFromHost();
if(tcp->state() == QAbstractSocket::UnconnectedState ||
tcp->waitForDisconnected(1000)){
tcpError = tcp->error();
}
else{
tcpError = tcp->error();
qDebug() << "Disconnect Failed: " << tcp->errorString();
}
return;
}

Flow Controll Settings for Serial Communication between Java RXTX and Arduino

I have a simple sketch on my Seeeduino Mega 1.22 which just displays the serial input on a LCD Display. Using lynx term and the arduino serial monitor works fine: sent input is being displayed. The trouble starts when I want to start serial communication between my Java programm, running in Eclipse on a Win7 x64 machine, and the Seeeduino. I'm using the RXTX x64 build. The programm is intended to send and receive some string.getBytes() via the open port. Receiving on the Java side works, but receiving on the Arduino side fails.
It seems that the problem is the proper Flow Control setting. I saw that some people had the same issue like here Issues receving in RXTX
But this solution does not work for me. If I set the FlowControl to None, than I get only a block icon on the display, indicating, that the serial connection has been established, but nothing else. If I set the FlowControl to RCTS_IN | RCTS_OUT, then I get the string bytes only on the display when I close the established connection.
Why is the data only send when I close the connection (Flushing the out stream did not help as well) ? What am I doing wrong with the Flow Controll settings?
This is the modified connect() method I'm using.
void connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier
.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(),
2000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8,
SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
try {
serialPort.setFlowControlMode(
// SerialPort.FLOWCONTROL_NONE);
// OR
// If CTS/RTS is needed
//serialPort.setFlowControlMode(
SerialPort.FLOWCONTROL_RTSCTS_IN |
SerialPort.FLOWCONTROL_RTSCTS_OUT);
} catch (UnsupportedCommOperationException ex) {
System.err.println(ex.getMessage());
}
serialPort.setRTS(true);
in = serialPort.getInputStream();
out = serialPort.getOutputStream();
(new Thread(new SerialWriter(out))).start();
serialPort.addEventListener(new SerialReader(in, this));
serialPort.notifyOnDataAvailable(true);
} else {
System.out.println("Error: Only serial ports are to use!");
}
}
}
Thanks in advance for your time
Solved it. It was not the buffer, as many suggested it. The problem was, that the Seeeduinos RST Switch on the board was set to automatic. Setting it to manual, solved the problem.
No Flow-Controll needed.

gnu.io.PortInUseException: Unknown Application?

void connect ( String portName ) throws Exception
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
}
else
{
System.out.println(portIdentifier.getCurrentOwner());
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if ( commPort instanceof SerialPort )
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
(new Thread(new SerialReader(in))).start();
(new Thread(new SerialWriter(out))).start();
}
else
{
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
is giving
gnu.io.PortInUseException: Unknown Application
at gnu.io.CommPortIdentifier.open(CommPortIdentifier.java:354)
i am using RXTX with Java in windows 7 home 64-bit.
Check that /var/lock folder exist on your machine.
mkdir /var/lock
chmod go+rwx /var/lock
Reboot the system / disable the port.
Actual problem is when the program runs port is opened and it didn't close after the program terminates.
it works.
I ran into this problem because the port was actually in use. A previous instance of javaw.exe appeared in the Windows task manager, it hogged the port.
The reason why that previous java process hung was a hardware issue: When plugging the USB-2-serial converter that I happened to use into a USB-2 port, all worked fine. When plugged into a USB-3 port, RXTX CommPortIdentifier code would hang, and then subsequent instances of Java received the PortInUseException.
I used Process Explorer to find a process with the handle \Device\PCISerial0 and closed the handle. If your com ports aren't on a PCI card, the name might be different.
For Windows
Open Task Manager
under Eclipse (or your ide) find Java application.
Right click on it -> End Task
May be useful, I solved such problem by remove gateway from service and stop it , gateway is instance of SerialModemGateway.
Service.getInstance().stopService();
Service.getInstance().removeGateway(gateway);
gateway.stopGateway();

Resources