For some application I need to scan WiFi searching for available network (SSID). On Ubuntu 18.04 LTS I don't have any issue with the fallowing code. It return all available SSID as expected but when running on Raspbian stretch (Rasberry PI 3 b) the fallowing code is returning the interface wlan0 and eth0 and not the SSID. Does someone have any clue why? or can tell me what I miss? On the other hand, is it better not to use Qt network lib and use a QProcess and parse what sudo iwlist wlan0 scan is returning?
.cpp
void wificonfig::findavailableWifinetwork( void )
{
QNetworkConfigurationManager ncm;
netconflist = ncm.allConfigurations(QNetworkConfiguration::Discovered); //
int i =0;
awifilist.clear();
for(auto &x : netconflist){
if ((x.bearerType() == QNetworkConfiguration::BearerWLAN) ){
if(x.name() == "")
awifilist << "Unknown(Other Network)";
else{
ui->wificonnection_tw->setItem(i, 0, new QTableWidgetItem(x.name()));
i++;
}
//qDebug() << x.type();
}
}
ui->wificonnection_tw->setRowCount(i);
}
.h
#ifndef WIFICONFIG_H
#define WIFICONFIG_H
#include <QList>
#include <QTimer>
#include <QDialog>
#include <QNetworkConfiguration>
#include <QNetworkConfigurationManager>
#include <QNetworkSession>
namespace Ui {
class wificonfig;
}
class wificonfig : public QDialog
{
Q_OBJECT
public:
explicit wificonfig(QWidget *parent = 0);
~wificonfig();
int connection_count;
QNetworkConfiguration netconf;
QStringList awifilist;
QList<QNetworkConfiguration>netconflist;
public slots:
void findavailableWifinetwork( void );
private slots:
void on_wifi_scan_butt_clicked();
private:
Ui::wificonfig *ui;
QTime *scan_timeout_timer;
QNetworkSession *session;
};
#endif // WIFICONFIG_H
Related
I have a simple program that should retrieve the HTML from a website URL.
main.cpp
#include "Downloader.h"
#include <QCoreApplication>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
auto dl = new Downloader(&a);
QString url = "https://www.dognow.at/ergebnisse/?page=1";
dl->fetch(url);
return a.exec();
}
Downloader.h
#ifndef DOWNLOADER_H
#define DOWNLOADER_H
#include <QNetworkReply>
#include <QObject>
class Downloader : public QObject
{
Q_OBJECT
public:
explicit Downloader(QObject* parent = nullptr);
void fetch(QString &url);
private:
QNetworkAccessManager* m_manager;
private slots:
void replyFinished(QNetworkReply* rep);
};
#endif // DOWNLOADER_H
Downloader.cpp
#include "Downloader.h"
#include <QDebug>
Downloader::Downloader(QObject* parent): QObject(parent),
m_manager(new QNetworkAccessManager(parent))
{}
void Downloader::fetch(QString& url)
{
qDebug() << "fetch " << url;
connect(m_manager, &QNetworkAccessManager::finished, this, &Downloader::replyFinished);
m_manager->get(QNetworkRequest(QUrl(url)));
}
void Downloader::replyFinished(QNetworkReply* rep)
{
QByteArray data=rep->readAll();
QString str(data);
qDebug() << "data len: " << str.length();
rep->close();
}
When I run the program on my local PC it works fine. When I run it on another machine the reply data is empty. On both systems I use Linux (x86_64) and Qt 5.15.0.
I hope someone can give me a hint where I should have a look at.
UPDATE: 2022-04-04 - 16:22:
when I run a simple curl command on the failing machine it works fine.
Ok, I found the problem.
On the failing machin I have an older ubuntu (16.04 LTS) running with an incompatible openssl version.
I found it out because I copied my own Qt libs build (debug) to the other machine and I got SSL error (incompatbile version).
I installed a newer openssl version and know it works.
I am a newbee when it comes to coding in C++.
I am currently using qt to make a simple GUI, where I want to send a command to a device via TCP/IP.
When i connect my computer to the device and via the terminal send the command:
echo '3b00010000001b010001000000120000013000002713000300030101' | xxd -r -p | nc 192.168.1.101 30013
The device does correspondently.
I need to be able to send this command in qt as a function. Can anyone help me? This is what i have so far (does not work)
Header:
#ifndef SOCKET_H
#define SOCKET_H
#include <QObject>
#include <QTcpSocket>
#include <QtDebug>
#include <string>
using namespace std;
class Socket : public QObject
{
Q_OBJECT
public:
explicit Socket(QObject *parent = nullptr);
void Connect(const QString &host, const string &cmd);
private:
QTcpSocket *socket;
};
#endif // SOCKET_H
Cpp:
#include "socket.h"
Socket::Socket(QObject *parent) : QObject(parent)
{
}
void Socket::Connect(const QString &host, const string &cmd)
{
//connect
socket = new QTcpSocket(this);
socket->connectToHost(host,30013);
if(socket->waitForConnected(1500))
{
qDebug() << "Connected";
//send
socket->write(cmd.c_str(), cmd.size());
socket->waitForBytesWritten(1000);
//close
socket->close();
}
else
qDebug() << "Not Connected";
}
Then I want to send the command by:
Socket.Test
Test.Connect("192.168.1.101","3b00010000001b010001000000120000013000002713000300030101")
Any help would be much appreciated. Thanks.
As your command is a fixed string you can simply enter the characters directly:
const char data[] = "\x3b\x00\x01\x00\x00\x00\x1b\x01\x00\x01\x00\x00\x00\x12\x00\x00\x01\x30\x00\x00\x27\x13\x00\x03\x00\x03\x01\x01";
Test.Connect("192.168.1.101",string(data, sizeof(data)-1));
Note that as your data has embedded null characters you can't simply pass the string literal to std::string as it would truncate the string before the first null character.
I am trying to make an application in Qt to configure a bluetooth module RN42 http://ww1.microchip.com/downloads/en/DeviceDoc/rn-42-ds-v2.32r.pdf . In order to configure the module some command have to be sent via serial port, but here is where the extrange things start happening. I conecto it to the computer via xbee xplorer and I can configure it without any problems using my application, but when I try to retreive the current configuration no response is got, I can see that the device enters in configuration mode because the led blinks faster, but I cannot get any feedback from the device via serial port.
So I decided to start debugging with arduino due, if I connect it via programming port I can comunicate wihout problems, but if I connect it with the USB native port I do not get any information from the device. But if I open the port with the arduino serial monitor, the comunication starts, then close the arduino serial monitor, open my application and I am comunicating without problems.
I have also tried to comunicate with docklight (a serial monitor application) and again I have no problem comunicating, but if after comunicating with docklight I try to comunicate with my application no response will be got, unlike arduino serial monitor.
Eventhough I debugged with an oscilloscope and I can see that the information is sent once the port is closed.
I have tried many different things and I do not know what I am doing wrong. I tink it is related with the configuration of the port, but not sure, could it be a bug with the QtSerialport?
Here are my programs. I am using Qt creator 5.9.1 in windows with MinGW53_32
QT
.pro
#-------------------------------------------------
#
# Project created by QtCreator 2017-07-25T08:39:59
#
#-------------------------------------------------
QT += core gui
QT += serialport
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = BT_Config_Tool
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
bluetooth_config.cpp
HEADERS += \
bluetooth_config.h
FORMS += \
bluetooth_config.ui
bluetooth_config.h
#ifndef BLUETOOTH_CONFIG_H
#define BLUETOOTH_CONFIG_H
#include <QMainWindow>
#include <QTimer>
#include <QSerialPort>
#include <QtSerialPort>
#include <QtSerialPort/QtSerialPort>
#include <stdio.h>
#include <math.h>
#include <QSerialPortInfo>
#define BUFFMAX 1000
namespace Ui {
class bluetooth_config;
}
class bluetooth_config : public QMainWindow
{
Q_OBJECT
public slots:
void ReadDevice(void);
void FlashDevice(void);
void UpdateCombobox(void);
void ReadSerial(void);
public:
explicit bluetooth_config(QWidget *parent = 0);
~bluetooth_config();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
private:
Ui::bluetooth_config *ui;
QSerialPort *_port;
QTimer *_timerRead;
QTimer *_timerFlash;
QTimer *_timerUpdateCombobox;
QSerialPortInfo *_serialPortInfo;
int _cFlash = 0;
int _cRead = 0;
char _buffer[BUFFMAX];
//QByteArray _buffer;
int c;
};
#endif // BLUETOOTH_CONFIG_H
bluetooth_config.cpp
#include "bluetooth_config.h"
#include "ui_bluetooth_config.h"
const char *nameFlash;
const char *passFlash;
const char *nameRead;
char trama[BUFFMAX];
int item = 0;
bluetooth_config::bluetooth_config(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::bluetooth_config)
{
ui->setupUi(this);
ui->label_4->setVisible(false);
ui->label_5->setVisible(false);
_timerRead = new QTimer(this);
connect(_timerRead,SIGNAL(timeout()),this, SLOT(ReadDevice()));
_timerFlash = new QTimer(this);
connect(_timerFlash,SIGNAL(timeout()),this, SLOT(FlashDevice()));
_timerUpdateCombobox = new QTimer(this);
connect(_timerUpdateCombobox,SIGNAL(timeout()),this, SLOT(UpdateCombobox()));
_timerUpdateCombobox->start(2000);
_port = new QSerialPort();
_port->setBaudRate(QSerialPort::Baud115200);
_port->setDataBits(QSerialPort::Data8);
_port->setParity(QSerialPort::NoParity);
_port->setStopBits(QSerialPort::OneStop);
_port->setFlowControl(QSerialPort::NoFlowControl);
connect(_port,SIGNAL(readyRead()),this,SLOT(ReadSerial()));
//ui->tabWidget->setTabEnabled(0, false);
}
bluetooth_config::~bluetooth_config()
{
delete ui;
}
void bluetooth_config::ReadDevice()
{
_cRead ++;
if (_cRead == 1){
_port->write("$$$");
ui->lcdNumber_2->display(_cRead);
_timerRead->stop();
}
else if (_cRead == 2){
_port->write("---\r\n");
_port->waitForBytesWritten();
ui->lcdNumber_2->display(_cRead);
_timerRead->stop();
}
else if (_cRead == 3){
ui->label_5->setVisible(true);
ui->lcdNumber_2->display(_cRead);
_timerRead->stop();
_cRead = 0;
}
}
void bluetooth_config::FlashDevice()
{
_cFlash ++;
if (_cFlash == 1){
_port->write("$$$");
}
else if (_cFlash == 2){
nameFlash = ui->lineEdit->displayText().toUtf8().constData();
strcpy(trama, "SN,");
strcat(trama,nameFlash);
strcat(trama,"\n\r");
_port->write(trama);
}
else if (_cFlash == 3){
passFlash = ui->lineEdit_2->displayText().toUtf8().constData();
strcpy(trama, "SP,");
strcat(trama,passFlash);
strcat(trama,"\n\r");
_port->write(trama);
}
else if (_cFlash == 4){
_port->write("---\n\r");
}
else if (_cFlash == 5){
_cFlash = 0;
_timerFlash->stop();
ui->label_4->setVisible(true);
}
}
void bluetooth_config::UpdateCombobox()
{
item = ui->comboBox->currentIndex();
ui->comboBox->clear();
foreach (const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts())
{
ui->comboBox->addItem(serialPortInfo.portName());
}
if (item <= (ui->comboBox->count() - 1) && item >= 0){
ui->comboBox->setCurrentIndex(item);
}
else {
ui->comboBox->setCurrentIndex(ui->comboBox->count() - 1);
}
}
void bluetooth_config::ReadSerial()
{
int ojete = _port->bytesAvailable();
ui->lcdNumber->display(ojete);
//_port->read(_buffer,BUFFMAX);
QByteArray a = _port->readAll();
//ui->plainTextEdit->appendPlainText(_buffer);
ui->plainTextEdit->appendPlainText(a);
if (_cRead == 1 || _cRead == 2){
_timerRead->start(50);
}
}
void bluetooth_config::on_pushButton_clicked()
{
ui->label_5->setVisible(false);
_timerRead->start(50);
_port->flush();
}
void bluetooth_config::on_pushButton_2_clicked()
{
ui->label_4->setVisible(false);
_timerFlash->start(50);
_port->flush();
}
void bluetooth_config::on_pushButton_3_clicked()
{
if (!_port->isOpen()){
_port->setPortName(ui->comboBox->currentText());
if (_port->open(QIODevice::ReadWrite)){
ui->label_3->setText("Puerto abierto");
ui->pushButton_3->setText("Cerrar");
ui->pushButton->setEnabled(true);
ui->pushButton_2->setEnabled(true);
}
else {
ui->label_3->setText("Ha ocurrido un error al abrir el puerto");
}
}
else {
_port->close();
ui->label_3->setText("Puerto cerrado");
ui->pushButton_3->setText("Abrir");
ui->pushButton->setEnabled(false);
ui->pushButton_2->setEnabled(false);
}
}
main.cpp
#include "bluetooth_config.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
bluetooth_config w;
w.show();
return a.exec();
}
Thank you very much.
Alejandro
I am trying to embed a movie in a Qt (4.7.1) widget using ActiveQt:
VideoManager2.h:
#ifndef VIDEOMANAGER2_H_
#define VIDEOMANAGER2_H_
#include <QtCore/QtCore>
#include <QtGui/QtGui>
#include "qaxwidget.h"
class VideoManager2: public QWidget{
Q_OBJECT
//Q_ENUMS(ReadyStateConstants);
enum PlayStateConstants { Stopped = 0, Paused = 1, Playing = 2 };
enum ReadyStateConstants { Uninitialized = 0, Loading = 1, Interactive = 3, Complete = 4 };
QAxWidget *wmp;
private slots:
void onPlayStateChange(int a, int b);
void onReadyStateChange(ReadyStateConstants readyState);
public:
VideoManager2();
};
#endif /* VIDEOMANAGER2_H_ */
VideoManager2.cpp:
#include <QtCore/QtCore>
#include <QtGui/QtGui>
#include <InitGuid.h>
#include "VideoManager2.h"
#include "wmp.h"
#include "qaxobject.h"
VideoManager2::VideoManager2() {
wmp = new QAxWidget(this);
wmp->setControl("{6BF52A52-394A-11D3-B153-00C04F79FAA6}");
wmp->setProperty("ShowControls", false);
wmp->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
wmp->setProperty("URL", "C:/Users/qxf3567/Downloads/demoMedia/movie/earth.avi");
qDebug("Version Info: %s", qPrintable(wmp->property("versionInfo").toString()));
qDebug("Playing: %s", qPrintable(wmp->property("URL").toString()));
qDebug("State: %s", qPrintable(wmp->property("playState").toString()));
QAxObject* currentMedia= wmp->querySubObject("currentMedia");
IWMPMedia *media;
currentMedia->queryInterface(QUuid(__uuidof(IWMPMedia)), (void **)&media);
{
BSTR durationStr;
media->get_durationString(&durationStr);
QString convertedBSTR((QChar*) durationStr, wcslen(durationStr));
qDebug("Duration: %s", qPrintable(QString(convertedBSTR)));
}
}
void VideoManager2::onPlayStateChange(int a, int b){
}
void VideoManager2::onReadyStateChange(ReadyStateConstants readyState){
}
main.cpp:
...
QScrollArea *movieWidget = new QScrollArea(groupBox_2);
VideoManager2 vm;
ui->movieWidget->setWidget(&vm);
...
Output:
Version Info: 12.0.7601.18741
Playing: C:\Users\qxf3567\Downloads\demoMedia\movie\earth.avi
State: 9
Duration: 00:00
I can get the Version number of WMPlayer, but the movie to be played is displayed as 0 length. What could be the problem here? It's as if it doensn't find the file in the first place?!
I can't make sensors works on my Asus Transformer T100.
Magnetometer and Compass don't start, and I have fake value from the accelerometer (always x=0, y=9.8, z=0).
I always get the same result, even with my laptop :
first textEdit:
Initialisation...
QAccelerometer is connected to backend...
QAccelerometer isActive...
Attente des données capteur...
Second textEdit:
ven. juin 6 14:56:41 2014
Acceleration: x = 0
y = 9.8
z = 0
Compass: UNAVAILABLE
QMagnetometer: UNAVAILABLE
And this code :
QList<QByteArray> sensorList = QSensor::sensorTypes();
ui->init->append("Sensor list length: " + QString::number(sensorList.size()).toUtf8());
foreach( QByteArray sensorName, sensorList ) {
ui->init->append("Sensor: " + sensorName);
}
Give me :
Sensor: QAmbientLightSensor
Sensor: QAccelerometer
Sensor: QTiltSensor
Sensor: QOrientationSensor
Sensor: QRotationSensor
Where is QCompass ? QMagnetometer ? Why QAccelerometer is faked ? :'(
Here is my simplified test-code, only with QCompass :
header:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QCompass>
#include <QCompassReading>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void update();
void error(int);
private:
Ui::MainWindow *ui;
QCompass *compass;
QCompassReading *compass_reading;
};
#endif // MAINWINDOW_H
code :
#include <QDateTime>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->init->setText("Initialisation...");
compass = new QCompass(this);
connect(compass, SIGNAL(readingChanged()), this, SLOT(update()));
connect(compass, SIGNAL(sensorError(int)), this, SLOT(error(int)));
compass->setDataRate(1);
compass->start();
if (compass->isBusy()) {
ui->init->append("QCompass is busy...");
}
if(compass->isConnectedToBackend()) {
ui->init->append("QCompass is connected to backend...");
}
if(compass->isActive()) {
ui->init->append("QCompass isActive...");
}
ui->init->append("Waiting for sensors...");
}
MainWindow::~MainWindow()
{
delete compass;
delete ui;
}
void MainWindow::update()
{
QString text_compass;
ui->textEdit->clear();
accel_reading = accel->reading();
compass_reading = compass->reading();
if(compass_reading != 0) {
text_compass = QDateTime::currentDateTime().toString() +
+ "\nCompass: azimuth = " + QString::number(compass_reading->azimuth());
+ "\ncalibration level = " + QString::number(compass_reading->calibrationLevel());
ui->textEdit->append(text_compass);
}
else {
text_compass = "\nCompass: UNAVAILABLE";
ui->textEdit->append(text_compass);
}
}
void MainWindow::error(int erreur) {
QMessageBox::critical(this, "Erreur", "Erreur num : " + QString::number(erreur).toUtf8());
}
The solution for now is to hack the winrt sensors plugin and rebuild it.
(the sensors backend for winrt works for windows 7/8 desktop application).
First git clone the plugin, or get Qt's source code.
then open src/plugins/sensors/sensors.pro and add these lines :
win32-msvc2012|win32-msvc2013 {
isEmpty(SENSORS_PLUGINS): SENSORS_PLUGINS = winrt generic dummy
}
winrt|win32-msvc2012|win32-msvc2013 {
isEmpty(SENSORS_PLUGINS)|contains(SENSORS_PLUGINS, winrt):SUBDIRS += winrt
}
REMOVE this line :
isEmpty(SENSORS_PLUGINS)|contains(SENSORS_PLUGINS, winrt):winrt:SUBDIRS += winrt
Then open src/plugins/sensors/winrt/winrt.pro and add this lines :
win32-msvc2012|win32-msvc2013: LIBS += -lruntimeobject
And finally run qmake, make/nmake, make/nmake install
(Ask google for more informations about how to build)
IMPORTANT : the run process should start from the directory where the qtsensors.pro file is (e. g. C:\Qt\5.4\Src\qtsensors).
To get more informations, and follow :
Link to the bug : https://bugreports.qt-project.org/browse/QTBUG-39590
Link to the patch : https://codereview.qt-project.org/#/c/87370/