-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.cpp
1141 lines (1066 loc) · 48.4 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
@file main.cpp
@brief Main program to read EKM meters and save response in database.
@author Thomas A. DeMay
@date 2015
@par Copyright (C) 2015 Thomas A. DeMay
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <QCoreApplication>
#include <QtCore/QCoreApplication>
#include <QtCore/QCommandLineParser>
#include <QtCore/QCommandLineOption>
#include <QtSql>
#include <QtSerialPort>
#include <QtSerialPort/QSerialPortInfo>
#include <unistd.h>
#include <stdlib.h>
#include "../SupportRoutines/supportfunctions.h"
#include "messages.h"
/* ******** Global variable declarations ***************/
QTimeZone LocalTimeZone = QTimeZone(QTimeZone::systemTimeZoneId()); //!< The local timezone, either Standard time or Daylight time.
QTimeZone LocalStandardTimeZone = QTimeZone(LocalTimeZone.standardTimeOffset(QDateTime::currentDateTime())); //!< Timezone for Local Standard time.
/* ******** Global function declarations ***************/
bool ConnectSerial(const QString &serialDeviceName, QSerialPort **serialPortPtr);
bool SaveV3ResponseToDatabase(const ResponseV3Data &responseData);
bool SaveV4ResponseToDatabase(const uint8_t responseType, const ResponseV4Generic &response);
bool GetMeterV4Data(QSerialPort *serialPort, const QString meterId, const uint8_t requestType, ResponseV4Generic *response);
bool GetMeterV3Data(QSerialPort *serialPort, const QString meterId, ResponseV3Data *response);
bool ReadResponse(QSerialPort *serialPort, qint8 *msg, const qint64 msgSize);
bool WriteSerialMsg(QSerialPort *serialPort, const char *msg, const qint64 msgSize);
bool ValidateCRC(const uint8_t *msg, int numBytes);
bool SendControl(QSerialPort *serialPort, QString &meterId, OutputControlDef *ctrlMsg, const int msgSize);
bool SetMeterTime(QSerialPort *serialPort, QString &meterId);
bool InitializeMeters(QSerialPort *serialPort, const QStringList &args);
void VerifyDatabaseTable(QSqlQuery &query, const QString fullMeterId, const QString dataKind);
uint16_t computeEkmCrc(const uint8_t *dat, uint16_t len);
/* ********** Global function definitions *************/
/*!
* \brief VerifyDatabaseTable -- Create meter data table if it doesn't exist.
*
* Returns without doing anything if the dataKind is unrecognized.
*
* Query the INFORMATION_SCHEMA for the existence of the desired table.
* If errors accessing INFORMATION_SCHEMA, assume the table exists.
* If the INFORMATION_SCHEMA query returns a result, the table exists.
* Otherwise, try to create the table. Assume success, we will fail later
* if the table could not be created.
*
* \param query QSqlQuery opened on the database.
* \param fullMeterId Meter serial number expanded to 12 characters.
* \param dataKind Kind of table to check. Must be one of: "_A", "_B" or "".
*/
void VerifyDatabaseTable(QSqlQuery &query, const QString fullMeterId, const QString dataKind)
{
/* dataKind must be one of: "_A", "_B" or "". */
qDebug("Begin");
if ((dataKind != "_A") && (dataKind != "_B") && (dataKind != ""))
{
qWarning("dataKind argument is not a legal value. Should be one of \"_A\", \"_B\", or \"\". Was \"%s\"."
, qUtf8Printable(dataKind));
qDebug("Return");
return;
}
if (!query.exec(QString("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '%1%2_RawMeterData'")
.arg(fullMeterId)
.arg(dataKind)))
{
qCritical("Unable to access INFORMATION_SCHEMA; assume data tables exist.");
qInfo(" Query was: %s", qUtf8Printable(query.lastQuery()));
qInfo(" Error was: %s", qUtf8Printable(query.lastError().text()));
}
else
{
qDebug("Successfully accessed INFORMATION_SCHEMA for query about existence of data table.");
if (!query.next())
{
// the query returned no results => table does not exist. Create it.
QString queryText = QString("CREATE TABLE `%1%2_RawMeterData` ("
"`idRawMeterData` int(11) NOT NULL AUTO_INCREMENT,"
"`ComputerTime` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) COMMENT 'Time that record written to database.',"
"`MeterTime` datetime DEFAULT NULL COMMENT 'Meter time from response message.',"
"`MeterId` varchar(12) DEFAULT NULL COMMENT 'Meter ID (Serial number) from response.',"
"`MeterType` varchar(4) DEFAULT NULL,"
"`DataType` varchar(4) DEFAULT NULL COMMENT 'Either \"V3\", \"V4A\" or \"V4B\"',"
"`MeterData` binary(255) NOT NULL COMMENT 'Exact copy of entire response data from meter.',"
"PRIMARY KEY (`idRawMeterData`),"
"UNIQUE KEY `idRawMeterData_UNIQUE` (`idRawMeterData`)"
") ENGINE=InnoDB AUTO_INCREMENT=8281 DEFAULT CHARSET=utf8")
.arg(fullMeterId)
.arg(dataKind);
if (!DontActuallyWriteDatabase)
{
if (!query.exec(queryText))
{
qCritical("Unable to create RawMeterData %s table for %s meter. Assume table already exists."
, qUtf8Printable(dataKind)
, qUtf8Printable(fullMeterId));
qInfo(" Query was: %s", qUtf8Printable(query.lastQuery()));
qInfo(" Error was: %s", qUtf8Printable(query.lastError().text()));
}
else
{
qInfo("Successfully created Table %s%s_RawMeterData"
, qUtf8Printable(fullMeterId)
, qUtf8Printable(dataKind));
}
}
else
{
qInfo() << "Didn't actually create database table. Command was:";
qInfo() << queryText;
}
}
qDebug("Table %s%s_RawMeterData exists.", qUtf8Printable(fullMeterId), qUtf8Printable(dataKind));
}
qDebug("Return");
return;
}
/*!
* \brief InitializeMeters -- Once per program execution actions.
*
* Opens a connection to the database.
*
* For each meter in the args list, check to see if there is a table in the
* database for the response from the meter. If not, create the table.
*
* Each meter has its time set to the local standard time.
*
* \param serialPort Pointer to serial port for communication with meter.
* \param args List of meter ids from command line.
* \return true if successful, false otherwise.
*/
bool InitializeMeters(QSerialPort *serialPort, const QStringList &args)
{
qDebug("Begin");
QSqlDatabase dbConn = QSqlDatabase::database(ConnectionName);
if (!dbConn.isOpen())
{
qCritical() << "Unable to open database for meter data.";
qInfo() << "Return false";
return false;
}
QSqlQuery query(dbConn);
/*! Do meter initialization tasks for each meter. */
foreach (QString meterId, args)
{
//! Expand meter id to all 12 characters.
QString fullMeterId = meterId.rightJustified(sizeof(RequestMsgV4.meterId), '0', true);
//! Check for the existence of database tables in which to store meter data.
if (fullMeterId.toLongLong() >= 300000000)
{
// Is a v.4 meter.
//! Set the time in the meter to the computer's idea of the local standard time.
if (!SetMeterTime(serialPort, fullMeterId))
{
qWarning("Unable to set meter time for meter %s.", qUtf8Printable(fullMeterId));
}
// Create the tables if they don't exist.
VerifyDatabaseTable(query, fullMeterId, "_A");
VerifyDatabaseTable(query, fullMeterId, "_B");
}
else
{
// Is a v.3 meter.
// Don't try to set meter time for v.3 meter since I don't know how to do it.
// Create the table if it doesn't exist.
VerifyDatabaseTable(query, fullMeterId, "");
}
}
return true;
}
/*!
* \brief ConnectSerial -- Create connection to serial device.
* \param serialDeviceName Name of serial device.
* \param serialPortPtr Pointer to pointer to serial port.
* \return true if successful, false otherwise.
*/
bool ConnectSerial(const QString &serialDeviceName, QSerialPort **serialPortPtr)
{
qInfo("Begin");
if (serialPortPtr == NULL)
{
qDebug() << "Connect Serial called with serialPortPtr NULL.";
qDebug() << "Return false";
return false;
}
QSerialPort *serialPort = *serialPortPtr;
/*! If the serial port we're given is already connected to something,
* close the connection.
*/
if (serialPort != NULL)
{
serialPort->flush();
serialPort->close();
delete serialPort;
serialPort = NULL;
*serialPortPtr = serialPort;
}
/*! Get information about the serial device. */
const QSerialPortInfo info(serialDeviceName);
if (info.isNull())
{
qDebug("Serial port info for %s is null AND it is %s", qUtf8Printable(serialDeviceName), info.isBusy()?"busy.":"not busy.");
qInfo() << "Available serial ports are:";
QList<QSerialPortInfo> portList(QSerialPortInfo::availablePorts());
foreach (QSerialPortInfo pl, portList) {
qInfo() << " " << pl.portName() << pl.description() << pl.systemLocation();
}
qInfo() << "Return false";
return false;
}
qDebug() << "Got port info for port" << info.portName();
if (info.isBusy())
{
qDebug() << serialDeviceName << "is busy";
qInfo() << "Available serial ports are:";
QList<QSerialPortInfo> portList(QSerialPortInfo::availablePorts());
foreach (QSerialPortInfo pl, portList) {
qInfo() << " " << pl.portName() << pl.description() << pl.systemLocation();
}
qInfo() << "Return false";
return false;
}
qDebug() << info.portName() << "is supposedly not busy.";
QString s = QObject::tr("Port: ") + info.portName() + "\n"
+ QObject::tr("Location: ") + info.systemLocation() + "\n"
+ QObject::tr("Description: ") + info.description() + "\n"
+ QObject::tr("Manufacturer: ") + info.manufacturer() + "\n"
+ QObject::tr("Serial number: ") + info.serialNumber() + "\n"
+ QObject::tr("Vendor Identifier: ") + (info.hasVendorIdentifier() ? QString::number(info.vendorIdentifier(), 16) : QString()) + "\n"
+ QObject::tr("Product Identifier: ") + (info.hasProductIdentifier() ? QString::number(info.productIdentifier(), 16) : QString()) + "\n"
+ QObject::tr("Busy: ") + (info.isBusy() ? QObject::tr("Yes") : QObject::tr("No")) + "\n";
qDebug() << (s);
serialPort = new QSerialPort(info);
qDebug() << "SerialPort is:" << serialPort;
s = "serialPort: baudRate: " + QString::number(serialPort->baudRate())
+ " dataBits: " + QString::number(serialPort->dataBits())
+ " flowControl: " + QString::number(serialPort->flowControl())
+ " parity: " + QString::number(serialPort->parity())
+ " stop bits: " + QString::number(serialPort->stopBits())
;
qDebug() << (s);
/*! Set the serial port characteristics to EKM specs. */
serialPort->setFlowControl(QSerialPort::NoFlowControl);
serialPort->setBaudRate(9600);
serialPort->setDataBits(QSerialPort::Data7);
serialPort->setParity(QSerialPort::EvenParity);
serialPort->setStopBits(QSerialPort::OneStop);
if (!serialPort->open(QIODevice::ReadWrite))
{
qCritical("Could not open %s: %s", qPrintable(info.portName()), qPrintable(serialPort->errorString()));
qInfo() << "Available serial ports are:";
QList<QSerialPortInfo> portList(QSerialPortInfo::availablePorts());
foreach (QSerialPortInfo pl, portList) {
qInfo() << " " << pl.portName() << pl.description() << pl.systemLocation();
}
}
else
{
qInfo() << (info.portName() + " successfully opened.");
s = "serialPort: baudRate: " + QString::number(serialPort->baudRate())
+ " dataBits: " + QString::number(serialPort->dataBits())
+ " flowControl: " + QString::number(serialPort->flowControl())
+ " parity: " + QString::number(serialPort->parity())
+ " stop bits: " + QString::number(serialPort->stopBits())
;
qDebug() << (s);
*serialPortPtr = serialPort;
}
qInfo() << "Return" << serialPort->isOpen();
return serialPort->isOpen();
}
/*!
* \brief SaveV3ResponseToDatabase -- Store a v.3 meter response in its database table.
* \param responseData Data from v.3 meter to save.
* \return true if successful, false otherwise.
*/
bool SaveV3ResponseToDatabase(const ResponseV3Data &responseData)
{
/*
* Assumes responseData is valid ResponseV3Data.
*/
/*! Extract critical pieces of info from response. */
QVariant meterTime = QDateTime(
QDate( QByteArray((char *)responseData.dateTime.year, 2).toInt() + 2000
, QByteArray((char *)responseData.dateTime.month, 2).toInt()
, QByteArray((char *)responseData.dateTime.day, 2).toInt())
, QTime(QByteArray((char *)responseData.dateTime.hour, 2).toInt()
, QByteArray((char *)responseData.dateTime.minute, 2).toInt()
, QByteArray((char *)responseData.dateTime.second, 2).toInt()));
QVariant meterId = QString(QByteArray((char *)responseData.meterId, sizeof(responseData.meterId)));
QVariant meterType = QString(QByteArray((char *)responseData.model, 2).toHex());
QVariant meterData = QByteArray((char *)responseData.fixed02, sizeof(responseData)); //!< Gets the response into a byte array.
QVariant dataType = "V3";
QSqlDatabase dbConn = QSqlDatabase::database(ConnectionName);
if (!dbConn.isOpen())
{
qCritical() << "Unable to open database to save solar data.";
qInfo() << "Return false";
return false;
}
QSqlQuery query(dbConn);
query.prepare("INSERT INTO RawMeterData (MeterTime, MeterId, DataType, MeterType, MeterData) VALUES (?, ?, ?, ?, ?)");
query.bindValue(0, meterTime);
query.bindValue(1, meterId);
query.bindValue(2, meterType);
query.bindValue(3, dataType);
query.bindValue(4, meterData);
if (!DontActuallyWriteDatabase)
{
if (!query.exec())
{
qCritical() << "Error inserting raw meter data record in database: " << query.lastError() << "\nQuery: " << query.lastQuery();
qInfo() << "Return false";
return false;
}
else
qDebug() << "Inserting raw meter data was successful.";
}
else
{
qDebug() << "Did not execute " << query.lastQuery();
}
qInfo() << "Return true";
return true;
}
/*!
* \brief SaveV4ResponseToDatabase
* \param responseType x30 if response A, otherwise B.
* \param response Data from meter.
* \return true if successful, false otherwise.
*/
bool SaveV4ResponseToDatabase(const uint8_t responseType, const ResponseV4Generic &response)
{
/*
* Assumes responseData is valid ResponseV4Data.
*/
QString meterTable;
QVariant dataType;
QVariant meterTime = QDateTime(
QDate( QByteArray((char *)response.responseV4Generic.dateTime.year, 2).toInt() + 2000
, QByteArray((char *)response.responseV4Generic.dateTime.month, 2).toInt()
, QByteArray((char *)response.responseV4Generic.dateTime.day, 2).toInt())
, QTime(QByteArray((char *)response.responseV4Generic.dateTime.hour, 2).toInt()
, QByteArray((char *)response.responseV4Generic.dateTime.minute, 2).toInt()
, QByteArray((char *)response.responseV4Generic.dateTime.second, 2).toInt()));
QVariant meterId = QString(QByteArray((char *)response.responseV4Generic.meterId, sizeof(response.responseV4Generic.meterId)));
QVariant meterType = QString(QByteArray((char *)response.responseV4Generic.model, 2).toHex());
QVariant meterData = QByteArray((char *)response.responseV4Generic.fixed02, sizeof(response));
if (responseType == '\x30')
{
meterTable = meterId.toString() + "_A_RawMeterData";
dataType = "V4A";
}
else
{
meterTable = meterId.toString() + "_B_RawMeterData";
dataType = "V4B";
}
qDebug("Response meterTime %s, meterId %s, meterType %s, dataType %s"
, qUtf8Printable(meterTime.toString())
, qUtf8Printable(meterId.toString())
, qUtf8Printable(meterType.toString())
, qUtf8Printable(dataType.toString()));
QSqlDatabase dbConn = QSqlDatabase::database(ConnectionName);
if (!dbConn.isOpen())
{
qCritical() << "Unable to open database to save solar data.";
qInfo() << "Return false";
return false;
}
QSqlQuery query(dbConn);
query.prepare(QString("INSERT INTO %1 (MeterTime, MeterId, MeterType, DataType, MeterData) VALUES (?, ?, ?, ?, ?)").arg(meterTable));
query.bindValue(0, meterTime);
query.bindValue(1, meterId);
query.bindValue(2, meterType);
query.bindValue(3, dataType);
query.bindValue(4, meterData);
if (!DontActuallyWriteDatabase)
{
if (!query.exec())
{
qCritical("Error inserting raw meter %02x data record in database: %s\n Query: %s"
, responseType
, qUtf8Printable(query.lastError().text())
, qUtf8Printable(query.lastQuery()));
qInfo() << "Return false";
return false;
}
else
qDebug("Inserting raw meter %s data was successful.", qUtf8Printable(dataType.toString()));
}
else
{
qDebug() << "Did not execute " << query.lastQuery();
}
qInfo() << "Return true";
return true;
}
/*!
* \brief WriteSerialMsg -- Write a message to the meter.
* \param serialPort Serial port to use.
* \param msg Message to send.
* \param msgSize Size of message to send.
* \return true if successful, false otherwise.
*/
bool WriteSerialMsg(QSerialPort *serialPort, const char *msg, const qint64 msgSize)
{
qDebug() << "Begin";
qint64 bytesWritten = 0;
qInfo("msg is: %s", qUtf8Printable(QByteArray(msg, msgSize).toHex()));
bytesWritten = serialPort->write(msg, msgSize);
qDebug() << bytesWritten << "of" << msgSize << "bytes of msg written.";
bool writeSuccess = serialPort->waitForBytesWritten(10000);
if (!writeSuccess || (bytesWritten != msgSize))
{
qWarning() << "Unable to write message. Wait status =" << writeSuccess;
qInfo() << "Return false";
return false;
}
qInfo() << "Successfully wrote message.";
qDebug() << "Return true";
return true;
}
/*!
* \brief ReadResponse -- Read a response from the meter.
*
* Response is put into a character array so that it can have
* structure imposed on it for ease of intreptation.
*
* \param serialPort Serial port to read.
* \param msg Pointer to character array in which to put response.
* \param msgSize Expected size of response.
* msg array must be large enough to accomodate this many characters.
* \return true if successful, false otherwise.
*/
bool ReadResponse(QSerialPort *serialPort, qint8 *msg, const qint64 msgSize)
{
FlushDiagnostics();
/* Install the saveMessageOutput message handler so that timing considerations
* will not be impacted by terminal output. Restore message handler before returning.
*/
QtMessageHandler prevMsgHandler = qInstallMessageHandler(saveMessageOutput);
qDebug() << "Begin";
qDebug() << serialPort;
qDebug() << "The message address is" << msg;
qDebug() << msgSize << "is the size the response.";
static const int maxTries = 10;
qint64 bytesRead = 0, bytesThisRead = 0, prevBytesAvail = 0, bytesAvail = 0;
QByteArray readData;
int tryReadCount = 0;
while (bytesRead < msgSize)
{
qDebug() << "Wait for ready read 10 sec.";
if (!serialPort->waitForReadyRead(10000))
{
qWarning() << "Read timeout waiting for message";
qInstallMessageHandler(prevMsgHandler);
qDebug() << "Return false";
return false;
}
qDebug() << "waitForReadyRead(10000) returned true.";
bytesAvail = serialPort->bytesAvailable();
while ((bytesAvail < msgSize) && (bytesAvail > prevBytesAvail))
{
/*! Compute the number of microsec to wait to get the rest of the message.
* Some extra time in the form of 12 extra characters is allowed.
* 960 = characters per second at 9600 baud. (1 start bit, 7 data bits, 1 parity bit, 1 stop bit)
* Do arithmetic as indicated to preserve significance.
*/
useconds_t usec = (((msgSize - bytesAvail + 12ll) * 1000000ll) / 960ll);
qDebug("Waiting for %u usec to get %lld = (%lld - %lld) more bytes."
, usec
, (msgSize - bytesAvail)
, msgSize
, bytesAvail);
usleep(usec);
prevBytesAvail = bytesAvail;
qDebug() << "Wait again for ready read 10 msec.";
// bytesAvailable doesn't seem to update unless waitForReadyRead is called.
if (!serialPort->waitForReadyRead(10))
qWarning() << "Read timeout waiting for more bytes. Continue.";
else
qDebug() << "waitForReadyRead(10) returned true.";
qDebug() << " Now get the count again.";
bytesAvail = serialPort->bytesAvailable();
qDebug("Now there are %lld bytes available.", bytesAvail);
}
qDebug() << "Now read the data.";
readData = serialPort->readAll(); // Read into QByteArray.
bytesThisRead = readData.size();
if (serialPort->error() != QSerialPort::NoError)
{
qDebug("Data was ready for reading, but an error occurred trying to read. We read %lld bytes.", bytesThisRead);
qDebug() << "Error code is: " << serialPort->error() << "Error was: " << serialPort->errorString();
qInstallMessageHandler(prevMsgHandler);
qDebug() << "Return false";
return false;
}
else if ((bytesThisRead == 0) && (tryReadCount < maxTries))
{
qDebug() << "Data was ready for reading, but no bytes were read. Try reading again.";
tryReadCount++;
continue;
}
qDebug("%lld bytes read are: %s", bytesThisRead, qUtf8Printable(readData.toHex()));
qDebug("Copying %lld bytes read to msg at %p"
, qMax(qMin(bytesThisRead, (msgSize - bytesRead)), 0ll)
, (void *)((qint8 *)msg + bytesRead));
memcpy(((qint8 *)msg + bytesRead)
, readData.constData()
, qMax(qMin(bytesThisRead, (msgSize - bytesRead)), 0ll));
bytesRead += qMax(qMin(bytesThisRead, (msgSize - bytesRead)), 0ll);
qDebug("%lld bytes of Msg is now: %s\n", bytesRead, qUtf8Printable(QByteArray((char *)msg, bytesRead).toHex()));
}
qInstallMessageHandler(prevMsgHandler);
qDebug() << "Return true";
return true;
}
/*!
* \brief SendControl -- Send a control message to meter with interaction.
*
* Send request for "A" response to establish communication with a particular
* meter. Read response, send password message, read response,
* send this message, read response, send close message.
* \param serialPort
* \param meterId Full 12 character serial number of meter.
* \param ctrlMsg The message to send.
* \param msgSize The size of the message.
* \return true if successful, false otherwise.
*/
bool SendControl(QSerialPort *serialPort, QString &meterId, OutputControlDef *ctrlMsg, const int msgSize)
{
if (meterId.toLongLong() < 300000000)
{
qDebug() << "I only know how to send controls to v.4 Omnimeters.";
qDebug() << "Return false";
return false;
}
if (ctrlMsg == NULL)
{
qDebug () << "ctrlMsg is NULL";
qDebug() << "Return false";
return false;
}
{
qint8 ackResponse[1];
ResponseV4AData responseA;
qInfo() << "Begin";
static const int maxTries = 10;
memcpy(RequestMsgV4.meterId, qPrintable(meterId), sizeof(RequestMsgV4.meterId));
RequestMsgV4.reqType[1] = '\x30'; // \x30 to get A data
qInfo("RequestMsgV4 is: %s", qUtf8Printable(QByteArray((const char *)RequestMsgV4.fixedBegin, sizeof(RequestMsgV4)).toHex()));
int tryCount = 0;
while (tryCount++ < maxTries)
{
qDebug() << "Started trying to get data.";
WriteSerialMsg(serialPort, (const char *)RequestMsgV4.fixedBegin, sizeof(RequestMsgV4));
if (ReadResponse(serialPort, (qint8 *)(&responseA), sizeof(responseA)))
break;
}
if (tryCount >= maxTries)
{
qDebug() << "Could not get responseA from V4 meter" << meterId;
qDebug() << "Return false";
return false;
}
// Send the control message.
if (WriteSerialMsg(serialPort, (const char *)PasswordMsg, sizeof(PasswordMsg)))
{
qDebug() << "Wrote Password message ok.";
if (ReadResponse(serialPort, ackResponse, sizeof(ackResponse)))
{
if (ackResponse[0] == ResponseAck[0])
{
qDebug() << "Got ACK from password";
if (WriteSerialMsg(serialPort, (const char *)ctrlMsg->SOH, msgSize))
{
qDebug() << "Wrote control message ok.";
if (ReadResponse(serialPort, ackResponse, sizeof(ackResponse)))
{
if (ackResponse[0] == ResponseAck[0])
qDebug() << "Got ACK from control";
else
qDebug() << "ack response wasn't ACK.";
}
else
qDebug() << "Could not get ack response.";
}
else
qDebug() << "Failed to write control message.";
}
else
qDebug() << "ack response wasn't ACK.";
}
else
qDebug() << "Could not get ack response.";
}
else
qDebug() << "Failed to write password message.";
}
WriteSerialMsg(serialPort, (const char *)CloseString, sizeof(CloseString));
qDebug() << "Return true";
return true;
}
/*!
* \brief SetMeterTime -- Set the meter to this computer's idea of local standard time.
*
* Similar to SendControl() function. Time message must be computed before sending.
*
* \param serialPort
* \param meterId Full 12 character serial number of meter.
* \return true if successful, false otherwise.
*/
bool SetMeterTime(QSerialPort *serialPort, QString &meterId)
{
bool retVal = false;
if (meterId.toLongLong() < 300000000)
{
qDebug() << "I only know how to set time to v.4 Omnimeters; others ignored.";
qDebug() << "Return true";
return true;
}
{
qint8 ackResponse[1];
ResponseV4AData responseA;
qInfo() << "Begin";
static const int maxTries = 10;
memcpy(RequestMsgV4.meterId, qPrintable(meterId), sizeof(RequestMsgV4.meterId));
RequestMsgV4.reqType[1] = '\x30'; // \x30 to get A data
qInfo("RequestMsgV4 is: %s", qUtf8Printable(QByteArray((const char *)RequestMsgV4.fixedBegin, sizeof(RequestMsgV4)).toHex()));
int tryCount = 0;
while (tryCount++ < maxTries)
{
qDebug() << "Started trying to get data.";
WriteSerialMsg(serialPort, (const char *)RequestMsgV4.fixedBegin, sizeof(RequestMsgV4));
if (ReadResponse(serialPort, (qint8 *)(&responseA), sizeof(responseA)))
break;
}
if (tryCount >= maxTries)
{
qDebug() << "Could not get responseA from V4 meter" << meterId;
qDebug() << "Return false";
return false;
}
// Send the control message.
if (WriteSerialMsg(serialPort, (const char *)PasswordMsg, sizeof(PasswordMsg)))
{
qDebug() << "Wrote Password message ok.";
if (ReadResponse(serialPort, ackResponse, sizeof(ackResponse)))
{
if (ackResponse[0] == ResponseAck[0])
{
qDebug() << "Got ACK from password";
SetTimeMsgDef setTime = SetTimeMsg;
QDateTime timeNow = QDateTime::currentDateTime();
qInfo() << "The current time is: " << timeNow;
memcpy((void *)&(setTime.dateTime), qPrintable(
timeNow.toTimeZone(LocalStandardTimeZone)
.toString("yyMMdd00HHmmss")), sizeof(setTime.dateTime));
int dow = (timeNow.date().dayOfWeek() % 7) + 1; // Convert Qt's week day number to EKM's.
setTime.dateTime.weekday[0] = (dow / 256) + 48;
setTime.dateTime.weekday[1] = (dow % 256) + 48;
uint16_t crc = computeEkmCrc((uint8_t *)(setTime.SOH) + 1, sizeof(SetTimeMsgDef) - 3);
setTime.crc[0] = (crc >> 8) & 0x7f;
setTime.crc[1] = crc & 0x7f;
qInfo("setTime after CRC: %s", qUtf8Printable(QByteArray((const char *)&setTime, sizeof(setTime)).toHex()));
if (ValidateCRC((const uint8_t *)(&setTime.SOH) + 1, sizeof(SetTimeMsgDef) - 3))
qDebug("We think the CRC is OK.");
else
qDebug("We think the CRC is NOT OK.");
if (WriteSerialMsg(serialPort, (const char *)setTime.SOH, sizeof(SetTimeMsgDef)))
{
qDebug() << "Wrote set time message ok.";
if (ReadResponse(serialPort, ackResponse, sizeof(ackResponse)))
{
if (ackResponse[0] == ResponseAck[0])
{
qDebug() << "Got ACK from setting time";
retVal = true;
}
else
qDebug() << "ack response wasn't ACK.";
}
else
qDebug() << "Could not get ack response.";
}
else
qDebug() << "Failed to write set time message.";
}
else
qDebug() << "ack response wasn't ACK.";
}
else
qDebug() << "Could not get ack response.";
}
else
qDebug() << "Failed to write password message.";
}
WriteSerialMsg(serialPort, (const char *)CloseString, sizeof(CloseString));
qDebug() << "Return" << retVal;
return retVal;
}
/*!
* \brief GetMeterV4Data -- Get a data response from a v.4 Omnimeter.
*
* Send request for data, read response. Does not close meter since
* there may be another request for data soon.
*
* \param serialPort
* \param meterId Full 12 character serial number of meter.
* \param requestType Either x30 for "A" data or x31 for "B" data.
* \param response Pointer to response data.
* \return true if successful, false otherwise.
*/
bool GetMeterV4Data(QSerialPort *serialPort
, const QString meterId
, const uint8_t requestType
, ResponseV4Generic *response)
{
qInfo() << "Begin";
static const int maxTries = 10;
memcpy(RequestMsgV4.meterId, qPrintable(meterId), sizeof(RequestMsgV4.meterId));
RequestMsgV4.reqType[1] = requestType; // \x30 to get A data
qInfo("RequestMsgV4 is: %s", qUtf8Printable(QByteArray((const char *)RequestMsgV4.fixedBegin, sizeof(RequestMsgV4)).toHex()));
int tryCount = 0;
while (tryCount++ < maxTries)
{
if (serialPort->clear())
qDebug("Cleared serial port data.");
else
qWarning("Clearing serial port data had error: %s", qUtf8Printable(serialPort->errorString()));
serialPort->clearError();
qDebug() << "Started trying to get data.";
WriteSerialMsg(serialPort, (const char *)RequestMsgV4.fixedBegin, sizeof(RequestMsgV4));
if (ReadResponse(serialPort, (qint8 *)response, sizeof(*response)))
break;
}
if (tryCount >= maxTries)
{
qDebug("Could not get response %x from V4 meter %s"
, requestType
, qUtf8Printable(meterId));
qDebug() << "Return false";
return false;
}
qDebug() << "Return true";
return true;
}
/*!
* \brief GetMeterV3Data -- Get a data response from a v.3 Omnimeter.
* \param serialPort
* \param meterId Full 12 character serial number of meter.
* \param response
* \return true if successful, false otherwise.
*/
bool GetMeterV3Data(QSerialPort *serialPort, const QString meterId, ResponseV3Data *response)
{
qInfo() << "Begin";
static const int maxTries = 10;
memcpy(RequestMsgV3.meterId, qPrintable(meterId), sizeof(RequestMsgV3.meterId));
qInfo("RequestMsgV3 is: %s", qUtf8Printable(QByteArray((const char *)RequestMsgV3.fixedBegin, sizeof(RequestMsgV3)).toHex()));
int tryCount = 0;
while (tryCount++ < maxTries)
{
serialPort->clearError();
qDebug() << "Started trying to get data.";
WriteSerialMsg(serialPort, (const char *)RequestMsgV3.fixedBegin, sizeof(RequestMsgV3));
if (ReadResponse(serialPort, (qint8 *)response, sizeof(*response)))
break;
}
if (tryCount >= maxTries)
{
qDebug() << "Could not get response from V3 meter" << meterId;
qDebug() << "Return false";
return false;
}
WriteSerialMsg(serialPort, (const char *)CloseString, sizeof(CloseString));
qDebug() << "Return true";
return true;
}
/*!
* \brief ValidateCRC
* \param msg Pointer to beginning of part of message on which to compute CRC.
* \param numBytes Number of bytes to include in CRC.
* \return true if CRC in message matches computed CRC.
*/
bool ValidateCRC(const uint8_t *msg, int numBytes)
{
// Compute CRC from msg for numBytes; then compare to the next two bytes.
qDebug() << "Begin";
uint16_t crc = computeEkmCrc(msg, numBytes);
qDebug("Computed CRC is %04x", crc);
uint16_t msgCrc = msg[numBytes] * 256 + msg[numBytes + 1];
qDebug("Message CRC is %04x", msgCrc);
qDebug() << "Return" << (crc == msgCrc);
return (crc == msgCrc);
}
/*!
* \brief main -- The whole tamale.
* \param argc
* \param argv
* \return Program success indicator.
*/
int main(int argc, char *argv[])
{
/*
* DON'T ShowDiagnosticsSince OR DumpDebugInfo OR FlushDiagnostics
* DIAGNOSTICS TILL AFTER OPTIONS PROCESSED.
*
* THIS MAY AVOID TRYING TO WRITE DIAGNOSTICS TO MAIN DATABASE SINCE
* IT MAY NOT HAVE A DebugInfo TABLE.
*/
QCoreApplication a(argc, argv);
StartTime = QDateTime::currentDateTime();
// Silent till options processed.
qInstallMessageHandler(saveMessageOutput);
qInfo() << "Begin";
DetermineCommitTag();
/*
* Local variable declarations
*/
QSerialPort *serialPort = NULL;
int interval = 0, repeatCount = 0, aToBRatio = 10, aDataCount = 0;
/*
* Process command line options
*/
QCommandLineParser parser;
parser.setApplicationDescription("\nReadEKM\n"
" Program to read EKM power meters and store in database.");
parser.addHelpOption();
parser.addPositionalArgument("meterId", "Meter serial numbers to read.", "[meter id] ...");
QCommandLineOption serialDeviceOption(QStringList() << "s" << "serial-name"
, "The name of the serial device. [cu.usbserial-AH034Y93]"
, "Name"
, "cu.usbserial-AH034Y93");
QCommandLineOption intervalOption(QStringList() << "i" << "interval", "Time between successive reads of meters listed.\n"
"If zero read only once.", "minutes"
, "1");
QCommandLineOption repeatCountOption(QStringList() << "r" << "repeat-count", "Number of times to read the meters listed.\n"
"If zero read forever.", "count"
, "0");
QCommandLineOption aToBRatioOption(QStringList() << "n" << "a-to-b-ratio", "Number of times to read A data from V4 meters before reading B data.\n"
"If zero don't read B data.", "count"
, "15");
QCommandLineOption databaseOption(QStringList() << "d" << "database", "Database id string.", "URL"
, ""); // for example "QMYSQL://user:xxxxxx@host/schema"
QCommandLineOption envVarNameOption(QStringList() << "e" << "DbEnvName", "Name of environment variable containing database id string.", "Name"
, "EKMdatabase");
QCommandLineOption debugDatabaseOption(QStringList() << "B" << "debug-database", "Database id string for debug info.", "URL"
, "");
QCommandLineOption showDiagnosticsOption(QStringList() << "D" << "show-diagnostics"
, "Print saved diagnostics to terminal at runtime.");
QCommandLineOption immediateDiagnosticsOption(QStringList() << "S" << "immediate-diagnostics"
, "Print diagnostic info to terminal immediately.");
QCommandLineOption dontWriteDatabaseOption(QStringList() << "W" << "dont-write"
, "If specified, don't actually write to the database.");
parser.addOption(serialDeviceOption);
parser.addOption(intervalOption);
parser.addOption(repeatCountOption);
parser.addOption(aToBRatioOption);
parser.addOption(databaseOption);
parser.addOption(envVarNameOption);
parser.addOption(debugDatabaseOption);
parser.addOption(showDiagnosticsOption);
parser.addOption(immediateDiagnosticsOption);
parser.addOption(dontWriteDatabaseOption);
parser.process(a);
ShowDiagnostics = parser.isSet(showDiagnosticsOption);
ImmediateDiagnostics = parser.isSet(immediateDiagnosticsOption);
if (ImmediateDiagnostics)
qInstallMessageHandler(terminalMessageOutput);
else
qInstallMessageHandler(saveMessageOutput);
DontActuallyWriteDatabase = parser.isSet(dontWriteDatabaseOption);
qDebug() << "DontActuallyWriteDatabase: " << DontActuallyWriteDatabase;
QString serialDevice = parser.value(serialDeviceOption);
qDebug() << "Using serialDevice" << serialDevice;
QString databaseConnString = parser.value(databaseOption);
if (databaseConnString.isEmpty())
{
databaseConnString = QProcessEnvironment::systemEnvironment().value(parser.value(envVarNameOption));
if (databaseConnString.isEmpty())
{
qCritical("No database connection string found. Return -3");
return -3;
}
}
qDebug() << "Using database connection string: " << databaseConnString;
addConnectionFromString(databaseConnString);
databaseConnString = parser.value(debugDatabaseOption);
if (!databaseConnString.isEmpty())
{
qDebug() << "Using database connection string for debug info: " << databaseConnString;
addConnectionFromString(databaseConnString, true); // Optional last arg flags to create debug connection.
}
interval = parser.value(intervalOption).toInt();
qInfo("Interval between successive meter reads is %d minutes.", interval);
repeatCount = parser.value(repeatCountOption).toInt();
if (repeatCount <= 0)
repeatCount = INT32_MAX;
if (interval == 0)
qInfo("Read meters just once.");
else
qInfo("Number of times to read meters is %d.", repeatCount);
aToBRatio = parser.value(aToBRatioOption).toInt();
const QStringList args = parser.positionalArguments();
if (args.isEmpty())
{
qCritical("You must supply at least one meter id on the command line.");
qDebug("Return 1");
return 1;
}
/* Command line options processed. */
FlushDiagnostics();
DumpDebugInfo();
{ // block to isolate temporary variables.
qint64 t = QDateTime::currentMSecsSinceEpoch() / 60000; // number of min since epoch
t = t / interval; // number of intervals since epoch
t = t % aToBRatio; // number of intervals till next B read.
aDataCount = t - 1; // set count
qInfo("interval = %d; aToBRatio = %d; aDataCount = %d", interval, aToBRatio, aDataCount);
}
if (!ConnectSerial(serialDevice, &serialPort))
{