I have a main server and 4 computers connected. How can I learn which computer use how much CPU and disk.
I write code using Qt and C++.
Qt does not have an API for this. You'll need to use the platforms native API.
Maybe this can help you:
#include <QDebug>
#include <QProcess>
int main(void){
setenv("LC_NUMERIC", "C",1);
QProcess process;
process.start("/usr/bin/uptime",{},QIODevice::ReadWrite);
process.waitForFinished();
//Get results
QString output = process.readAllStandardOutput();
QString err = process.readAllStandardError();
//Get load portion
QString loads=output.section("load average: ",1,1);
QString load_lastmin=loads.section(" ",0,0);
load_lastmin.remove(load_lastmin.size()-1,1);
//For debug
qDebug() << "Output:" << output;
qDebug() << "Error:" << err;
qDebug() << "Loads:" << loads;
qDebug() << "Load last min:" << load_lastmin;
return 0;
}
Result example:
Output: " 10:04:33 up 3 days, 21:39, 1 user, load average: 0.55, 0.71, 0.78\n"
Error: ""
Loads: "0.55, 0.71, 0.78\n"
Load last min: "0.55"
Related
Good day.
Has anyone tried QMediaPlayer in Qt 6.2 already?
I'm trying this code, but Media Status always remains as "NoMedia" and no any sound :).
Full test project: https://github.com/avttrue/MediaPlayerTest
#include "mainwindow.h"
#include <QDebug>
#include <QBuffer>
#include <QFile>
#include <QAudioOutput>
#include <QMediaPlayer>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QFile file("../test/Bankrobber.mp3");
if(!file.open(QIODevice::ReadOnly))
qDebug() << "File not opened";
qDebug() << "File size:" << file.size(); // File size: 11181085
QByteArray ba = file.readAll();
qDebug() << "ByteArray size:" << ba.size(); // ByteArray size: 11181085
QBuffer* buffer = new QBuffer(this);
buffer->setData(ba);
if(!buffer->open(QIODevice::ReadOnly))
qDebug() << "Buffer not opened";
qDebug() << "Buffer size:" << buffer->size(); // Buffer size: 11181085
buffer->seek(qint64(0));
auto audioOutput = new QAudioOutput(this);
auto player = new QMediaPlayer(this);
player->setAudioOutput(audioOutput);
audioOutput->setVolume(50);
player->setSourceDevice(buffer);
qDebug() << "Device:" << player->sourceDevice(); // Device: QBuffer(0x563180493020)
QObject::connect(player, &QMediaPlayer::mediaStatusChanged,
[=](QMediaPlayer::MediaStatus status)
{ qDebug() << "MediaStatus:" << player->mediaStatus() << "|" << status; });
QObject::connect(player, &QMediaPlayer::errorOccurred,
[=](QMediaPlayer::Error error)
{ qDebug() << "Error:" << player->errorString() << "|" << error; });
QObject::connect(player, &QMediaPlayer::playbackStateChanged,
[=](QMediaPlayer::PlaybackState state)
{ qDebug() << "PlaybackState:" << player->playbackState() << "|" << state; });
player->play();
qDebug() << "MediaStatus:" << player->mediaStatus(); // MediaStatus: QMediaPlayer::NoMedia
}
As the docs points out:
void QMediaPlayer::setSourceDevice(QIODevice *device, const QUrl
&sourceUrl = QUrl())
Sets the current source device.
The media data will be read from device. The sourceUrl can be provided
to resolve additional information about the media, mime type etc. The
device must be open and readable.
For macOS the device should also be seek-able.
Note: This function returns immediately after recording the specified
source of the media. It does not wait for the media to finish loading
and does not check for errors. Listen for the mediaStatusChanged() and
error() signals to be notified when the media is loaded, and if an
error occurs during loading.
(emphasis mine)
QMediaPlayer does not know how to deduce the file format so it does not load it. The solution is to point out that it is an mp3:
player->setSourceDevice(buffer, QUrl("foo.mp3"));
The function setSourceDevice() you are using isn't doing what you think?
Maybe you wanted setSource() instead?
Qt has great documentation:
https://doc.qt.io/qt-6/qmediaplayer.html#setSourceDevice
Even good examples:
player = new QMediaPlayer;
audioOutput = new QAudioOutput;
player->setAudioOutput(audioOutput);
connect(player, SIGNAL(positionChanged(qint64)), this, SLOT(positionChanged(qint64)));
player->setSource(QUrl::fromLocalFile("/Users/me/Music/coolsong.mp3"));
audioOutput->setVolume(50);
player->play();
Ref.
https://doc.qt.io/qt-6/qmediaplayer.html#details
May be this is as variant, but i think it not good:
QTemporaryFile tfile;
if (!tfile.open())
qDebug() << "TemporaryFile not opened";
else
{
qDebug() << "TemporaryFile writed:" << tfile.write(ba);
if(tfile.size() != ba.size())
qDebug() << "TemporaryFile not complited";
else
player->setSource(QUrl::fromLocalFile(tfile.fileName()));
}
I'm trying to write a program in Qt that simultaneously records audio from a microphone and plays it back at the same time. I'm using Qt 5.9.4 and I'm on Fedora 29 (can't update to latest version as our production environment is Fedora 29 -- can't update it, have already asked boss).
I have some barebones code written, as you can see below. But everytime I run the program, I get the following error message:
using null output device, none available
using null input device, none available
I've installed every qt5* package. I have alsa-utils and pulse audio installed as well.
I have also looked at these which more or less helped me but did not solve my problem:
Qt - how to record and play sound simultaneously
https://forum.qt.io/topic/10399/how-to-record-and-play-sound-simultaneously/5
https://www.qtcentre.org/threads/45300-How-to-record-and-play-sound-simultaneously
Qt - No audio output device - Yocto/poky
Qt + conan = using null output device, none available
I don't know if this is a fedora related issue or a Qt related issue. Please help!
myaudiorecorder.h:
#ifndef MYAUDIORECORDER_H
#define MYAUDIORECORDER_H
#include <QAudioFormat>
#include <QAudioDeviceInfo>
#include <QTextStream>
#include <QAudioInput>
#include <QAudioOutput>
#include <QObject>
class MyAudioRecorder : public QObject
{
Q_OBJECT
public:
MyAudioRecorder();
QAudioFormat formatIn;
QAudioFormat formatOut;
QAudioInput *m_audioInput;
QAudioOutput *m_audioOutput;
QAudioDeviceInfo m_InputDevice;
QAudioDeviceInfo m_OutputDevice;
QIODevice *m_input;
QIODevice *m_output;
QAudioDeviceInfo deviceIn;
QAudioDeviceInfo deviceOut;
void getFormat();
void createAudioInput();
void createAudioOutput();
void beginAudio();
};
#endif // MYAUDIORECORDER_H
myaudiorecorder.cpp:
#include "myaudiorecorder.h"
MyAudioRecorder::MyAudioRecorder() {
getFormat();
createAudioInput();
createAudioOutput();
}
void MyAudioRecorder::getFormat(){
formatIn.setSampleSize(8);
formatIn.setCodec("audio/pcm");
formatIn.setByteOrder(QAudioFormat::LittleEndian);
formatIn.setSampleType(QAudioFormat::UnSignedInt);
deviceIn = QAudioDeviceInfo::availableDevices(QAudio::AudioInput).at(1);
if(!deviceIn.isFormatSupported(formatIn)){
QTextStream(stdout) << " default formatIn not supported " << endl;
formatIn = deviceIn.nearestFormat(formatIn);
} else {
QTextStream(stdout) << " default formatIn supported " << endl;
}
deviceOut = QAudioDeviceInfo::availableDevices(QAudio::AudioOutput).at(0);
if(!deviceOut.isFormatSupported(formatOut)) {
QTextStream(stdout) << "1. default formatOut not supported " << endl;
formatOut = deviceOut.nearestFormat(formatOut);
}
}
void MyAudioRecorder::createAudioInput(){
m_audioInput = new QAudioInput(m_InputDevice, formatIn, 0);
}
void MyAudioRecorder::createAudioOutput(){
m_audioOutput = new QAudioOutput(m_OutputDevice, formatOut, 0);
}
void MyAudioRecorder::beginAudio(){
m_output = m_audioOutput->start();
m_input = m_audioInput->start();
}
void MyAudioRecorder::beginAudio(){
m_output = m_audioOutput->start();
m_audioInput->start(m_output);
//Above should do the trick but do check the volume, state and error if any:
qDebug() << "m_audioInput: volume=" << m_audioInput->volume()
<< ", state=" << m_audioInput->state()
<< ", error=" << m_audioInput->error();
qDebug() << "m_audioOutput: volume=" << m_audioOutput->volume()
<< ", state=" << m_audioOutput->state()
<< ", error=" << m_audioOutput->error();
}
you need copy qt Qt/5.9.x/mingw73_64/plugins/audio to you binary directory,not copy qtaudio_windows.dll ,is copy audio folder
I'm trying to connect a micro-controller with my desktop PC via USB-serial cable.
The OS of my desktop PC is Windows 8.1, and USB-serial cable is TTL-232R-3V3. (FTDI)
(Qt version: 5.2.0 beta1, QtCreator Version: 3.0, Compiler: MSVC2012)
Now I'm trying read/write loop-back tests, and that's why RX/TX pin of USB-serial cable are connected with each other.
Here is my code.
#include <QtCore/QCoreApplication>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <QtCore/QDebug>
#define PORT_NAME "COM3"
#define BAUDRATE 19600
#define TIMEOUT_MS 1000
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSerialPort pSerial(PORT_NAME);
const char strMsg[] = "#1:Send data line \n #2:Send data line\n #3:Send data line end\n";
char strBuf[256];
qint64 nByte;
if(pSerial.open(QIODevice::ReadWrite)){
pSerial.setBaudRate(BAUDRATE);
qDebug() << "OPEN PASS";
pSerial.write(strMsg);
pSerial.flush();
if(pSerial.waitForBytesWritten(TIMEOUT_MS)){
qDebug() << "WRITE PASS";
}
pSerial.waitForReadyRead(TIMEOUT_MS);
while(true){
if( pSerial.canReadLine()){
qDebug() << "CAN READ LINE";
nByte = pSerial.readLine(strBuf,sizeof(strBuf));
qDebug() << "Length: " << nByte;
qDebug() << "Read data: " << strBuf;
}
}
pSerial.close();
} else {
qDebug() << "OPEN FAIL\n";
}
return a.exec();
}
When the program starts to run, the result is different than I expected.
Only first line of sent data can be received. So, "Read data: #1 Send data line" is printed
on console. But the rest of sent data will never be received. Does anyone know why?
Any help would be appreciated.
Thanks in advance.
EDIT: I revised my code according to Papp's comment.Then it works as I expected.
All sent message has been received.
Does it mean I misunderstand the usage about readLine() or canReadLine()?
// while(true){
// if( pSerial.canReadLine()){
// qDebug() << "CAN READ LINE";
// nByte = pSerial.readLine(strBuf,sizeof(strBuf));
// qDebug() << "Length: " << nByte;
// qDebug() << "Read data: " << strBuf;
// }
// }
pSerial.waitForReadyRead(TIMEOUT_MS);
QByteArray readData = pSerial.readAll();
while (pSerial.waitForReadyRead(TIMEOUT_MS)) {
readData.append(pSerial.readAll());
}
qDebug() << "Read data: " << readData;
EDIT 2nd time : Following code also works for me.
while(true){
if( pSerial.waitForReadyRead(TIMEOUT_MS) && pSerial.canReadLine()){ // I revised this line
qDebug() << "CAN READ LINE";
nByte = pSerial.readLine(strBuf,sizeof(strBuf));
qDebug() << "Length: " << nByte;
qDebug() << "Read data: " << strBuf;
qDebug() << "Error Message: " << pSerial.errorString();
}
}
That is because you need to read in a loop like this:
QByteArray readData = serialPort.readAll();
while (serialPort.waitForReadyRead(5000))
readData.append(serialPort.readAll());
Please see the creadersync example for the details what I added to 5.2. You can also check the creaderasync example for non-blocking operation.
To be fair, we have not tested readLine that much, but it works for me on Unix, so does it on Windows for someone else.
The mistake that you've made is expecting to receive all the sent data when waitForReadyRead returns. When waitForReadyRead finishes, all you're guaranteed is some data being available to be read. It may be as little as one character, not necessarily a whole line.
The loop from your last modification is the almost correct way to do it. You should nest reading of the lines in a separate loop. The following code is how it should be done, and agrees with the semantics of QIODevice:
while (pSerial.waitForReadyRead(TIMEOUT_MS)) {
while (pSerial.canReadLine()) {
qDebug() << "NEW LINE";
QByteArray line = pSerial.readLine();
qDebug() << "Length: " << line.size();
qDebug() << "Read data: " << line;
qDebug() << "Error Message: " << pSerial.errorString();
}
}
qDebug << "TIMED OUT";
Note that none of this code should even run in the GUI thread. Ideally you should move it to a QObject, use the signals emitted by QIODevice (and thus QSerialPort), and move that object to a separate thread.
The GUI thread can sometimes block for long periods of time, it's not normally desirable to have it disturb the timeliness of your device communication. Similarly, you don't want device timeouts to block the GUI thread. Both are equally bad and are a very common source of bad user experience. Qt makes multithreading very easy - leverage it for your user's sake, and do it properly.
On Linux I have to do it this way to receive ASCII text ending with '\n'
QByteArray readData = pSerial.readAll();
while (readData[readData.length() - 1] != '\n') {
pSerial.waitForReadyRead(5000);
readData.append(pSerial.readAll());
}
QString result(readData);
QSerialPort::readLine() doesn't work for me either
Here is my code:
#include "MyClass.h"
#include <qstring.h>
#include <qdebug.h>
MyClass::MyClass()
{
QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();
int counter=0;
while(counter<ports.size())
{
QString portName = ports[counter].portName;
QString productId= ports[counter].productID;
QString physicalName = ports[counter].physName;
QString vendorId = ports[counter].vendorID;
QString friendName = ports[counter].friendName;
string convertedPortName = portName.toLocal8Bit().constData();
string convertedProductId = productId.toLocal8Bit().constData();
string convertedPhysicalName = physicalName.toLocal8Bit().constData();
string convertedVendorId = vendorId.toLocal8Bit().constData();
string convertedFriendName = friendName.toLocal8Bit().constData();
cout << "Port Name: " << convertedPortName << endl;
cout << "Product ID:" << convertedProductId << endl;
cout << "Physical Name: " << convertedPhysicalName << endl;
cout << "Vendor Id: " << convertedVendorId << endl;
cout << "Friend Name: " << convertedFriendName << endl;
cout << endl;
counter++;
}
}
I have connected "Dreamcheeky Thunder Missile Launcher" USB toy, but I am unable to get it's Vendor ID or product ID or atleast anything related to it! See the following image
But using USBDView software, I can get all the details. See the following image
What is matter with My code? Or if it is simply not suitable?
Just running the installer for the toy and checking what it comes up with, it doesn't describe any API or documentation for accessing it as a serial port.
If you used some sort of monitoring program on their program you could maybe reverse engineer how it commands the device.
It may be easier just to interface with their UI directly. Using a program like AHK or calling SendInput() to coordinates relative to the upper left corner of their UI, you could command the directions of the device.
EDIT: More links related to this:
Because the USB device doesn't get listed as a COM# (how serial port shows up), and it is a HID device, you need a library that can talk to that. Here are some links that should help you get there:
http://www.qtcentre.org/threads/41075-USB-HID-connect-on-QT
http://www.signal11.us/oss/hidapi/
https://github.com/iia/Qt_libusb
It also looks like the guys at Robo Realm have done it already:
http://www.roborealm.com/help/DC_Missile.php
http://www.roborealm.com/help/USB_HID.php
http://www.roborealm.com/tutorial/usb_missile_launcher/slide010.php
Hope that helps.
I'm using Qt and want a platform-independent way of getting the available free disk space.
I know in Linux I can use statfs and in Windows I can use GetDiskFreeSpaceEx(). I know boost has a way, boost::filesystem::space(Path const & p).
But I don't want those. I'm in Qt and would like to do it in a Qt-friendly way.
I looked at QDir, QFile, QFileInfo -- nothing!
I know It's quite old topic but somebody can still find it useful.
Since QT 5.4 the QSystemStorageInfo is discontinued, instead there is a new class QStorageInfo that makes the whole task really simple and it's cross-platform.
QStorageInfo storage = QStorageInfo::root();
qDebug() << storage.rootPath();
if (storage.isReadOnly())
qDebug() << "isReadOnly:" << storage.isReadOnly();
qDebug() << "name:" << storage.name();
qDebug() << "fileSystemType:" << storage.fileSystemType();
qDebug() << "size:" << storage.bytesTotal()/1024/1024 << "MB";
qDebug() << "availableSize:" << storage.bytesAvailable()/1024/1024 << "MB";
Code has been copied from the example in QT 5.5 docs
The new QStorageInfo class, introduced in Qt 5.4, can do this (and more). It's part of the Qt Core module so no additional dependencies required.
#include <QStorageInfo>
#include <QDebug>
void printRootDriveInfo() {
QStorageInfo storage = QStorageInfo::root();
qDebug() << storage.rootPath();
if (storage.isReadOnly())
qDebug() << "isReadOnly:" << storage.isReadOnly();
qDebug() << "name:" << storage.name();
qDebug() << "filesystem type:" << storage.fileSystemType();
qDebug() << "size:" << storage.bytesTotal()/1024/1024 << "MB";
qDebug() << "free space:" << storage.bytesAvailable()/1024/1024 << "MB";
}
I wrote this back when I wrote the question (after voting on QTBUG-3780); I figure I'll save someone (or myself) from doing this from scratch.
This is for Qt 4.8.x.
#ifdef WIN32
/*
* getDiskFreeSpaceInGB
*
* Returns the amount of free drive space for the given drive in GB. The
* value is rounded to the nearest integer value.
*/
int getDiskFreeSpaceInGB( LPCWSTR drive )
{
ULARGE_INTEGER freeBytesToCaller;
freeBytesToCaller.QuadPart = 0L;
if( !GetDiskFreeSpaceEx( drive, &freeBytesToCaller, NULL, NULL ) )
{
qDebug() << "ERROR: Call to GetDiskFreeSpaceEx() failed.";
}
int freeSpace_gb = freeBytesToCaller.QuadPart / B_per_GB;
qDebug() << "Free drive space: " << freeSpace_gb << "GB";
return freeSpace_gb;
}
#endif
Usage:
// Check available hard drive space
#ifdef WIN32
// The L in front of the string does some WINAPI magic to convert
// a string literal into a Windows LPCWSTR beast.
if( getDiskFreeSpaceInGB( L"c:" ) < MinDriveSpace_GB )
{
errString = "ERROR: Less than the recommended amount of free space available!";
isReady = false;
}
#else
# pragma message( "WARNING: Hard drive space will not be checked at application start-up!" )
#endif
There is nothing in Qt at time of writing.
Consider commenting on or voting for QTBUG-3780.
I need to write to a mounted USB-Stick and I got the available size of memory with the following code:
QFile usbMemoryInfo;
QStringList usbMemoryLines;
QStringList usbMemoryColumns;
system("df /dev/sdb1 > /tmp/usb_usage.info");
usbMemoryInfo.setFileName( "/tmp/usb_usage.info" );
usbMemoryInfo.open(QIODevice::ReadOnly);
QTextStream readData(&usbMemoryInfo);
while (!readData.atEnd())
{
usbMemoryLines << readData.readLine();
}
usbMemoryInfo.close();
usbMemoryColumns = usbMemoryLines.at(1).split(QRegExp("\\s+"));
QString available_bytes = usbMemoryColumns.at(3);
I know that this question is already quite old by now, but I searched stackoverflow and found that nobody got solution for this, so I decided to post.
There is QSystemStorageInfo class in QtMobility, it provides cross-platform way to get info about logical drives. For example: logicalDrives() returns list of paths which you can use as parameters for other methods: availableDiskSpace(), totalDiskSpace() to get free and total drive's space, accordingly, in bytes.
Usage example:
QtMobility::QSystemStorageInfo sysStrgInfo;
QStringList drives = sysStrgInfo.logicalDrives();
foreach (QString drive, drives)
{
qDebug() << sysStrgInfo.availableDiskSpace(drive);
qDebug() << sysStrgInfo.totalDiskSpace(drive);
}
This example prints free and total space in bytes for all logical drives in OS. Don't forget to add QtMobility in Qt project file:
CONFIG += mobility
MOBILITY += systeminfo
I used these methods in a project I'm working on now and it worked for me. Hope it'll help someone!
this code`s working for me:
#ifdef _WIN32 //win
#include "windows.h"
#else //linux
#include <sys/stat.h>
#include <sys/statfs.h>
#endif
bool GetFreeTotalSpace(const QString& sDirPath, double& fTotal, double& fFree)
{
double fKB = 1024;
#ifdef _WIN32
QString sCurDir = QDir::current().absolutePath();
QDir::setCurrent(sDirPath);
ULARGE_INTEGER free,total;
bool bRes = ::GetDiskFreeSpaceExA( 0 , &free , &total , NULL );
if ( !bRes )
return false;
QDir::setCurrent( sCurDir );
fFree = static_cast<__int64>(free.QuadPart) / fKB;
fTotal = static_cast<__int64>(total.QuadPart) / fKB;
#else // Linux
struct stat stst;
struct statfs stfs;
if ( ::stat(sDirPath.toLocal8Bit(),&stst) == -1 )
return false;
if ( ::statfs(sDirPath.toLocal8Bit(),&stfs) == -1 )
return false;
fFree = stfs.f_bavail * ( stst.st_blksize / fKB );
fTotal = stfs.f_blocks * ( stst.st_blksize / fKB );
#endif // _WIN32
return true;
}