UpdatePTUDevCtrl/update.cpp

650 lines
21 KiB
C++
Raw Normal View History

2023-05-22 16:06:52 +02:00
#include "update.h"
#include <QCoreApplication>
#include <QApplication>
#include <QFile>
#include <QTemporaryFile>
#include <QDebug>
#include <QTextStream>
2023-05-26 13:03:38 +02:00
#include <QRegularExpression>
2023-05-22 16:06:52 +02:00
#include "plugins/interfaces.h"
2023-05-22 16:06:52 +02:00
#include <QSharedMemory>
#include <QScopedPointer>
#include <QProcess>
2023-05-26 13:03:38 +02:00
#include <QDir>
#include <QThread>
#include <QDateTime>
#include <QPluginLoader>
#include <QMap>
2023-05-22 16:06:52 +02:00
#define COLUMN_REQUEST (0)
#define COLUMN_NAME (1)
#define COLUMN_DATE_TIME (2)
#define COLUMN_RESULT (3)
static const QMap<QString, int> baudrateMap = {
{"1200" , 0}, {"9600" , 1}, {"19200" , 2}, {"38400" , 3},
{"57600" , 4}, {"115200" , 5}
};
hwinf *Update::loadDCPlugin(QDir const &plugInDir, QString const &fname) {
hwinf *hw = nullptr;
if (plugInDir.exists()) {
QString pluginLibName(fname);
pluginLibName = plugInDir.absoluteFilePath(pluginLibName);
QFileInfo info(pluginLibName);
if (info.exists()) {
pluginLibName = plugInDir.absoluteFilePath(pluginLibName);
static QPluginLoader pluginLoader(pluginLibName);
if (!pluginLoader.load()) {
qCritical() << "in directory" << plugInDir.absolutePath();
qCritical() << "cannot load plugin" << pluginLoader.fileName();
qCritical() << pluginLoader.errorString();
exit(-1);
}
if (!pluginLoader.isLoaded()) {
qCritical() << pluginLoader.errorString();
exit(-2);
}
QObject *plugin = pluginLoader.instance();
if (!plugin) {
qCritical() << "cannot start instance";
exit(-3);
}
if (! (hw = qobject_cast<hwinf *>(plugin))) {
qCritical() << "cannot cast plugin" << plugin << "to hwinf";
exit(-4);
}
} else {
qCritical() << pluginLibName << "does not exist";
exit(-5);
}
} else {
qCritical() << "plugins directory" << plugInDir.absolutePath()
<< "does not exist";
exit(-6);
2023-05-22 16:06:52 +02:00
}
return hw;
2023-05-22 16:06:52 +02:00
}
Update::Update(hwinf *hw,
QString update_ctrl_file,
2023-05-26 13:03:38 +02:00
QString workingDir,
2023-05-22 16:06:52 +02:00
QObject *parent,
char const *serialInterface,
char const *baudrate)
: QObject(parent)
, m_hw(hw)
2023-05-22 16:06:52 +02:00
, m_serialInterface(serialInterface)
, m_baudrate(baudrate)
, m_update_ctrl_file(update_ctrl_file)
, m_update_ctrl_file_copy(update_ctrl_file + ".copy")
2023-05-26 13:03:38 +02:00
, m_workingDir(workingDir)
, m_init(true) {
2023-05-22 16:06:52 +02:00
2023-05-26 13:03:38 +02:00
execUpdateScript();
2023-05-22 16:06:52 +02:00
if (!m_update_ctrl_file.exists()) {
qCritical() << "Update-file" << m_update_ctrl_file.fileName()
<< "does not exist";
m_init = false;
}
if (!m_update_ctrl_file_copy.exists()) {
qCritical() << "Update-file-copy" << m_update_ctrl_file_copy.fileName()
<< "does not exist";
m_init = false;
}
if (!m_update_ctrl_file.open(QIODevice::ReadWrite | QIODevice::Text)) {
qCritical() << "can not open " << m_update_ctrl_file.fileName();
m_init = false;
}
qDebug() << "Opened" << m_update_ctrl_file.fileName();
if (!m_update_ctrl_file_copy.open(QIODevice::ReadWrite | QIODevice::Text)) {
qCritical() << "can not open " << m_update_ctrl_file_copy.fileName();
m_init = false;
}
qDebug() << "Opened" << m_update_ctrl_file_copy.fileName();
}
Update::~Update() {
}
2023-05-26 13:03:38 +02:00
bool Update::execUpdateScript() {
// path of update-script 'update_psa'
QString update_psa("/opt/app/tools/atbupdate/update_psa -m --wdir ");
2023-05-26 13:03:38 +02:00
update_psa += m_workingDir;
qCritical() << "update_psa: " << update_psa;
//QApplication::processEvents();
//for (int i=0;i<10;++i) {
// QThread::sleep(1);
//QApplication::processEvents();
//}
// debug
return true;
2023-05-26 13:03:38 +02:00
//QStringList const params(QStringList() << "-c" << update_psa);
QScopedPointer<QProcess> p(new QProcess(this));
p->setProcessChannelMode(QProcess::MergedChannels);
p->start(update_psa);
if (p->waitForStarted(1000)) {
if (p->state() == QProcess::ProcessState::Running) {
if (p->waitForFinished(60000)) {
QString output = p->readAllStandardOutput().toStdString().c_str();
QStringList lst = output.split('\n');
for (int i = 0; i < lst.size(); ++i) {
qDebug() << lst[i];
}
qInfo() << "EXECUTED" << update_psa;
return ((p->exitStatus() == QProcess::NormalExit)
&& (p->exitCode() == 0));
}
}
}
return false;
}
Update::DownloadResult Update::sendStatus(int ret) const {
switch (ret) { // return values of dc are:
case 0: // 0: no answer by now
return DownloadResult::NOP; // 1: error
case 10: // 10: success
return DownloadResult::OK;
default:;
}
return DownloadResult::ERROR;
}
Update::DownloadResult Update::sendNextAddress(int bNum) const {
// sends address only if blockNumber is one of 0, 1024, 2048, 3072, 4096
int noAnswerCount = 0;
int errorCount = 0;
if ( bNum==0 || bNum==1024 || bNum==2048 || bNum==3072 || bNum==4096 ) {
qDebug() << "addr-block" << bNum << "...";
while (noAnswerCount <= 250) {
m_hw->bl_sendAddress(bNum);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
DownloadResult const res = sendStatus(m_hw->bl_wasSendingAddOK());
if (res != DownloadResult::NOP) {
if (res == DownloadResult::ERROR) {
if (++errorCount >= 10) {
qCritical() << "addr-block" << bNum << "...FAILED";
return res;
}
} else { // res == DownloadResult::OK
qInfo() << "addr-block" << bNum << "...OK";
return res;
}
} else {
noAnswerCount += 1; // no answer by now
}
}
// wait max. about 3 seconds
return DownloadResult::TIMEOUT;
}
// blockNumber is not one of 0, 1024, 2048, 3072, 4096 -> do nothing
return DownloadResult::NOP;
}
Update::DownloadResult Update::sendNextDataBlock(QByteArray const &binary,
int bNum) const {
uint8_t local[66];
int const bAddr = bNum * 64;
int noAnswerCount = 0;
int errorCount = 0;
memcpy(local, binary.constData() + bAddr, 64);
local[64] = local[65] = 0x00;
//for (int i=0; i<4; ++i) {
// printf("%04d ", bNum);
// for (int j=0; j < 16; ++j) {
// printf("%02x ", local[i*16 + j]);
// } printf("\n");
//}
while (noAnswerCount <= 250) {
m_hw->bl_sendDataBlock(64, local);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
DownloadResult const res = sendStatus(m_hw->bl_wasSendingDataOK());
if (res != DownloadResult::NOP) {
if (res == DownloadResult::ERROR) {
if (++errorCount >= 10) {
qCritical() << "data for block" << bNum << "...FAILED";
return res;
}
} else {
qInfo() << "data for block" << bNum << "OK";
return res;
}
} else {
noAnswerCount += 1; // no answer by now
}
}
// wait max. about 3 seconds
return DownloadResult::TIMEOUT;
}
Update::DownloadResult Update::dc_downloadBinary(QByteArray const &b) const {
int const nBlocks = (((b.size())%64)==0) ? (b.size()/64) : (b.size()/64)+1;
qInfo() << "total number of bytes to send to dc" << b.size();
qInfo() << "total number of blocks to send to dc" << nBlocks;
int bNum = 0;
DownloadResult res = DownloadResult::OK;
while (res != DownloadResult::ERROR && bNum < nBlocks) {
if ((res = sendNextAddress(bNum)) != DownloadResult::ERROR) {
if ((res = sendNextDataBlock(b, bNum)) != DownloadResult::ERROR) {
bNum += 1;
}
}
}
qInfo() << "nBlocks" << nBlocks;
//if (res != DownloadResult::ERROR) {
// always send last block, even when there are no data !!!
int const rest = b.size() % 64;
int const offset = b.size() - rest;
char const *startAddress = b.constData() + offset;
uint8_t local[66];
memset(local, 0x00, sizeof(local));
if (rest > 0) {
memcpy(local, startAddress, rest);
}
//for (int i=0; i<4; ++i) {
// printf("*** %04d ", bNum);
// for (int j=0; j < 16; ++j) {
// printf("%02x ", local[i*16 + j]);
// } printf("\n");
//}
// bl_sendLastBlock(local);
m_hw->bl_sendLastBlock();
qInfo() << "last result" << (int)sendStatus(m_hw->bl_wasSendingDataOK());
return res;
}
bool Update::startBootloader() const {
qDebug() << "starting bootloader...";
int nTry = 5;
while (--nTry >= 0) {
m_hw->bl_startBL();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
m_hw->bl_checkBL();
if (m_hw->bl_isUp()) {
qInfo() << "starting bootloader...OK";
std::this_thread::sleep_for(std::chrono::milliseconds(500));
return true;
}
}
qCritical() << "starting bootloader...FAILED";
return false;
}
bool Update::stopBootloader() const {
qDebug() << "stopping bootloader...";
int nTry = 5;
while (--nTry >= 0) {
m_hw->bl_stopBL();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
if (!m_hw->bl_isUp()) {
qInfo() << "stopping bootloader...OK";
return true;
}
}
qCritical() << "stopping bootloader...FAILED";
return false;
}
// br is a index into a table, used for historical reasons.
bool Update::openSerial(int br, QString baudrate, QString comPort) const {
qDebug() << "opening serial" << br << baudrate << comPort << "...";
if (m_hw->dc_openSerial(br, baudrate, comPort, 1)) { // 1 for connect
qInfo() << "opening serial" << br << baudrate << comPort << "...OK";
return true;
}
qCritical() << "opening serial" << br << baudrate << comPort << "...FAILED";
return false;
}
void Update::closeSerial() const {
m_hw->dc_closeSerial();
}
bool Update::resetDeviceController() const {
qDebug() << "resetting device controller...";
//if (stopBootloader()) { // first stop a (maybe) running bootloader
// std::this_thread::sleep_for(std::chrono::milliseconds(1000));
m_hw->bl_rebootDC();
// wait maximally 3 seconds, before starting bootloader
std::this_thread::sleep_for(std::chrono::milliseconds(1500));
qInfo() << "resetting device controller...OK";
return true;
//}
//qCritical() << "stopping bootloader...FAILED";
//return false;
}
QByteArray Update::loadBinaryDCFile(QString filename) const {
qDebug() << "loading dc binary" << filename << "...";
QFile file(filename); // closed in destructor call
if (!file.exists()) {
qCritical() << file.fileName() << "does not exist";
return QByteArray();
}
if (!file.open(QIODevice::ReadOnly)) {
qCritical() << "cannot open file" << file.fileName();
return QByteArray();
}
qInfo() << "loading dc binary" << filename << "...OK";
return file.readAll();
}
bool Update::downloadBinaryToDC(QString const &bFile) const {
qDebug() << "sending" << bFile << "to dc...";
QByteArray const dcBinary = loadBinaryDCFile(bFile);
if (dcBinary.size() > 0) {
if (dc_downloadBinary(dcBinary) != DownloadResult::OK) {
qCritical() << "sending" << bFile << "to dc...FAILED";
return false;
} else {
qInfo() << "sending" << bFile << "to dc...OK";
}
} else {
qCritical() << "sending" << bFile << "to dc...FAILED";
qCritical() << "loading binary" << bFile << "FAILED";
return false;
}
return true;
}
2023-05-22 16:06:52 +02:00
bool Update::updateBinary(char const *fileToSendToDC) {
QFile fn(fileToSendToDC);
bool r;
if ((r = fn.exists()) == true) {
QString const linkTarget = fn.symLinkTarget();
qInfo() << "updating binary (dc)" << linkTarget << "...";
if ((r = updateDC(linkTarget, m_baudrate, m_serialInterface)) == true) {
qInfo() << "updating binary (dc)" << linkTarget << "... done";
} else {
qCritical() << "updating binary (dc)" << linkTarget << "... FAILED";
}
} else {
qCritical() << "symlink" << fileToSendToDC << "does not exist";
}
return r;
2023-05-22 16:06:52 +02:00
}
bool Update::updateDC(QString bFile, QString br, QString serial) const {
if (!baudrateMap.contains(br)) { // sanity check
qCritical() << "passed wrong baudrate" << br;
return false;
}
m_hw->dc_autoRequest(false);
qDebug() << "updating dc: " << bFile << br << serial << "...";
return true;
if (!openSerial(baudrateMap.value(br), br, serial)) {
return false;
}
if (!resetDeviceController()) {
closeSerial();
return false;
}
if (!startBootloader()) {
closeSerial();
return false;
}
if (!downloadBinaryToDC(bFile)) {
stopBootloader();
closeSerial();
qCritical() << "updating dc: " << bFile << br << serial << "...FAILED";
return false;
}
qInfo() << "updating dc: " << bFile << br << serial << "...OK";
stopBootloader();
QThread::sleep(3);
closeSerial();
return true;
}
bool Update::updatePrinterTemplate(enum FileTypeJson type,
int templateIdx,
QString fname,
QString br,
QString serial) const {
// sanity checks
if (!baudrateMap.contains(br)) {
qCritical() << "passed wrong baudrate" << br;
return false;
}
if (type != FileTypeJson::PRINTER) {
qCritical() << "wrong file type" << (uint8_t)type;
return false;
}
qDebug() << "updating: " << fname << br << serial << "...";
if (!serial.isNull()) {
if (!openSerial(baudrateMap.value(br), br, serial)) {
return false;
}
}
int nTry = 50;
while (!m_hw->sys_ready4sending()) { // wait max. 5 seconds
std::this_thread::sleep_for(std::chrono::milliseconds(100));
if (--nTry <= 0) {
qCritical() << "sys not ready for sending";
if (!serial.isNull()) {
closeSerial();
}
return false;
}
}
bool ret = true;
QFile file(fname);
if (file.exists() && file.open(QIODevice::ReadOnly)) {
QByteArray ba = file.readAll();
if (ba.size() <= 800) { // max. size is 800 bytes
if (m_hw->sys_sendJsonFileToDc((uint8_t)(type),
templateIdx,
(uint8_t *)ba.data())) {
std::this_thread::sleep_for(std::chrono::seconds(1));
qInfo() << "sent file" << fname << "to dc";
}
}
} else {
qCritical() << fname << "!!! does not exist!!!";
ret = false;
}
if (!serial.isNull()) {
closeSerial();
}
return ret;
}
bool Update::updatePrinterConf(int templateIdx, QString fileToSendToDC) {
qCritical() << "updating printer template: " << fileToSendToDC;
return updatePrinterTemplate(FileTypeJson::PRINTER,
templateIdx,
fileToSendToDC,
QString(m_baudrate),
QString(m_serialInterface));
2023-05-22 16:06:52 +02:00
}
QStringList Update::getOpenLines() {
QStringList openLines;
QTextStream in(&m_update_ctrl_file);
while (!in.atEnd()) {
QString line = in.readLine().trimmed();
if (line.startsWith("DONE")) {
m_update_ctrl_file_copy.write(line.toUtf8().constData());
m_update_ctrl_file_copy.write("\n");
} else {
openLines << line;
}
}
return openLines;
}
QStringList Update::split(QString line, QChar sep) {
2023-05-22 16:06:52 +02:00
QStringList lst;
QString next;
int start = 0, end;
while ((end = line.indexOf(sep, start)) != -1) {
2023-05-22 16:06:52 +02:00
next = line.mid(start, end - start).trimmed();
lst << next;
start = end + 1;
}
next = line.mid(start, end - start).trimmed();
lst << next;
return lst;
}
bool Update::doUpdate() {
/*
The file referred to by 'update_data' has the following structure for
each line:
# ======================================================================
# REQUEST | NAME | DATE | RESULT
# ======================================================================
# where
#
# STATUS: DOWNLOAD, EXECUTE or DONE
# NAME : If starting with 'opkg' it is an opkg-command to be executed.
# Otherwise its the name of a file which has to be updated.
# DATE : 0000-00-00T00:00:00
# RESULT: SUCCESS or ERROR (possibly with description)
#
*/
2023-05-22 16:06:52 +02:00
if (!m_init) {
return false;
}
QStringList openLines = getOpenLines();
if (openLines.size() == 0) {
qCritical() << "No lines to handle in" << m_update_ctrl_file.fileName();
return false;
}
qDebug() << "open lines...";
for (int i=0; i< openLines.size(); ++i) {
qDebug() << "line" << i << ":" << openLines.at(i).trimmed();
}
2023-05-22 16:06:52 +02:00
QList<QString>::const_iterator it;
for (it = openLines.cbegin(); it != openLines.cend(); ++it) {
bool res = false;
QString line = (*it).trimmed();
if (line.size() == 0 || line.startsWith(QChar('#'))) {
continue;
}
QStringList lst = split(line.trimmed());
if (lst.size() != 4) {
qCritical() << "Parsing error for" << m_update_ctrl_file.fileName();
return false;
}
QString const &request = lst[COLUMN_REQUEST];
QString const &name = lst[COLUMN_NAME];
// QString const &datetime = lst[COLUMN_DATE_TIME];
QString const &result = lst[COLUMN_RESULT];
if ((!request.contains("DOWNLOAD") && !request.contains("EXECUTE")) ||
!result.contains("N/A")) {
qCritical() << "parsing error for" << m_update_ctrl_file.fileName();
2023-05-22 16:06:52 +02:00
return false;
}
if (name.contains("dc2c") && name.endsWith(".bin")) {
qInfo() << "downloading" << name.trimmed() << "to DC";
2023-05-22 16:06:52 +02:00
if ((res = updateBinary(name.toStdString().c_str())) == true) {
qInfo() << "downloaded binary" << name;
2023-05-22 16:06:52 +02:00
}
} else
if (name.contains("DC2C_print") && name.endsWith(".json")) {
int i = name.indexOf("DC2C_print");
int templateIdx = name.mid(i).midRef(10, 2).toInt();
if ((templateIdx < 1) || (templateIdx > 32)) {
qCritical() << "wrong template index";
res = false;
} else {
if ((res = updatePrinterConf(templateIdx, name)) == true) {
qInfo() << "downloaded printer template" << name;
}
2023-05-22 16:06:52 +02:00
}
} else
if (name.contains("opkg")) {
qInfo() << "starting" << name.trimmed();
2023-05-22 16:06:52 +02:00
QScopedPointer<QProcess> p(new QProcess(this));
p->setProcessChannelMode(QProcess::MergedChannels);
p->start(name.trimmed());
2023-05-22 16:06:52 +02:00
if (p->waitForStarted(1000)) {
if (p->state() == QProcess::ProcessState::Running) {
if (p->waitForFinished(100000)) {
QString output = p->readAllStandardOutput();
QStringList outputLst = split(output, QChar('\n'));
for (int line=0; line < outputLst.size(); ++line) {
qDebug() << outputLst[line];
}
2023-05-22 16:06:52 +02:00
res = true;
qInfo() << "EXECUTED" << name;
}
}
}
} else {
// TODO
}
char buf[80];
int const bytesWritten =
snprintf(buf, sizeof(buf)-1, "DONE, %*.*s, %*.*s, %*.*s\n",
35, 35, name.toStdString().c_str(),
20, 20, QDateTime::currentDateTime().toString(Qt::ISODate).toStdString().c_str(),
10, 10, (res == true) ? "SUCCESS" : "ERROR");
if (bytesWritten < 80) {
buf[bytesWritten] = '\0';
}
m_update_ctrl_file_copy.write(buf);
} // for (it = openLines.cbegin(); it != openLines.end(); ++it) {
return finishUpdate(openLines.size() > 0);
}
bool Update::finishUpdate(bool swapCtrlFiles) {
if (swapCtrlFiles) {
m_update_ctrl_file.close();
m_update_ctrl_file_copy.close();
QString const &fn = m_update_ctrl_file.fileName();
QString const &fn_tmp = m_update_ctrl_file.fileName() + ".tmp";
QString const &fn_copy = m_update_ctrl_file_copy.fileName();
QFile tmp(fn_tmp);
if (tmp.exists()) {
tmp.remove();
}
if (m_update_ctrl_file.rename(fn_tmp)) {
if (m_update_ctrl_file_copy.rename(fn)) {
return m_update_ctrl_file.rename(fn_copy);
}
}
return false;
}
return true;
}