├── img ├── led0.png ├── led1.png ├── new.png ├── open.png ├── save.png ├── wave.png ├── zoom.png ├── delete.png ├── icon32.ico ├── icon32.png ├── icon40.png ├── reload.png ├── configure.png ├── trash-empty.png └── application-exit.png ├── plcrecorder.rc ├── .gitignore ├── csvhandler.h ├── specwidgets.h ├── plcrecorder.qrc ├── README.md ├── main.cpp ├── specwidgets.cpp ├── plc_p.h ├── settingsdialog.h ├── libnodave ├── setport.h ├── openS7online.h ├── openSocket.h ├── openS7online.c ├── log2.h ├── openSocket.c ├── setport.c ├── setportw.c └── openSocketw.c ├── plcrecorder.pro ├── graphform.h ├── global.h ├── mainwindow.h ├── varmodel.h ├── settingsdialog.cpp ├── csvhandler.cpp ├── plc.h ├── varmodel.cpp ├── mainwindow.ui ├── graphform.ui ├── settingsdialog.ui ├── LICENSE ├── plc.cpp ├── mainwindow.cpp ├── global.cpp └── graphform.cpp /img/led0.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/led0.png -------------------------------------------------------------------------------- /img/led1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/led1.png -------------------------------------------------------------------------------- /img/new.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/new.png -------------------------------------------------------------------------------- /img/open.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/open.png -------------------------------------------------------------------------------- /img/save.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/save.png -------------------------------------------------------------------------------- /img/wave.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/wave.png -------------------------------------------------------------------------------- /img/zoom.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/zoom.png -------------------------------------------------------------------------------- /img/delete.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/delete.png -------------------------------------------------------------------------------- /img/icon32.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/icon32.ico -------------------------------------------------------------------------------- /img/icon32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/icon32.png -------------------------------------------------------------------------------- /img/icon40.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/icon40.png -------------------------------------------------------------------------------- /img/reload.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/reload.png -------------------------------------------------------------------------------- /plcrecorder.rc: -------------------------------------------------------------------------------- 1 | IDI_ICON1 ICON DISCARDABLE "img/icon32.ico" 2 | -------------------------------------------------------------------------------- /img/configure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/configure.png -------------------------------------------------------------------------------- /img/trash-empty.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/trash-empty.png -------------------------------------------------------------------------------- /img/application-exit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kernel1024/plcrecorder/HEAD/img/application-exit.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generic Qt and C++ patterns 2 | *.moc 3 | Makefile* 4 | *.so.* 5 | *.so 6 | *.so.debug 7 | *.o 8 | .cd.rc 9 | *.swp 10 | core 11 | moc_*.cpp 12 | *.Debug 13 | *.Release 14 | *.pdb 15 | *.idb 16 | *.ib_pdb_index 17 | ui_*.h 18 | qrc_*.cpp 19 | Debug/ 20 | Release/ 21 | *.log 22 | *.autosave 23 | .*.stash 24 | moc_* 25 | 26 | # QtCreator project files 27 | *.pro.user 28 | ======= 29 | *.pro.user* 30 | *~ 31 | 32 | # Project specific 33 | plcrecorder 34 | -------------------------------------------------------------------------------- /csvhandler.h: -------------------------------------------------------------------------------- 1 | #ifndef CSVHANDLER_H 2 | #define CSVHANDLER_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include "plc.h" 8 | 9 | class CCSVHandler : public QObject 10 | { 11 | Q_OBJECT 12 | private: 13 | QTextStream csvLog; 14 | QTime csvPrevTime; 15 | bool csvHasHeader; 16 | 17 | public: 18 | explicit CCSVHandler(QObject *parent = 0); 19 | 20 | void addData(const CWPList& wp, const QDateTime& stm); 21 | 22 | signals: 23 | void appendLog(const QString& message); 24 | void errorMessage(const QString& message); 25 | void recordingStopped(); 26 | 27 | public slots: 28 | bool rotateFile(); 29 | void timerSync(); 30 | void stopClose(); 31 | }; 32 | 33 | #endif // CSVHANDLER_H 34 | -------------------------------------------------------------------------------- /specwidgets.h: -------------------------------------------------------------------------------- 1 | #ifndef SPECWIDGETS_H 2 | #define SPECWIDGETS_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | class CTableView : public QTableView 10 | { 11 | Q_OBJECT 12 | public: 13 | explicit CTableView(QWidget *parent = 0); 14 | 15 | signals: 16 | void ctxMenuRequested(const QPoint& pos); 17 | 18 | private slots: 19 | void selectAll(); 20 | 21 | protected: 22 | void mouseDoubleClickEvent(QMouseEvent *event); 23 | 24 | }; 25 | 26 | class CSleep : public QThread 27 | { 28 | public: 29 | static void sleep(unsigned long secs); 30 | static void msleep(unsigned long msecs); 31 | static void usleep(unsigned long usecs); 32 | }; 33 | #endif // SPECWIDGETS_H 34 | -------------------------------------------------------------------------------- /plcrecorder.qrc: -------------------------------------------------------------------------------- 1 | 2 | 3 | img/led0.png 4 | img/led1.png 5 | img/icon32.png 6 | img/delete.png 7 | img/new.png 8 | img/open.png 9 | img/reload.png 10 | img/save.png 11 | img/icon40.png 12 | img/application-exit.png 13 | img/configure.png 14 | img/trash-empty.png 15 | img/zoom.png 16 | img/wave.png 17 | 18 | 19 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # plcrecorder 2 | 3 | PLC Recorder is a recording and debugging tool for Siemens S7 300/400 PLCs. 4 | 5 | Includes partial libnodave snapshot. libnodave (c) Thomas Hergenhahn (thomas.hergenhahn@web.de) 2002-2005, under license GPLv2. 6 | 7 | # BIG FAT WARNING 8 | 9 | This is beta code and information. You assume all responsibility for its use. 10 | 11 | **DANGER:** DON'T connect to a PLC unless you are certain it is safe to do so!!! It is assumed that you are experienced in PLC programming/troubleshooting and that you know EXACTLY what you are doing. PLCs are used to control industrial processes, motors, steam valves, hydraulic presses, etc. 12 | 13 | **You are ABSOLUTELY RESPONSIBLE for ensuring that NO-ONE is in danger of being injured or killed because you affected the operation of a running PLC.** 14 | 15 | Also expect that buggy drivers could write data even when you expect that they will read only!!! 16 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "mainwindow.h" 3 | #include "graphform.h" 4 | #include "plc.h" 5 | 6 | #ifdef LINUX 7 | #include 8 | #endif 9 | 10 | static MainWindow* mw = NULL; 11 | 12 | #ifdef LINUX 13 | void sig_handler(int) { 14 | if (mw!=NULL) 15 | QMetaObject::invokeMethod(mw,"sysSIGPIPE"); 16 | } 17 | #endif 18 | 19 | int main(int argc, char *argv[]) 20 | { 21 | #ifdef LINUX 22 | struct sigaction pipe; 23 | pipe.sa_handler = sig_handler; 24 | sigemptyset(&pipe.sa_mask); 25 | pipe.sa_flags = 0; 26 | pipe.sa_flags |= SA_RESTART; 27 | sigaction(SIGPIPE, &pipe, NULL); 28 | #endif 29 | qRegisterMetaType("CWP"); 30 | qRegisterMetaType("CWPList"); 31 | qRegisterMetaType("CPairing"); 32 | qRegisterMetaType("CGraphForm::CursorType"); 33 | 34 | initGraphFormData(); 35 | 36 | QApplication a(argc, argv); 37 | MainWindow w; 38 | mw = &w; 39 | w.show(); 40 | 41 | return a.exec(); 42 | } 43 | -------------------------------------------------------------------------------- /specwidgets.cpp: -------------------------------------------------------------------------------- 1 | #include "specwidgets.h" 2 | #include 3 | #include 4 | #include 5 | 6 | CTableView::CTableView(QWidget *parent) : 7 | QTableView(parent) 8 | { 9 | } 10 | 11 | void CTableView::selectAll() 12 | { 13 | if (qobject_cast(sender())!=NULL) { 14 | QPoint p = mapFromGlobal(QCursor::pos()); 15 | p.setX(p.x()-verticalHeader()->width()); 16 | p.setY(p.y()-horizontalHeader()->height()); 17 | if (!p.isNull()) 18 | emit ctxMenuRequested(p); 19 | } else 20 | QTableView::selectAll(); 21 | } 22 | 23 | void CTableView::mouseDoubleClickEvent(QMouseEvent *event) 24 | { 25 | if (!indexAt(event->pos()).isValid()) 26 | emit ctxMenuRequested(event->pos()); 27 | else 28 | QTableView::mouseDoubleClickEvent(event); 29 | } 30 | 31 | 32 | void CSleep::sleep(unsigned long secs) 33 | { 34 | QThread::sleep(secs); 35 | } 36 | 37 | void CSleep::msleep(unsigned long msecs) 38 | { 39 | QThread::msleep(msecs); 40 | } 41 | 42 | void CSleep::usleep(unsigned long usecs) 43 | { 44 | QThread::usleep(usecs); 45 | } 46 | -------------------------------------------------------------------------------- /plc_p.h: -------------------------------------------------------------------------------- 1 | #ifndef PLC_P_H 2 | #define PLC_P_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include "global.h" 9 | #include "plc.h" 10 | 11 | extern "C" { 12 | #include "libnodave/nodave.h" 13 | #include "libnodave/openSocket.h" 14 | } 15 | 16 | class CPLCPrivate : public QObject 17 | { 18 | Q_OBJECT 19 | 20 | public: 21 | CPLC* qptr; 22 | 23 | QString ip; 24 | int rack; 25 | int slot; 26 | int netTimeout; 27 | _daveOSserialType fds; 28 | CPLC::PlcState state; 29 | 30 | daveInterface* daveIntf; 31 | daveConnection* daveConn; 32 | 33 | QMutex clockInterlock; 34 | int skippedTicks; 35 | int recErrorsCount; 36 | QTimer* mainClock; 37 | QTimer* resClock; 38 | QTimer* infClock; 39 | int updateInterval; 40 | QTime updateClock; 41 | 42 | int tmMaxRecErrorCount; 43 | int tmMaxConnectRetryCount; 44 | int tmWaitReconnect; 45 | 46 | CWPList watchpoints; 47 | 48 | QList pairings; 49 | 50 | CPLCPrivate(CPLC* q) : QObject(q), qptr(q) { } 51 | virtual ~CPLCPrivate() { } 52 | 53 | bool rearrangeWatchpoints(); 54 | }; 55 | 56 | #endif // PLC_P_H 57 | -------------------------------------------------------------------------------- /settingsdialog.h: -------------------------------------------------------------------------------- 1 | #ifndef OUTPUTDIALOG_H 2 | #define OUTPUTDIALOG_H 3 | 4 | #include 5 | #include 6 | 7 | namespace Ui { 8 | class CSettingsDialog; 9 | } 10 | 11 | class CSettingsDialog : public QDialog 12 | { 13 | Q_OBJECT 14 | 15 | public: 16 | explicit CSettingsDialog(QWidget *parent = NULL); 17 | ~CSettingsDialog(); 18 | 19 | void setParams(const QString& outputDir, const QString& fileTemplate, int tcpTimeout, 20 | int maxRecErrorCount, int maxConnectRetryCount, int waitReconnect, int totalRetryCount, 21 | bool suppressMsgBox, bool restoreCSV, int plotVerticalSize, bool plotShowScatter, bool plotAntialiasing); 22 | QString getOutputDir() const; 23 | QString getFileTemplate() const; 24 | int getTCPTimeout(); 25 | int getMaxRecErrorCount(); 26 | int getMaxConnectRetryCount(); 27 | int getWaitReconnect(); 28 | int getTotalRetryCount(); 29 | bool getSuppressMsgBox(); 30 | bool getRestoreCSV(); 31 | int getPlotVerticalSize(); 32 | bool getPlotShowScatter(); 33 | bool getPlotAntialiasing(); 34 | 35 | 36 | private: 37 | Ui::CSettingsDialog *ui; 38 | 39 | private slots: 40 | void selectDirDlg(); 41 | }; 42 | 43 | #endif // OUTPUTDIALOG_H 44 | -------------------------------------------------------------------------------- /libnodave/setport.h: -------------------------------------------------------------------------------- 1 | /* 2 | Part of Libnodave, a free communication libray for Siemens S7 300/400. 3 | 4 | (C) Thomas Hergenhahn (thomas.hergenhahn@web.de) 2001. 5 | 6 | Libnodave is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 2, or (at your option) 9 | any later version. 10 | 11 | Libnodave is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Libnodave; see the file COPYING. If not, write to 18 | the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. 19 | */ 20 | 21 | #ifndef setport__ 22 | #define setport__ 23 | 24 | #ifdef __cplusplus 25 | extern "C" { 26 | #endif 27 | 28 | #ifdef BCCWIN 29 | 30 | #ifdef DOEXPORT 31 | #define EXPORTSPEC __declspec (dllexport) 32 | #else 33 | #define EXPORTSPEC __declspec (dllimport) 34 | #endif 35 | 36 | EXPORTSPEC HANDLE __stdcall setPort(char * name, char* baud,char parity); 37 | 38 | EXPORTSPEC int __stdcall closePort(HANDLE port); 39 | #endif 40 | 41 | #ifdef LINUX 42 | int setPort(char * name, char* baud, char parity); 43 | 44 | int closePort(int port); 45 | #endif 46 | 47 | #ifdef __cplusplus 48 | } 49 | #endif 50 | 51 | #endif // setport__ 52 | /* 53 | 01/08/07 Put __cplusplus directive as where suggested by Keith Harrison. 54 | */ 55 | -------------------------------------------------------------------------------- /plcrecorder.pro: -------------------------------------------------------------------------------- 1 | #------------------------------------------------- 2 | # 3 | # Project created by QtCreator 2012-06-21T17:05:11 4 | # 5 | #------------------------------------------------- 6 | 7 | QT += core gui printsupport 8 | 9 | TARGET = plcrecorder 10 | TEMPLATE = app 11 | 12 | greaterThan(QT_MAJOR_VERSION, 4) { 13 | QT += widgets 14 | DEFINES += HAVE_QT5 15 | } 16 | 17 | DEFINES += DAVE_LITTLE_ENDIAN 18 | 19 | 20 | SOURCES += libnodave/nodave.c \ 21 | main.cpp\ 22 | mainwindow.cpp \ 23 | plc.cpp \ 24 | varmodel.cpp \ 25 | global.cpp \ 26 | specwidgets.cpp \ 27 | qcustomplot-source/qcustomplot.cpp \ 28 | graphform.cpp \ 29 | settingsdialog.cpp \ 30 | csvhandler.cpp 31 | 32 | HEADERS += mainwindow.h \ 33 | libnodave/log2.h \ 34 | libnodave/nodave.h \ 35 | plc.h \ 36 | varmodel.h \ 37 | global.h \ 38 | specwidgets.h \ 39 | qcustomplot-source/qcustomplot.h \ 40 | graphform.h \ 41 | plc_p.h \ 42 | settingsdialog.h \ 43 | csvhandler.h 44 | 45 | FORMS += mainwindow.ui \ 46 | graphform.ui \ 47 | settingsdialog.ui 48 | 49 | RESOURCES += \ 50 | plcrecorder.qrc 51 | 52 | CONFIG += warn_on \ 53 | link_pkgconfig \ 54 | 55 | unix { 56 | DEFINES += LINUX 57 | SOURCES += libnodave/setport.c \ 58 | libnodave/openSocket.c 59 | HEADERS += libnodave/openSocket.h \ 60 | libnodave/setport.h \ 61 | } 62 | 63 | win32 { 64 | DEFINES += BCCWIN DOEXPORT 65 | LIBS += -lws2_32 66 | SOURCES += libnodave/openSocketw.c \ 67 | libnodave/setportw.c 68 | HEADERS += libnodave/openS7online.h 69 | } 70 | 71 | RC_FILE = plcrecorder.rc 72 | -------------------------------------------------------------------------------- /libnodave/openS7online.h: -------------------------------------------------------------------------------- 1 | /* 2 | Part of Libnodave, a free communication libray for Siemens S7 300/400. 3 | 4 | (C) Thomas Hergenhahn (thomas.hergenhahn@web.de) 2002, 2003.2004 5 | 6 | Libnodave is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 2, or (at your option) 9 | any later version. 10 | 11 | Libnodave is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Libnodave; see the file COPYING. If not, write to 18 | the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. 19 | */ 20 | #ifndef __openS7online 21 | #define __openS7online 22 | 23 | 24 | #ifdef __cplusplus 25 | extern "C" { // All here is C, *** NOT *** C++ 26 | #endif 27 | 28 | #include "nodave.h" 29 | 30 | #ifdef BCCWIN 31 | #define WIN32_LEAN_AND_MEAN 32 | #include 33 | #define DECL2 __stdcall 34 | #define us unsigned short 35 | #ifdef DOEXPORT 36 | #define EXPORTSPEC __declspec (dllexport) 37 | #else 38 | #define EXPORTSPEC __declspec (dllimport) 39 | #endif 40 | //EXPORTSPEC HANDLE DECL2 openS7online(const char * accessPoint); 41 | EXPORTSPEC HANDLE DECL2 openS7online(const char * accessPoint, HWND handle); 42 | EXPORTSPEC HANDLE DECL2 closeS7online(int h); 43 | #endif 44 | 45 | #ifdef __cplusplus 46 | } 47 | #endif 48 | 49 | #endif 50 | 51 | /* 52 | 01/09/07 Used Axel Kinting's version. 53 | */ 54 | -------------------------------------------------------------------------------- /graphform.h: -------------------------------------------------------------------------------- 1 | #ifndef GRAPHFORM_H 2 | #define GRAPHFORM_H 3 | 4 | #include 5 | #include "qcustomplot-source/qcustomplot.h" 6 | #include "global.h" 7 | #include "plc.h" 8 | 9 | namespace Ui { 10 | class CGraphForm; 11 | } 12 | 13 | class CGraphForm : public QWidget 14 | { 15 | Q_OBJECT 16 | 17 | public: 18 | enum CursorType { 19 | ctRunning = 1, 20 | ctLeft = 2, 21 | ctRight = 3 22 | }; 23 | 24 | explicit CGraphForm(QWidget *parent = 0); 25 | ~CGraphForm(); 26 | 27 | void addData(const CWPList &wp, const QDateTime &time, bool noReplot = false); 28 | 29 | private: 30 | Ui::CGraphForm *ui; 31 | CWPList watchpoints; 32 | QCPItemStraightLine *runningCursor, *leftCursor, *rightCursor; 33 | bool moveSplitterOnce; 34 | int getScreenWidth(); 35 | void createCursorSignal(CGraphForm::CursorType cursor, double timestamp); 36 | QCPRange getTotalKeyRange(); 37 | void updateScrollBarRange(); 38 | void setupGraphs(const CWPList &wp); 39 | void clearDataEx(bool clearOnlyCursors); 40 | 41 | protected: 42 | virtual void closeEvent(QCloseEvent * event); 43 | virtual void showEvent(QShowEvent * event); 44 | 45 | signals: 46 | void logMessage(const QString& msg); 47 | void stopGraph(); 48 | void cursorMoved(CGraphForm::CursorType cursor, const QDateTime &time, const CWPList &wp); 49 | 50 | public slots: 51 | void clearData(); 52 | void zoomAll(); 53 | void loadCSV(); 54 | void exportGraph(); 55 | 56 | private slots: 57 | void plotRangeChanged(const QCPRange &newRange); 58 | void plotMouseMove(QMouseEvent *event); 59 | void scrollBarMoved(int value); 60 | void plotContextMenu(const QPoint &pos); 61 | 62 | }; 63 | 64 | Q_DECLARE_METATYPE(CGraphForm::CursorType) 65 | 66 | void initGraphFormData(); 67 | 68 | #endif // GRAPHFORM_H 69 | -------------------------------------------------------------------------------- /libnodave/openSocket.h: -------------------------------------------------------------------------------- 1 | /* 2 | Part of Libnodave, a free communication libray for Siemens S7 300/400. 3 | 4 | (C) Thomas Hergenhahn (thomas.hergenhahn@web.de) 2002, 2003.2004 5 | 6 | Libnodave is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 2, or (at your option) 9 | any later version. 10 | 11 | Libnodave is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with Libnodave; see the file COPYING. If not, write to 18 | the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. 19 | */ 20 | 21 | 22 | #ifndef opensocket__ 23 | #define opensocket__ 24 | 25 | #ifdef __cplusplus 26 | extern "C" { 27 | #endif 28 | 29 | #ifdef BCCWIN 30 | #ifdef DOEXPORT 31 | #define EXPORTSPEC __declspec (dllexport) 32 | #else 33 | #define EXPORTSPEC __declspec (dllimport) 34 | #endif 35 | EXPORTSPEC HANDLE __stdcall openSocket(const int port, const char * peer); 36 | 37 | EXPORTSPEC int __stdcall closeSocket(HANDLE h); 38 | 39 | #endif 40 | 41 | #ifdef LINUX 42 | #define EXPORTSPEC 43 | int openSocket(const int port, const char * peer); 44 | 45 | int closeSocket(int h); 46 | 47 | #endif 48 | 49 | #ifdef __cplusplus 50 | } 51 | #endif 52 | 53 | 54 | #endif //opensocket__ 55 | 56 | 57 | /* 58 | Changes: 59 | 07/12/03 moved openSocket to it's own file, because it can be reused in other TCP clients 60 | 04/07/04 ported C++ version to C 61 | 12/17/04 additonal defines for WIN32 62 | 04/09/05 removed CYGWIN defines. As there were no more differences against LINUX, it should 63 | work with LINUX defines. 64 | Version 0.8.4.5 65 | 07/10/09 Added closeSocket() 66 | 67 | */ 68 | -------------------------------------------------------------------------------- /libnodave/openS7online.c: -------------------------------------------------------------------------------- 1 | 2 | #include "openS7online.h" 3 | #include "log2.h" 4 | #ifdef BCCWIN 5 | #define WIN32_LEAN_AND_MEAN 6 | #include 7 | #include 8 | #endif 9 | 10 | /* 11 | Access S7onlinx.dll and load pointers to the functions. 12 | We load them using GetProcAddress on their names because: 13 | 1. We have no .lib file for them. 14 | 2. We don't want to link with a particular version. 15 | 3. Libnodave shall remain useable without Siemens .dlls. So it shall not try to access them 16 | unless the user chooses the daveProtoS7online. 17 | */ 18 | 19 | extern int daveDebug; 20 | 21 | typedef int (DECL2 * _setHWnd) (int, HWND); 22 | 23 | EXPORTSPEC HANDLE DECL2 openS7online(const char * accessPoint, HWND handle) { 24 | HMODULE hmod; 25 | int h,en; 26 | _setHWnd SetSinecHWnd; 27 | 28 | hmod=LoadLibrary("S7onlinx.dll"); 29 | if (daveDebug & daveDebugOpen) 30 | LOG2("LoadLibrary(S7onlinx.dll) returned %p)\n",hmod); 31 | 32 | SCP_open=GetProcAddress(hmod,"SCP_open"); 33 | if (daveDebug & daveDebugOpen) 34 | LOG2("GetProcAddress returned %p)\n",SCP_open); 35 | 36 | SCP_close=GetProcAddress(hmod,"SCP_close"); 37 | if (daveDebug & daveDebugOpen) 38 | LOG2("GetProcAddress returned %p)\n",SCP_close); 39 | 40 | SCP_get_errno=GetProcAddress(hmod,"SCP_get_errno"); 41 | if (daveDebug & daveDebugOpen) 42 | LOG2("GetProcAddress returned %p)\n",SCP_get_errno); 43 | 44 | SCP_send=GetProcAddress(hmod,"SCP_send"); 45 | if (daveDebug & daveDebugOpen) 46 | LOG2("GetProcAddress returned %p)\n",SCP_send); 47 | 48 | SCP_receive=GetProcAddress(hmod,"SCP_receive"); 49 | if (daveDebug & daveDebugOpen) 50 | LOG2("GetProcAddress returned %p)\n",SCP_receive); 51 | 52 | SetSinecHWnd=GetProcAddress(hmod,"SetSinecHWnd"); 53 | if (daveDebug & daveDebugOpen) 54 | LOG2("GetProcAddress returned %p)\n",SetSinecHWnd); 55 | 56 | en=SCP_get_errno(); 57 | h=SCP_open(accessPoint); 58 | en=SCP_get_errno(); 59 | LOG3("handle: %d error:%d\n", h, en); 60 | SetSinecHWnd(h, handle); 61 | return h; 62 | }; 63 | 64 | EXPORTSPEC HANDLE DECL2 closeS7online(int h) { 65 | SCP_close(h); 66 | } 67 | 68 | /* 69 | 01/09/07 Used Axel Kinting's version. 70 | */ 71 | -------------------------------------------------------------------------------- /global.h: -------------------------------------------------------------------------------- 1 | #ifndef CGLOBAL_H 2 | #define CGLOBAL_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include "plc.h" 8 | 9 | class CGlobal : public QObject 10 | { 11 | Q_OBJECT 12 | public: 13 | // global settings --------------------------------- 14 | QString outputCSVDir, outputFileTemplate; 15 | int tmTCPTimeout, tmMaxRecErrorCount, tmMaxConnectRetryCount; 16 | int tmWaitReconnect, tmTotalRetryCount; 17 | bool suppressMsgBox, restoreCSV; 18 | int plotVerticalSize; 19 | bool plotShowScatter; 20 | bool plotAntialiasing; 21 | 22 | QString savedAuxDir; 23 | 24 | 25 | // ------------------------------------------------- 26 | 27 | explicit CGlobal(QObject *parent = 0); 28 | 29 | QString plcGetAddrName(const CWP& aWp); 30 | QString plcGetTypeName(const CWP& aWp); 31 | QStringList plcAvailableTypeNames(); 32 | bool plcSetTypeForName(const QString& tname, CWP &wp); 33 | bool plcParseAddr(const QString& addr, CWP &wp); 34 | QString plcFormatActualValue(const CWP& wp); 35 | bool plcIsPlottableType(const CWP& aWp); 36 | 37 | void loadSettings(); 38 | void saveSettings(); 39 | }; 40 | 41 | extern CGlobal* gSet; 42 | 43 | QString getOpenFileNameD ( QWidget * parent = NULL, const QString & caption = QString(), 44 | const QString & dir = QString(), const QString & filter = QString(), 45 | QString * selectedFilter = NULL); 46 | 47 | QStringList getOpenFileNamesD ( QWidget * parent = NULL, const QString & caption = QString(), 48 | const QString & dir = QString(), const QString & filter = QString(), 49 | QString * selectedFilter = NULL); 50 | 51 | QString getSaveFileNameD (QWidget * parent = NULL, const QString & caption = QString(), 52 | const QString & dir = QString(), const QString & filter = QString(), 53 | QString * selectedFilter = NULL, QString preselectFileName = QString()); 54 | 55 | QString getExistingDirectoryD ( QWidget * parent = NULL, const QString & caption = QString(), 56 | const QString & dir = QString(), 57 | QFileDialog::Options options = QFileDialog::ShowDirsOnly); 58 | #endif // CGLOBAL_H 59 | -------------------------------------------------------------------------------- /mainwindow.h: -------------------------------------------------------------------------------- 1 | #ifndef MAINWINDOW_H 2 | #define MAINWINDOW_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include "plc.h" 9 | #include "graphform.h" 10 | #include "csvhandler.h" 11 | 12 | class CVarModel; 13 | class CVarDelegate; 14 | 15 | namespace Ui { 16 | class MainWindow; 17 | } 18 | 19 | class MainWindow : public QMainWindow 20 | { 21 | Q_OBJECT 22 | 23 | public: 24 | CPLC* plc; 25 | CGraphForm* graph; 26 | CCSVHandler* csvHandler; 27 | 28 | explicit MainWindow(QWidget *parent = NULL); 29 | ~MainWindow(); 30 | 31 | private: 32 | Ui::MainWindow *ui; 33 | CVarModel *vtmodel; 34 | CVarDelegate *vtdelegate; 35 | QCheckBox* cbVat; 36 | QCheckBox* cbRec; 37 | QCheckBox* cbPlot; 38 | QThread* plcThread; 39 | QLabel* lblState; 40 | QLabel* lblScanTime; 41 | int agcRestartCounter; 42 | bool autoOnLogging; 43 | bool savedCSVActive; 44 | bool aggregatedStartActive; 45 | 46 | void loadConnectionFromFile(const QString& fname); 47 | 48 | protected: 49 | virtual void closeEvent(QCloseEvent * event); 50 | 51 | signals: 52 | void csvSync(); 53 | 54 | public slots: 55 | void plcConnected(); 56 | void plcDisconnected(); 57 | void plcStarted(); 58 | void plcStopped(); 59 | void plcStartFailed(); 60 | void plcErrorMsg(const QString &msg, bool critical); 61 | void plcVariablesUpdatedConsistent(const CWPList& wp, const QDateTime& stm); 62 | 63 | void connectPLC(); 64 | void aboutMsg(); 65 | void aboutQtMsg(); 66 | void variablesCtxMenu(QPoint pos); 67 | void settingsDlg(); 68 | void loadConnection(); 69 | void saveConnection(); 70 | 71 | void plotControl(); 72 | void plotStop(); 73 | 74 | void vatControl(); 75 | 76 | void csvControl(); 77 | 78 | void ctlAggregatedStart(); 79 | void ctlAggregatedStartForce(); 80 | void ctlStop(); 81 | 82 | void sysSIGPIPE(); 83 | 84 | void appendLog(const QString& msg); 85 | 86 | void syncTimer(); 87 | void csvError(const QString& msg); 88 | void recordingStopped(); 89 | 90 | void ctxNew(); 91 | void ctxRemove(); 92 | void ctxRemoveAll(); 93 | 94 | signals: 95 | void plcSetAddress(const QString& Ip, int Rack, int Slot, int Timeout); 96 | void plcSetRetryParams(int maxErrorCnt, int maxRetryCnt, int waitReconnect); 97 | void plcConnect(); 98 | void plcStart(); 99 | void plcDisconnect(); 100 | void plcCorrectToThread(); 101 | 102 | }; 103 | 104 | #endif // MAINWINDOW_H 105 | -------------------------------------------------------------------------------- /varmodel.h: -------------------------------------------------------------------------------- 1 | #ifndef VARMODEL_H 2 | #define VARMODEL_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include "plc.h" 9 | 10 | class CVarModel; 11 | class MainWindow; 12 | 13 | class CVarDelegate : public QItemDelegate 14 | { 15 | Q_OBJECT 16 | public: 17 | explicit CVarDelegate(QObject *parent = 0); 18 | QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, 19 | const QModelIndex &index) const; 20 | 21 | void setEditorData(QWidget *editor, const QModelIndex &index) const; 22 | void setModelData(QWidget *editor, QAbstractItemModel *model, 23 | const QModelIndex &index) const; 24 | 25 | void updateEditorGeometry(QWidget *editor, 26 | const QStyleOptionViewItem &option, 27 | const QModelIndex &index) const; 28 | void setVarModel(CVarModel* aVmodel); 29 | 30 | void setEditEnabled(bool state); 31 | bool isEditEnabled(); 32 | private: 33 | CVarModel* vmodel; 34 | bool editEnabled; 35 | 36 | }; 37 | 38 | class CVarModel : public QAbstractItemModel 39 | { 40 | Q_OBJECT 41 | friend class CVarDelegate; 42 | public: 43 | MainWindow* mainWnd; 44 | explicit CVarModel(QObject *parent, CPLC* aPlc); 45 | ~CVarModel(); 46 | 47 | Qt::ItemFlags flags(const QModelIndex & index) const; 48 | QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const; 49 | QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; 50 | int rowCount( const QModelIndex & parent = QModelIndex()) const; 51 | int columnCount(const QModelIndex &parent) const; 52 | QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const; 53 | QModelIndex parent(const QModelIndex &child) const; 54 | bool insertRows(int row, int count, const QModelIndex &parent = QModelIndex()); 55 | bool removeRows(int row, int count, const QModelIndex &parent = QModelIndex()); 56 | void removeMultipleRows(QList rows); 57 | 58 | CWP getCWP(int idx) const; 59 | int getCWPCount() const; 60 | CWPList getCWPList() const; 61 | 62 | void saveWPList(QDataStream& out); 63 | void loadWPList(QDataStream &in); 64 | 65 | void loadActualsFromPLC(const CWPList& wpl); 66 | 67 | void setEditEnabled(bool state); 68 | bool isEditEnabled(); 69 | 70 | private: 71 | CWPList wp; 72 | CPLC *plc; 73 | QPixmap led0, led1; 74 | bool editEnabled; 75 | 76 | signals: 77 | void syncPLCtoModel(const CWPList& aWatchpoints); 78 | 79 | public slots: 80 | void syncPLC(); 81 | 82 | }; 83 | 84 | #endif // VARMODEL_H 85 | -------------------------------------------------------------------------------- /libnodave/log2.h: -------------------------------------------------------------------------------- 1 | #ifndef __log 2 | #define __log 3 | 4 | #ifdef LINUX 5 | #define HAVE_PRINTF 6 | #define logout stdout 7 | #endif 8 | 9 | #ifdef BCCWIN 10 | #define HAVE_PRINTF 11 | #define logout stdout 12 | #endif 13 | 14 | #ifdef KEILC51 15 | 16 | #endif 17 | 18 | #ifdef DOS 19 | #define HAVE_PRINTF 20 | #define logout stdout 21 | #endif 22 | 23 | #ifdef AVR 24 | #define NO_PRINT_CODE 25 | #endif 26 | 27 | 28 | #ifdef HAVE_PRINTF 29 | 30 | #define FLUSH fflush(logout) 31 | 32 | //#define LINENUMBERS 33 | 34 | 35 | #ifdef LINENUMBERS 36 | #define LOG1(a) fprintf(logout,"%20s() %4d :"a,__FUNCTION__,__LINE__) 37 | #define LOG2(a,b) fprintf(logout,"%20s() %4d :"a,__FUNCTION__,__LINE__,b) 38 | #define LOG3(a,b,c) fprintf(logout,"%20s() %4d :"a,__FUNCTION__,__LINE__,b,c) 39 | #define LOG4(a,b,c,d) fprintf(logout,"%20s() %4d :"a,__FUNCTION__,__LINE__,b,c,d) 40 | #define LOG5(a,b,c,d,e) fprintf(logout,"%20s() %4d :"a,__FUNCTION__,__LINE__,b,c,d,e) 41 | #define LOG6(a,b,c,d,e,f) fprintf(logout,"%20s() %4d :"a,__FUNCTION__,__LINE__,b,c,d,e,f) 42 | #define LOG7(a,b,c,d,e,f,g) fprintf(logout,"%20s() %4d :"a,__FUNCTION__,__LINE__,b,c,d,e,f,g) 43 | 44 | /* 45 | #define LOG1(a) fprintf(logout,"%14s %20s() %4d :"a,__FILE__,__FUNCTION__,__LINE__) 46 | #define LOG2(a,b) fprintf(logout,"%14s %20s() %4d :"a,__FILE__,__FUNCTION__,__LINE__,b) 47 | #define LOG3(a,b,c) fprintf(logout,"%14s %20s() %4d :"a,__FILE__,__FUNCTION__,__LINE__,b,c) 48 | #define LOG4(a,b,c,d) fprintf(logout,"%14s %20s() %4d :"a,__FILE__,__FUNCTION__,__LINE__,b,c,d) 49 | #define LOG5(a,b,c,d,e) fprintf(logout,"%14s %20s() %4d :"a,__FILE__,__FUNCTION__,__LINE__,b,c,d,e) 50 | #define LOG6(a,b,c,d,e,f) fprintf(logout,"%14s %20s() %4d :"a,__FILE__,__FUNCTION__,__LINE__,b,c,d,e,f) 51 | #define LOG7(a,b,c,d,e,f,g) fprintf(logout,"%14s %20s() %4d :"a,__FILE__,__FUNCTION__,__LINE__,b,c,d,e,f,g) 52 | */ 53 | #else 54 | #define LOG1(x) fprintf(logout,x) 55 | #define LOG2(x,y) fprintf(logout,x,y) 56 | #define LOG3(a,b,c) fprintf(logout,a,b,c) 57 | #define LOG4(a,b,c,d) fprintf(logout,a,b,c,d) 58 | #define LOG5(a,b,c,d,e) fprintf(logout,a,b,c,d,e) 59 | #define LOG6(a,b,c,d,e,f) fprintf(logout,a,b,c,d,e,f) 60 | #define LOG7(a,b,c,d,e,f,g) fprintf(logout,a,b,c,d,e,f,g) 61 | 62 | #endif 63 | 64 | #define LOG_1(a) fprintf(logout,a) 65 | #define LOG_2(a,b) fprintf(logout,a,b) 66 | #endif /* HAVE_PRINTF */ 67 | 68 | #ifdef NO_PRINT_CODE 69 | #define LOG1(x) 70 | #define LOG2(x,y) 71 | #define LOG3(a,b,c) 72 | #define LOG4(a,b,c,d) 73 | #define LOG5(a,b,c,d,e) 74 | #define LOG6(a,b,c,d,e,f) 75 | #define LOG7(a,b,c,d,e,f,g) 76 | #define FLUSH 77 | 78 | #define LOG_1(a) 79 | #define LOG_2(a,b) 80 | #endif /* NO_PRINT_CODE */ 81 | 82 | 83 | #endif /* __log */ 84 | -------------------------------------------------------------------------------- /settingsdialog.cpp: -------------------------------------------------------------------------------- 1 | #include "settingsdialog.h" 2 | #include "ui_settingsdialog.h" 3 | #include "global.h" 4 | 5 | 6 | CSettingsDialog::CSettingsDialog(QWidget *parent) : 7 | QDialog(parent), 8 | ui(new Ui::CSettingsDialog) 9 | { 10 | ui->setupUi(this); 11 | connect(ui->btnCSVDir,SIGNAL(clicked()),this,SLOT(selectDirDlg())); 12 | } 13 | 14 | CSettingsDialog::~CSettingsDialog() 15 | { 16 | delete ui; 17 | } 18 | 19 | int CSettingsDialog::getTCPTimeout() 20 | { 21 | return ui->spinNetTimeout->value()*1000; 22 | } 23 | 24 | int CSettingsDialog::getMaxRecErrorCount() 25 | { 26 | return ui->spinMaxRecErrorCount->value(); 27 | } 28 | 29 | int CSettingsDialog::getMaxConnectRetryCount() 30 | { 31 | return ui->spinConnectRetryCount->value(); 32 | } 33 | 34 | int CSettingsDialog::getWaitReconnect() 35 | { 36 | return ui->spinWaitBeforeRetryConnect->value(); 37 | } 38 | 39 | int CSettingsDialog::getTotalRetryCount() 40 | { 41 | return ui->spinTotalRetryCount->value(); 42 | } 43 | 44 | bool CSettingsDialog::getSuppressMsgBox() 45 | { 46 | return ui->checkSuppressMsgBoxes->isChecked(); 47 | } 48 | 49 | bool CSettingsDialog::getRestoreCSV() 50 | { 51 | return ui->checkRestoreCSV->isChecked(); 52 | } 53 | 54 | int CSettingsDialog::getPlotVerticalSize() 55 | { 56 | return ui->spinPlotVerticalSize->value(); 57 | } 58 | 59 | bool CSettingsDialog::getPlotShowScatter() 60 | { 61 | return ui->checkPlotShotScatter->isChecked(); 62 | } 63 | 64 | bool CSettingsDialog::getPlotAntialiasing() 65 | { 66 | return ui->checkAntialiasing->isChecked(); 67 | } 68 | 69 | 70 | void CSettingsDialog::setParams(const QString &outputDir, const QString &fileTemplate, int tcpTimeout, 71 | int maxRecErrorCount, int maxConnectRetryCount, int waitReconnect, 72 | int totalRetryCount, bool suppressMsgBox, bool restoreCSV, 73 | int plotVerticalSize, bool plotShowScatter, bool plotAntialiasing) 74 | { 75 | ui->editCSVDir->setText(outputDir); 76 | ui->editCSVTemplate->setText(fileTemplate); 77 | ui->spinNetTimeout->setValue(tcpTimeout/1000); 78 | ui->spinMaxRecErrorCount->setValue(maxRecErrorCount); 79 | ui->spinConnectRetryCount->setValue(maxConnectRetryCount); 80 | ui->spinWaitBeforeRetryConnect->setValue(waitReconnect); 81 | ui->spinTotalRetryCount->setValue(totalRetryCount); 82 | ui->checkSuppressMsgBoxes->setChecked(suppressMsgBox); 83 | ui->checkRestoreCSV->setChecked(restoreCSV); 84 | ui->spinPlotVerticalSize->setValue(plotVerticalSize); 85 | ui->checkPlotShotScatter->setChecked(plotShowScatter); 86 | ui->checkAntialiasing->setChecked(plotAntialiasing); 87 | } 88 | 89 | QString CSettingsDialog::getOutputDir() const 90 | { 91 | return ui->editCSVDir->text(); 92 | } 93 | 94 | QString CSettingsDialog::getFileTemplate() const 95 | { 96 | return ui->editCSVTemplate->text(); 97 | } 98 | 99 | void CSettingsDialog::selectDirDlg() 100 | { 101 | QString s = getExistingDirectoryD(this,trUtf8("Directory for CSV files"),ui->editCSVDir->text()); 102 | if (!s.isEmpty()) ui->editCSVDir->setText(s); 103 | } 104 | -------------------------------------------------------------------------------- /csvhandler.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "global.h" 3 | #include "csvhandler.h" 4 | 5 | CCSVHandler::CCSVHandler(QObject *parent) : QObject(parent) 6 | { 7 | csvPrevTime = QTime::currentTime(); 8 | csvHasHeader = false; 9 | } 10 | 11 | void CCSVHandler::addData(const CWPList &wp, const QDateTime &stm) 12 | { 13 | if (csvLog.device()!=NULL) { 14 | if (!csvHasHeader) { 15 | QString hdr = trUtf8("\"Time\"; "); 16 | for (int i=0;iplcGetAddrName(wp.at(i))); 20 | } 21 | hdr += QString("\"Scan dump\"; "); 22 | csvLog << hdr << QString("\r\n"); 23 | csvHasHeader = true; 24 | } 25 | QString s = QString("\"%1\"; ").arg(stm.toString("yyyy-MM-dd hh:mm:ss.zzz")); 26 | for (int i=0;iplcFormatActualValue(wp.at(i))); 28 | } 29 | 30 | // write wp dump for graph visualization 31 | QByteArray ba; 32 | QBuffer buf(&ba); 33 | buf.open(QIODevice::WriteOnly); 34 | QDataStream out(&buf); 35 | out << stm << wp; 36 | buf.close(); 37 | s += QString("%1; ").arg(QString::fromLatin1(qCompress(ba,1).toBase64())); 38 | 39 | csvLog << s << QString("\r\n"); 40 | } 41 | } 42 | 43 | bool CCSVHandler::rotateFile() 44 | { 45 | csvPrevTime = QTime::currentTime(); 46 | if (gSet->outputCSVDir.isEmpty()) { 47 | emit recordingStopped(); 48 | emit appendLog(trUtf8("CSV rotation failure. Directory for creating CSV files not configured.")); 49 | emit errorMessage(trUtf8("Directory for creating CSV files not configured.")); 50 | return false; 51 | } 52 | stopClose(); 53 | 54 | QDir d(gSet->outputCSVDir); 55 | QString fname = d.filePath(QString("%1_%2.csv"). 56 | arg(gSet->outputFileTemplate). 57 | arg(QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm-ss"))); 58 | QFile *f = new QFile(fname); 59 | if (!f->open(QIODevice::WriteOnly)) { 60 | emit recordingStopped(); 61 | emit appendLog(trUtf8("Unable to save CSV file %1.").arg(fname)); 62 | emit errorMessage(trUtf8("Unable to save file '%1'").arg(fname)); 63 | return false; 64 | } 65 | 66 | csvLog.setDevice(f); 67 | csvLog.setCodec("Windows-1251"); 68 | csvHasHeader = false; 69 | emit appendLog(trUtf8("CSV rotation was successful.")); 70 | return (csvLog.device()!=NULL); 71 | } 72 | 73 | void CCSVHandler::timerSync() 74 | { 75 | // reset cache 76 | if (csvLog.device()!=NULL) 77 | csvLog.flush(); 78 | 79 | // rotate csv at 0:00 80 | QTime curTime = QTime::currentTime(); 81 | bool needToRotate = (csvPrevTime.hour()>curTime.hour()); 82 | csvPrevTime = curTime; 83 | if (needToRotate) 84 | rotateFile(); 85 | } 86 | 87 | void CCSVHandler::stopClose() 88 | { 89 | if (csvLog.device()!=NULL) { 90 | csvLog.flush(); 91 | csvLog.device()->close(); 92 | csvLog.setDevice(NULL); 93 | emit appendLog(trUtf8("CSV recording stopped. File closed.")); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /plc.h: -------------------------------------------------------------------------------- 1 | #ifndef PLC_H 2 | #define PLC_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | class CVarModel; 13 | 14 | class CWP 15 | { 16 | friend QDataStream &operator<<(QDataStream &out, const CWP &obj); 17 | friend QDataStream &operator>>(QDataStream &in, CWP &obj); 18 | public: 19 | friend class CVarModel; 20 | enum VArea { 21 | NoArea = -1, 22 | Inputs = 0x81, 23 | Outputs = 0x82, 24 | Merkers = 0x83, 25 | DB = 0x84, 26 | IDB = 0x85, 27 | Counters = 28, 28 | Timers = 29 29 | }; 30 | enum VType { 31 | S7NoType, 32 | S7BOOL, 33 | S7BYTE, 34 | S7WORD, 35 | S7DWORD, 36 | S7INT, 37 | S7DINT, 38 | S7REAL, 39 | S7TIME, 40 | S7DATE, 41 | S7S5TIME, 42 | S7TIME_OF_DAY 43 | }; 44 | 45 | QString label; 46 | VArea varea; 47 | VType vtype; 48 | int vdb; 49 | int offset; 50 | int bitnum; 51 | QVariant data; 52 | bool dataSign; 53 | CWP(); 54 | CWP(QString aLabel, VArea aArea, VType aType, int aVdb, int aOffset, int aBitnum); 55 | CWP &operator=(const CWP& other); 56 | bool operator==(const CWP& ref) const; 57 | bool operator!=(const CWP& ref) const; 58 | int size(); 59 | private: 60 | QUuid uuid; 61 | }; 62 | 63 | typedef QList CWPList; 64 | 65 | class CPairing { 66 | public: 67 | QList items; 68 | CWP::VArea area; 69 | int db; 70 | CPairing(); 71 | CPairing(CWPList* Wlist, CWP::VArea Area, int aDB = -1); 72 | CPairing &operator=(const CPairing& other); 73 | int size(); 74 | int offset(); 75 | int sizeWith(CWP wp); 76 | int offsetWith(CWP wp); 77 | void calcSize(); 78 | private: 79 | int sz; 80 | int ofs; 81 | int cnt; 82 | CWPList* wlist; 83 | }; 84 | 85 | class CPLCPrivate; 86 | 87 | class CPLC : public QObject 88 | { 89 | Q_OBJECT 90 | public: 91 | enum PlcState { 92 | splcDisconnected, 93 | splcConnected, 94 | splcRecording 95 | }; 96 | explicit CPLC(QObject *parent = NULL); 97 | virtual ~CPLC(); 98 | 99 | private: 100 | CPLCPrivate* dptr; 101 | 102 | signals: 103 | void plcError(const QString& msg, bool critical); 104 | void plcConnectFailed(); 105 | void plcStartFailed(); 106 | void plcOnConnect(); 107 | void plcOnDisconnect(); 108 | void plcOnStart(); 109 | void plcOnStop(); 110 | void plcVariablesUpdated(); 111 | void plcVariablesUpdatedConsistent(const CWPList& aWatchpoints, const QDateTime& tm); 112 | void plcScanTime(const QString& msg); 113 | 114 | public slots: 115 | void plcSetAddress(const QString& Ip, int Rack, int Slot, int Timeout = 5000000); 116 | void plcSetAcqInterval(int Milliseconds); 117 | void plcSetWatchpoints(const CWPList& aWatchpoints); 118 | void plcSetRetryParams(int maxErrorCnt, int maxRetryCnt, int waitReconnect); 119 | void plcConnect(); 120 | void plcStart(); 121 | void plcStop(); 122 | void plcDisconnect(); 123 | void correctToThread(); 124 | 125 | private slots: 126 | void plcClock(); 127 | void resClock(); 128 | void infClock(); 129 | 130 | }; 131 | 132 | QString plcGetAddrName(const CWP& aWp); 133 | QString plcGetTypeName(CWP::VType vtype); 134 | 135 | #endif // PLC_H 136 | -------------------------------------------------------------------------------- /libnodave/openSocket.c: -------------------------------------------------------------------------------- 1 | /* 2 | Part of Libnodave, a free communication libray for Siemens S7 300/400. 3 | This version uses the IBHLink MPI-Ethernet-Adapter from IBH-Softec. 4 | www.ibh.de 5 | 6 | (C) Thomas Hergenhahn (thomas.hergenhahn@web.de) 2002, 2003. 7 | 8 | Libnodave is free software; you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation; either version 2, or (at your option) 11 | any later version. 12 | 13 | Libnodave is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with Libnodave; see the file COPYING. If not, write to 20 | the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. 21 | */ 22 | 23 | #ifndef __openSocket 24 | #define __openSocket 25 | 26 | #define ThisModule "openSocket: " 27 | 28 | #ifndef DONT_USE_GETHOSTBYNAME 29 | #include // for gethostbyname 30 | #endif 31 | 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | /* The following two lines seem to be necessary for FreeBSD and do no harm on Linux */ 39 | 40 | #include 41 | #include 42 | 43 | #include "log2.h" 44 | #include "nodave.h" 45 | #include "openSocket.h" 46 | 47 | extern int daveDebug; 48 | 49 | int openSocket(const int port, const char * peer) { 50 | int fd,res,opt; 51 | struct sockaddr_in addr; 52 | socklen_t addrlen; 53 | #ifndef DONT_USE_GETHOSTBYNAME 54 | struct hostent *he; 55 | #endif 56 | if (daveDebug & daveDebugOpen) { 57 | LOG1(ThisModule "enter OpenSocket"); 58 | FLUSH; 59 | } 60 | addr.sin_family = AF_INET; 61 | addr.sin_port =htons(port); 62 | // (((port) & 0xff) << 8) | (((port) & 0xff00) >> 8); 63 | #ifndef DONT_USE_GETHOSTBYNAME 64 | he = gethostbyname(peer); 65 | if (!he) return 0; // bug reported by Nick Hibma 66 | memcpy(&addr.sin_addr, he->h_addr_list[0], sizeof(addr.sin_addr)); 67 | #else 68 | inet_aton(peer, &addr.sin_addr); 69 | #endif 70 | 71 | fd = socket(AF_INET, SOCK_STREAM, 0); 72 | if (daveDebug & daveDebugOpen) { 73 | LOG2(ThisModule "OpenSocket: socket is %d\n", fd); 74 | } 75 | 76 | addrlen = sizeof(addr); 77 | if (connect(fd, (struct sockaddr *) & addr, addrlen)) { 78 | LOG2(ThisModule "Socket error: %s \n", strerror(errno)); 79 | close(fd); 80 | fd = 0; 81 | } else { 82 | if (daveDebug & daveDebugOpen) { 83 | LOG2(ThisModule "Connected to host: %s \n", peer); 84 | } 85 | /* 86 | Need this, so we can read a packet with a single read call and make 87 | read return if there are too few bytes. 88 | */ 89 | errno=0; 90 | // res=fcntl(fd, F_SETFL, O_NONBLOCK); 91 | // if (daveDebug & daveDebugOpen) 92 | // LOG3(ThisModule "Set mode to O_NONBLOCK %s %d\n", strerror(errno),res); 93 | /* 94 | I thought this might solve Marc's problem with the CP closing 95 | a connection after 30 seconds or so, but the Standrad keepalive time 96 | on my box is 7200 seconds. 97 | */ 98 | errno=0; 99 | opt=1; 100 | res=setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &opt, 4); 101 | if (daveDebug & daveDebugOpen) { 102 | LOG3(ThisModule "setsockopt %s %d\n", strerror(errno),res); 103 | } 104 | } 105 | FLUSH; 106 | return fd; 107 | } 108 | 109 | int closeSocket(int h) { 110 | return close(h); 111 | } 112 | 113 | 114 | #endif 115 | /* 116 | Changes: 117 | 07/12/2003 moved openSocket to it's own file, because it can be reused in other TCP clients 118 | 04/07/2004 ported C++ version to C 119 | 07/19/2004 removed unused vars. 120 | 03/06/2005 added Hugo Meiland's includes for FreeBSD. 121 | Version 0.8.4.5 122 | 07/10/09 Added closeSocket() 123 | 124 | */ 125 | -------------------------------------------------------------------------------- /libnodave/setport.c: -------------------------------------------------------------------------------- 1 | /* 2 | Part of Libnodave, a free communication libray for Siemens S7 300/400. 3 | 4 | (C) Thomas Hergenhahn (thomas.hergenhahn@web.de) 2001. 5 | 6 | Libnodave is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 2, or (at your option) 9 | any later version. 10 | 11 | Libnodave is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this; see the file COPYING. If not, write to 18 | the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. 19 | */ 20 | //#ifdef __cplusplus // some people try to compile this with C++ compilers... 21 | // Then the linker will expect mangled names, but libnodave dont have them. 22 | //extern "C" { 23 | //#endif 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include "setport.h" 33 | #define debug 0 34 | #define ThisModule "setPort : " 35 | 36 | int setPort(char * name, char* baud,char parity) 37 | { 38 | int fd,res; 39 | struct termios oldtio, newtio; 40 | // fd = open(name, O_RDWR | O_NOCTTY | O_NONBLOCK); 41 | fd = open(name, O_RDWR | O_NOCTTY); 42 | #if debug >3 43 | printf(ThisModule "%s = %d\n", name, fd); 44 | #endif 45 | // res=fcntl(fd, F_SETFL, 0x2000 /* FASYNC */ ); 46 | #if debug >3 47 | printf(ThisModule "fcntl: %s\n", strerror(errno)); 48 | #endif 49 | tcgetattr(fd, &oldtio); // save current settings 50 | #if debug >3 51 | printf(ThisModule "tcget...:%s\n", strerror(errno)); 52 | #endif 53 | // set new port settings for noncanonical input processing: 54 | if (0==strncmp(baud,"115200",6)) 55 | newtio.c_cflag = B115200; 56 | else if (0==strncmp(baud,"57600",5)) 57 | newtio.c_cflag = B57600; 58 | else if (0==strncmp(baud,"38400",5)) 59 | newtio.c_cflag = B38400; 60 | else if (0==strncmp(baud,"19200",5)) 61 | newtio.c_cflag = B19200; 62 | else if (0==strncmp(baud,"9600",4)) 63 | newtio.c_cflag = B9600; 64 | else if (0==strncmp(baud,"4800",4)) 65 | newtio.c_cflag = B4800; 66 | else if (0==strncmp(baud,"2400",4)) 67 | newtio.c_cflag = B2400; 68 | else if (0==strncmp(baud,"1200",4)) 69 | newtio.c_cflag = B1200; 70 | else if (0==strncmp(baud,"600",3)) 71 | newtio.c_cflag = B600; 72 | else if (0==strncmp(baud,"300",3)) 73 | newtio.c_cflag = B300; 74 | else 75 | printf(ThisModule "illegal Baudrate: %s\n", baud); 76 | parity=tolower(parity); 77 | if (parity == 'e') 78 | // newtio.c_cflag = newtio.c_cflag & (~PARODD | PARENB); // wrong !! 79 | // newtio.c_cflag = newtio.c_cflag & ~PARODD | PARENB; // gives compiler warning 80 | newtio.c_cflag = (newtio.c_cflag & ~PARODD) | PARENB; 81 | else if (parity == 'o') 82 | newtio.c_cflag = newtio.c_cflag | PARODD | PARENB; 83 | else if (parity == 'n') 84 | newtio.c_cflag = newtio.c_cflag & ~(PARODD | PARENB); 85 | else 86 | printf(ThisModule "illegal parity mode:%c\n", parity); 87 | 88 | newtio.c_cflag |= CS8; // should allways be eight bit 89 | 90 | newtio.c_cflag = newtio.c_cflag | CLOCAL | CREAD; 91 | newtio.c_iflag = 0; // {IGNPAR |} ICRNL; 92 | newtio.c_oflag = ONOCR; 93 | newtio.c_lflag = 0; //ICANON 94 | newtio.c_cc[VMIN] = 1; 95 | newtio.c_cc[VTIME] = 0; 96 | tcflush(fd, TCIFLUSH); 97 | #if debug >3 98 | printf(ThisModule "tcflush:%s\n", strerror(errno)); 99 | #endif 100 | tcsetattr(fd, TCSANOW, &newtio); 101 | #if debug >3 102 | printf(ThisModule "tcset...:%s\n", strerror(errno)); 103 | #endif 104 | return (fd); 105 | } 106 | 107 | /* 108 | Not acting on -1 is just a kludge for s7online. See comment in nodave.c before 109 | daveDisconnectAdapterS7online for detailed explanation. 110 | */ 111 | int closePort(int port){ 112 | int res=0; 113 | if (port!=-1) 114 | res=close(port); 115 | return res; 116 | } 117 | //#ifdef __cplusplus 118 | // } 119 | //#endif 120 | 121 | /* 122 | Changes: 123 | 124 | 02/12/2002 change output statements to printf, this gives less code size. 125 | 06/21/2002 * got rid of some warnings 126 | 10/04/2003 fixed an error with parity even 127 | Version 0.8.4.5 128 | 07/12/09 Changed flags in setport.c. Older version does not work with recent Linux 129 | kernels. 130 | 131 | */ 132 | -------------------------------------------------------------------------------- /libnodave/setportw.c: -------------------------------------------------------------------------------- 1 | /* 2 | Part of Libnodave, a free communication libray for Siemens S7 300/400. 3 | 4 | (C) Thomas Hergenhahn (thomas.hergenhahn@web.de) 2004. 5 | 6 | Libnodave is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; either version 2, or (at your option) 9 | any later version. 10 | 11 | Libnodave is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this; see the file COPYING. If not, write to 18 | the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. 19 | */ 20 | 21 | #define debug 0 22 | #define ThisModule "setPort : " 23 | #ifdef BCCWIN 24 | #define WIN32_LEAN_AND_MEAN 25 | #include 26 | #include 27 | #include "nodave.h" 28 | 29 | extern int daveDebug; 30 | 31 | 32 | /* 33 | You may wonder why a pair of identical file handles is set up and 34 | returned. It's for compatibility with an extended UNIX version of 35 | this code, which can use two separate pipes for reads and writes. 36 | */ 37 | 38 | __declspec(dllexport) 39 | HANDLE __stdcall setPort(char * devname, char * baud,char parity /*, HANDLE * wfd*/){ 40 | HANDLE hComm; 41 | DCB dcb; 42 | 43 | hComm = CreateFile( devname, 44 | GENERIC_READ | GENERIC_WRITE, 45 | 0, 46 | 0, 47 | OPEN_EXISTING, 48 | FILE_FLAG_WRITE_THROUGH, 49 | 0); 50 | if (daveDebug & daveDebugOpen) { 51 | printf("setPort %s\n",devname); 52 | printf("setPort %s\n",baud); 53 | printf("setPort %c\n",parity); 54 | } 55 | 56 | // printf("Handle to %s opened! %d\n",devname,hComm); 57 | GetCommState(hComm,&dcb); 58 | // printf("got Comm State. %d\n ",dcb.BaudRate); 59 | dcb.ByteSize = 8; 60 | dcb.fOutxCtsFlow=FALSE; 61 | dcb.fOutxDsrFlow=FALSE; 62 | // dcb.fDtrControl=DTR_CONTROL_DISABLE; // this seems to be the evil. Guess do not understand the meaning of this parameter 63 | 64 | dcb.fDtrControl=DTR_CONTROL_ENABLE; 65 | 66 | dcb.fDsrSensitivity=FALSE; 67 | dcb.fInX=FALSE; 68 | dcb.fOutX=FALSE; 69 | dcb.fNull=FALSE; 70 | dcb.fAbortOnError=FALSE; 71 | dcb.fBinary=TRUE; 72 | dcb.fParity=TRUE; 73 | dcb.fOutxCtsFlow=FALSE; 74 | dcb.fOutxDsrFlow=FALSE; 75 | // dcb.fRtsControl=FALSE; // this seems to be the evil. Guess do not understand the meaning of this parameter 76 | // dcb.fRtsControl=TRUE; 77 | // from winbase.h : //****** ADD 78 | //#define RTS_CONTROL_DISABLE 0 //****** ADD 79 | //#define RTS_CONTROL_ENABLE 1 //****** ADD 80 | //#define RTS_CONTROL_HANDSHAKE 2 //****** ADD 81 | dcb.fRtsControl=RTS_CONTROL_ENABLE; //****** ADD 82 | //#define RTS_CONTROL_TOGGLE 3 //****** ADD 83 | 84 | dcb.fTXContinueOnXoff=TRUE; 85 | // dcb.StopBits=2; ///that was 2 !!! //****** REMOVE 86 | // from winbase.h : //****** ADD 87 | //#define ONESTOPBIT 0 //****** ADD 88 | //#define ONE5STOPBITS 1 //****** ADD 89 | //#define TWOSTOPBITS 2 //****** ADD 90 | dcb.StopBits=TWOSTOPBITS; //****** ADD 91 | 92 | if (0==strncmp(baud,"115200",6)) 93 | dcb.BaudRate = CBR_115200; 94 | else if (0==strncmp(baud,"57600",5)) 95 | dcb.BaudRate = CBR_57600; 96 | else if (0==strncmp(baud,"38400",5)) 97 | dcb.BaudRate = CBR_38400; 98 | else if (0==strncmp(baud,"19200",5)) 99 | dcb.BaudRate = CBR_19200; 100 | else if (0==strncmp(baud,"9600",4)) 101 | dcb.BaudRate = CBR_9600; 102 | else if (0==strncmp(baud,"4800",4)) 103 | dcb.BaudRate = CBR_4800; 104 | else if (0==strncmp(baud,"2400",4)) 105 | dcb.BaudRate = CBR_2400; 106 | else if (0==strncmp(baud,"1200",4)) 107 | dcb.BaudRate = CBR_1200; 108 | else if (0==strncmp(baud,"600",3)) 109 | dcb.BaudRate = CBR_600; 110 | else if (0==strncmp(baud,"300",3)) 111 | dcb.BaudRate = CBR_300; 112 | else if (daveDebug & daveDebugPrintErrors) { 113 | printf(ThisModule "illegal Baudrate: %s\n", baud); 114 | } 115 | parity=tolower(parity); 116 | if (parity == 'e') 117 | dcb.Parity = 2; 118 | else if (parity == 'o') 119 | dcb.Parity = 1; 120 | else if (parity == 'n') 121 | dcb.Parity = 0; 122 | else if (daveDebug & daveDebugPrintErrors) { 123 | printf(ThisModule "illegal parity mode:%c\n", parity); 124 | } 125 | 126 | SetCommState(hComm,&dcb); 127 | // printf("got Comm State. %d\n ",dcb.BaudRate); 128 | 129 | //printf("Comm State set.\n"); 130 | // *wfd=hComm; 131 | return hComm; 132 | } 133 | 134 | __declspec(dllexport) 135 | int __stdcall closePort(HANDLE port){ 136 | int res=CloseHandle(port); 137 | return res; 138 | } 139 | #endif 140 | 141 | /* 142 | Changes: 143 | 144 | 12/17/2004 1st Version for Windows. 145 | 04/03/2005 Hopefully really fixed COM port setting. 146 | 05/08/2005 Removed printfs for quiet operation. 147 | -Version 0.8.5 148 | 05/19/2013 Applied changes from Keith 149 | */ 150 | -------------------------------------------------------------------------------- /libnodave/openSocketw.c: -------------------------------------------------------------------------------- 1 | /* 2 | Part of Libnodave, a free communication libray for Siemens S7 300/400. 3 | This version uses the IBHLink MPI-Ethernet-Adapter from IBH-Softec. 4 | www.ibh.de 5 | 6 | (C) Thomas Hergenhahn (thomas.hergenhahn@web.de) 2002, 2003. 7 | 8 | Libnodave is free software; you can redistribute it and/or modify 9 | it under the terms of the GNU General Public License as published by 10 | the Free Software Foundation; either version 2, or (at your option) 11 | any later version. 12 | 13 | Libnodave is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with Libnodave; see the file COPYING. If not, write to 20 | the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. 21 | */ 22 | 23 | #ifndef __openSocket 24 | #define __openSocket 25 | #define DONT_USE_GETHOSTBYNAME 26 | 27 | 28 | #define ThisModule "openSocketw.c: " 29 | #ifdef BCCWIN 30 | #define WIN32_LEAN_AND_MEAN 31 | #include 32 | #include 33 | #endif 34 | 35 | 36 | #ifndef DONT_USE_GETHOSTBYNAME 37 | //#include // for gethostbyname 38 | #endif 39 | 40 | #include 41 | #include 42 | #include 43 | //#include 44 | #include 45 | #include "log2.h" 46 | #include "nodave.h" 47 | 48 | #include 49 | 50 | 51 | extern int daveDebug; 52 | #define DONT_USE_GETHOSTBYNAME 53 | 54 | __declspec (dllexport) HANDLE __stdcall openSocket(const int port, const char * peer) { 55 | int res; 56 | SOCKET fd; 57 | struct sockaddr_in addr; 58 | int addrlen; 59 | WSADATA wsadata; 60 | res=WSAStartup(MAKEWORD(2,0), &wsadata); 61 | #ifndef DONT_USE_GETHOSTBYNAME 62 | struct hostent *he; 63 | #endif 64 | if (daveDebug & daveDebugOpen) { 65 | LOG1(ThisModule "enter OpenSocket\n"); 66 | FLUSH; 67 | } 68 | addr.sin_family = AF_INET; 69 | if (daveDebug & daveDebugOpen) { 70 | LOG1(ThisModule "1\n"); 71 | FLUSH; 72 | } 73 | 74 | addr.sin_port =htons(port); 75 | //addr.sin_port = (((port) & 0xff) << 8) | (((port) & 0xff00) >> 8); 76 | if (daveDebug & daveDebugOpen) { 77 | printf(ThisModule "2 %04X\n",addr.sin_port); 78 | FLUSH; 79 | } 80 | 81 | #ifndef DONT_USE_GETHOSTBYNAME 82 | if (daveDebug & daveDebugOpen) { 83 | LOG1(ThisModule "3\n"); 84 | FLUSH; 85 | } 86 | 87 | he = gethostbyname(peer); 88 | LOG1(ThisModule "4\n"); 89 | FLUSH; 90 | if (!he) return 0; // bug reported by Nick Hibma 91 | 92 | memcpy(&addr.sin_addr, he->h_addr_list[0], sizeof(addr.sin_addr)); 93 | if (daveDebug & daveDebugOpen) { 94 | LOG1(ThisModule "5\n"); 95 | FLUSH; 96 | } 97 | 98 | #else 99 | // inet_aton(peer, &addr.sin_addr); 100 | addr.sin_addr.s_addr=inet_addr(peer); 101 | if (daveDebug & daveDebugOpen) { 102 | printf(ThisModule "peer:%s=%d\n",peer,inet_addr(peer)); 103 | FLUSH; 104 | } 105 | 106 | 107 | if (daveDebug & daveDebugOpen) { 108 | LOG1(ThisModule "6\n"); 109 | FLUSH; 110 | } 111 | 112 | #endif 113 | 114 | fd = socket(AF_INET, SOCK_STREAM, AF_UNSPEC); 115 | if (daveDebug & daveDebugOpen) { 116 | LOG1(ThisModule "7\n"); 117 | FLUSH; 118 | } 119 | 120 | if (daveDebug & daveDebugOpen) { 121 | LOG2(ThisModule "socket is %d\n", fd); 122 | } 123 | if (daveDebug & daveDebugOpen) { 124 | LOG3(ThisModule "setsockopt %s %d\n", strerror(WSAGetLastError()),WSAGetLastError()); 125 | } 126 | 127 | addrlen = sizeof(addr); 128 | if (daveDebug & daveDebugOpen) { 129 | LOG1(ThisModule "8\n"); 130 | FLUSH; 131 | } 132 | // if (bind(fd, (struct sockaddr *) & addr, addrlen)) { 133 | // LOG2(ThisModule "bind Socket error: %s \n", strerror(errno)); 134 | // } 135 | if (connect(fd, (struct sockaddr *) & addr, addrlen)) { 136 | if (daveDebug & daveDebugOpen) { 137 | LOG2(ThisModule "connect Socket error: %s \n", strerror(errno)); 138 | } 139 | closesocket(fd); 140 | WSACleanup(); // patch from Klaus Albert 141 | fd = 0; 142 | } else { 143 | if (daveDebug & daveDebugOpen) { 144 | LOG2(ThisModule "Connected to host: %s \n", peer); 145 | } 146 | /* 147 | Need this, so we can read a packet with a single read call and make 148 | read return if there are too few bytes. 149 | */ 150 | errno=0; 151 | /* 152 | res=fcntl(fd, F_SETFL, O_NONBLOCK); 153 | if (daveDebug & daveDebugOpen) 154 | LOG3(ThisModule "Set mode to O_NONBLOCK %s %d\n", strerror(errno),res); 155 | */ 156 | /* 157 | I thought this might solve Marc's problem with the CP closing 158 | a connection after 30 seconds or so, but the Standrad keepalive time 159 | on my box is 7200 seconds. 160 | errno=0; 161 | opt=1; 162 | res=setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &opt, 4); 163 | LOG3(ThisModule "setsockopt %s %d\n", strerror(errno),res); 164 | */ 165 | } 166 | FLUSH; 167 | return (HANDLE) fd; 168 | } 169 | 170 | __declspec (dllexport) int __stdcall closeSocket(SOCKET h) { 171 | int res=closesocket(h); 172 | WSACleanup(); // patch from Klaus Albert 173 | return res; 174 | } 175 | 176 | #endif 177 | /* 178 | Changes: 179 | 07/12/2003 moved openSocket to it's own file, because it can be reused in other TCP clients 180 | 04/07/2004 ported C++ version to C 181 | 07/19/2004 removed unused vars. 182 | Version 0.8.4.5 183 | 07/10/09 Added closeSocket() 184 | Version 0.8.5 185 | 05/17/2013 Suppress message if debug mode is not set 186 | 05/20/2013 added WSACleanup(), patch from Klaus Albert 187 | 01/16/2013 fixed unreachable WSACleanup(). Grazie a Domenichini Luca. 188 | */ 189 | -------------------------------------------------------------------------------- /varmodel.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "varmodel.h" 5 | #include "plc.h" 6 | #include "global.h" 7 | #include "mainwindow.h" 8 | 9 | CVarDelegate::CVarDelegate(QObject *parent) : 10 | QItemDelegate(parent) 11 | { 12 | vmodel = NULL; 13 | editEnabled = true; 14 | } 15 | 16 | QWidget *CVarDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const 17 | { 18 | if (!index.isValid()) return NULL; 19 | if (!editEnabled) return NULL; 20 | if ((index.row()<0) || (index.row()>=index.model()->rowCount())) return NULL; 21 | if (index.column()==0) 22 | return new QLineEdit(parent); 23 | else if (index.column()==1) 24 | return new QLineEdit(parent); 25 | else if (index.column()==2) 26 | return new QComboBox(parent); 27 | else if (index.column()==3) 28 | return NULL; // read-only column 29 | return NULL; 30 | } 31 | 32 | void CVarDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const 33 | { 34 | if (vmodel==NULL) return; 35 | if (!index.isValid()) return; 36 | if ((index.row()<0) || (index.row()>=index.model()->rowCount())) return; 37 | 38 | CWP wp = vmodel->wp.at(index.row()); 39 | 40 | QLineEdit *le = qobject_cast(editor); 41 | QComboBox *cb = qobject_cast(editor); 42 | 43 | if ((index.column()==0) && (le!=NULL)) 44 | le->setText(wp.label); 45 | else if ((index.column()==1) && (le!=NULL)) 46 | le->setText(gSet->plcGetAddrName(wp)); 47 | else if ((index.column()==2) && (cb!=NULL)) { 48 | cb->clear(); 49 | QStringList sl = gSet->plcAvailableTypeNames(); 50 | cb->addItems(sl); 51 | cb->setCurrentIndex(sl.indexOf(gSet->plcGetTypeName(wp))); 52 | } 53 | } 54 | 55 | void CVarDelegate::setModelData(QWidget *editor, QAbstractItemModel *, const QModelIndex &index) const 56 | { 57 | if (vmodel==NULL) return; 58 | if (!index.isValid()) return; 59 | if ((index.row()<0) || (index.row()>=index.model()->rowCount())) return; 60 | 61 | QLineEdit *le = qobject_cast(editor); 62 | QComboBox *cb = qobject_cast(editor); 63 | 64 | if ((index.column()==0) && (le!=NULL)) { 65 | vmodel->wp[index.row()].label=le->text(); 66 | vmodel->syncPLC(); 67 | } else if ((index.column()==1) && (le!=NULL)) { 68 | if (!gSet->plcParseAddr(le->text(),vmodel->wp[index.row()])) 69 | QMessageBox::warning(vmodel->mainWnd,trUtf8("PLC recorder error"), 70 | trUtf8("Unable to parse address. Possible syntax error.")); 71 | vmodel->syncPLC(); 72 | } else if ((index.column()==2) && (cb!=NULL)) { 73 | if (!gSet->plcSetTypeForName(cb->currentText(),vmodel->wp[index.row()])) 74 | QMessageBox::warning(vmodel->mainWnd,trUtf8("PLC recorder error"), 75 | trUtf8("Unable to parse type. Possible syntax error.")); 76 | vmodel->syncPLC(); 77 | } 78 | } 79 | 80 | void CVarDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &) const 81 | { 82 | editor->setGeometry(option.rect); 83 | } 84 | 85 | void CVarDelegate::setVarModel(CVarModel *aVmodel) 86 | { 87 | vmodel = aVmodel; 88 | } 89 | 90 | void CVarDelegate::setEditEnabled(bool state) 91 | { 92 | editEnabled = state; 93 | } 94 | 95 | bool CVarDelegate::isEditEnabled() 96 | { 97 | return editEnabled; 98 | } 99 | 100 | CVarModel::CVarModel(QObject *parent, CPLC* aPlc) 101 | : QAbstractItemModel(parent) 102 | { 103 | wp.clear(); 104 | plc = aPlc; 105 | led0.load(":/led0"); 106 | led1.load(":/led1"); 107 | editEnabled = true; 108 | } 109 | 110 | CVarModel::~CVarModel() 111 | { 112 | wp.clear(); 113 | } 114 | 115 | Qt::ItemFlags CVarModel::flags(const QModelIndex &) const 116 | { 117 | return (Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable); 118 | } 119 | 120 | QVariant CVarModel::data(const QModelIndex &index, int role) const 121 | { 122 | // 4 columns: label | area(db)offset.bitnum | type | actual value 123 | 124 | if (!index.isValid()) return QVariant(); 125 | 126 | int row = index.row(); 127 | int column = index.column(); 128 | 129 | if ((row<0) || (row>=wp.count()) || (column<0) || (column>=4)) return QVariant(); 130 | if (role==Qt::DisplayRole) { 131 | if (column==0) return wp.at(row).label; 132 | else if (column==1) return gSet->plcGetAddrName(wp.at(row)); 133 | else if (column==2) return gSet->plcGetTypeName(wp.at(row)); 134 | else if (column==3) return gSet->plcFormatActualValue(wp.at(row)); 135 | else return QVariant(); 136 | } else if (role==Qt::DecorationRole) { 137 | CWP awp = wp.at(row); 138 | if ((column==3) && (awp.vtype==CWP::S7BOOL) && (awp.data.canConvert())) { 139 | if (awp.data.toBool()) 140 | return led1; 141 | else 142 | return led0; 143 | } else 144 | return QVariant(); 145 | } else 146 | return QVariant(); 147 | } 148 | 149 | QVariant CVarModel::headerData(int section, Qt::Orientation orientation, int role) const 150 | { 151 | if (role == Qt::DisplayRole) { 152 | if (orientation == Qt::Horizontal) { 153 | switch (section) { 154 | case 0: return trUtf8("Name"); 155 | case 1: return trUtf8("Address"); 156 | case 2: return trUtf8("Type"); 157 | case 3: return trUtf8("Value"); 158 | default: return QVariant(); 159 | } 160 | } else { 161 | return trUtf8("%1").arg(section+1); 162 | } 163 | } 164 | return QVariant(); 165 | } 166 | 167 | int CVarModel::rowCount(const QModelIndex &) const 168 | { 169 | return wp.count(); 170 | } 171 | 172 | int CVarModel::columnCount(const QModelIndex &) const 173 | { 174 | return 4; 175 | } 176 | 177 | QModelIndex CVarModel::index(int row, int column, const QModelIndex &) const 178 | { 179 | if ((row<0) || (row>=wp.count()) || (column<0) || (column>=4)) return QModelIndex(); 180 | return createIndex(row,column); 181 | } 182 | 183 | QModelIndex CVarModel::parent(const QModelIndex &) const 184 | { 185 | return QModelIndex(); 186 | } 187 | 188 | bool CVarModel::insertRows(int row, int count, const QModelIndex &parent) 189 | { 190 | if (!editEnabled) return false; 191 | if ((row<0) || (row>wp.count())) return false; 192 | beginInsertRows(parent,row,row+count-1); 193 | for (int i=0;i=wp.count())) return false; 203 | beginRemoveRows(parent,row,row+count-1); 204 | for (int i=0;i rows) 212 | { 213 | CWPList wl; 214 | for (int i=0;i=0) && (rows.at(i)(wp.count()); 240 | out << wp; 241 | } 242 | 243 | void CVarModel::loadWPList(QDataStream &in) 244 | { 245 | if (!editEnabled) return; 246 | removeRows(0,wp.count()); 247 | int cnt; 248 | in >> cnt; 249 | beginInsertRows(QModelIndex(),0,cnt-1); 250 | in >> wp; 251 | endInsertRows(); 252 | syncPLC(); 253 | } 254 | 255 | void CVarModel::loadActualsFromPLC(const CWPList &wpl) 256 | { 257 | if (wp.count()!=wpl.count()) { 258 | mainWnd->appendLog(trUtf8("Variables list is different. Unable to load VAT.")); 259 | return; 260 | } 261 | for (int i=0;i 2 | 3 | MainWindow 4 | 5 | 6 | 7 | 0 8 | 0 9 | 779 10 | 572 11 | 12 | 13 | 14 | PLC recorder 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | PLC connection via Ethernet 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | &IP address 32 | 33 | 34 | editIP 35 | 36 | 37 | 38 | 39 | 40 | 41 | 000.000.000.000 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | &Rack 53 | 54 | 55 | editRack 56 | 57 | 58 | 59 | 60 | 61 | 62 | 0 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | &Slot 74 | 75 | 76 | editSlot 77 | 78 | 79 | 80 | 81 | 82 | 83 | 3 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | PLC polling 96 | 97 | 98 | 99 | 100 | 101 | &Polling interval (ms) 102 | 103 | 104 | editAcqInterval 105 | 106 | 107 | 108 | 109 | 110 | 111 | 10 112 | 113 | 114 | 99999999 115 | 116 | 117 | 1 118 | 119 | 120 | 200 121 | 122 | 123 | 124 | 125 | 126 | 127 | Actual interval (ms) 128 | 129 | 130 | 131 | 132 | 133 | 134 | 0 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | Connect 147 | 148 | 149 | 150 | 151 | 152 | 153 | Disconnect 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | Qt::CustomContextMenu 165 | 166 | 167 | QAbstractItemView::ExtendedSelection 168 | 169 | 170 | 175 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | Clear 185 | 186 | 187 | 188 | 189 | 190 | 191 | Qt::Vertical 192 | 193 | 194 | 195 | 20 196 | 40 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 0 212 | 0 213 | 779 214 | 22 215 | 216 | 217 | 218 | 219 | &File 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | &Tools 231 | 232 | 233 | 234 | 235 | 236 | 237 | 238 | &Help 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | 250 | :/open:/open 251 | 252 | 253 | &Load connection... 254 | 255 | 256 | Load connection... 257 | 258 | 259 | Ctrl+O 260 | 261 | 262 | 263 | 264 | 265 | :/save:/save 266 | 267 | 268 | &Save connection... 269 | 270 | 271 | Save connection... 272 | 273 | 274 | Ctrl+S 275 | 276 | 277 | 278 | 279 | 280 | :/application-exit:/application-exit 281 | 282 | 283 | &Exit 284 | 285 | 286 | Ctrl+Q 287 | 288 | 289 | 290 | 291 | 292 | :/configure:/configure 293 | 294 | 295 | Sett&ings... 296 | 297 | 298 | Settings... 299 | 300 | 301 | 302 | 303 | 304 | :/reload:/reload 305 | 306 | 307 | &Force CSV rotation 308 | 309 | 310 | 311 | 312 | &About... 313 | 314 | 315 | 316 | 317 | About &Qt... 318 | 319 | 320 | 321 | 322 | 323 | :/wave:/wave 324 | 325 | 326 | &Show signal plot 327 | 328 | 329 | 330 | 331 | 332 | 333 | CTableView 334 | QTableView 335 |
specwidgets.h
336 |
337 |
338 | 339 | editIP 340 | editRack 341 | editSlot 342 | editAcqInterval 343 | btnConnect 344 | btnDisconnect 345 | tableVariables 346 | textLog 347 | 348 | 349 | 350 | 351 | 352 | 353 | actionQuit 354 | triggered() 355 | MainWindow 356 | close() 357 | 358 | 359 | -1 360 | -1 361 | 362 | 363 | 389 364 | 285 365 | 366 | 367 | 368 | 369 | btnClearLog 370 | clicked() 371 | textLog 372 | clear() 373 | 374 | 375 | 701 376 | 473 377 | 378 | 379 | 654 380 | 473 381 | 382 | 383 | 384 | 385 |
386 | -------------------------------------------------------------------------------- /graphform.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | CGraphForm 4 | 5 | 6 | 7 | 0 8 | 0 9 | 952 10 | 588 11 | 12 | 13 | 14 | Signal plot 15 | 16 | 17 | 18 | 19 | 20 | Qt::Vertical 21 | 22 | 23 | 24 | QFrame::StyledPanel 25 | 26 | 27 | QFrame::Raised 28 | 29 | 30 | 31 | 2 32 | 33 | 34 | 2 35 | 36 | 37 | 2 38 | 39 | 40 | 2 41 | 42 | 43 | 2 44 | 45 | 46 | 47 | 48 | true 49 | 50 | 51 | 52 | 53 | 0 54 | 0 55 | 926 56 | 168 57 | 58 | 59 | 60 | 61 | 2 62 | 63 | 64 | 0 65 | 66 | 67 | 0 68 | 69 | 70 | 0 71 | 72 | 73 | 0 74 | 75 | 76 | 77 | 78 | 79 | 0 80 | 0 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | Qt::Horizontal 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 2 102 | 103 | 104 | 105 | 106 | QFrame::StyledPanel 107 | 108 | 109 | QFrame::Raised 110 | 111 | 112 | 113 | 114 | 115 | Autoscroll 116 | 117 | 118 | 119 | 120 | 121 | 122 | Qt::Vertical 123 | 124 | 125 | 126 | 20 127 | 40 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | Load CSV 136 | 137 | 138 | 139 | 140 | 141 | 142 | Export 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 2 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 8 161 | 75 162 | true 163 | 164 | 165 | 166 | Current cursor 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 8 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 8 186 | 187 | 188 | 189 | QAbstractItemView::NoEditTriggers 190 | 191 | 192 | QAbstractItemView::NoSelection 193 | 194 | 195 | Qt::DotLine 196 | 197 | 198 | false 199 | 200 | 201 | false 202 | 203 | 204 | false 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 2 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 0 226 | 170 227 | 0 228 | 229 | 230 | 231 | 232 | 233 | 234 | 235 | 236 | 0 237 | 170 238 | 0 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 150 248 | 158 249 | 167 250 | 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 8 259 | 75 260 | true 261 | 262 | 263 | 264 | Left cursor (Ctrl) 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 8 273 | 274 | 275 | 276 | 277 | 278 | 279 | 280 | 281 | 282 | 283 | 8 284 | 285 | 286 | 287 | QAbstractItemView::NoEditTriggers 288 | 289 | 290 | QAbstractItemView::NoSelection 291 | 292 | 293 | Qt::DotLine 294 | 295 | 296 | false 297 | 298 | 299 | false 300 | 301 | 302 | false 303 | 304 | 305 | 306 | 307 | 308 | 309 | 310 | 311 | 2 312 | 313 | 314 | 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 170 324 | 0 325 | 0 326 | 327 | 328 | 329 | 330 | 331 | 332 | 333 | 334 | 170 335 | 0 336 | 0 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 150 346 | 158 347 | 167 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 8 357 | 75 358 | true 359 | 360 | 361 | 362 | Right cursor (Alt) 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 8 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 8 382 | 383 | 384 | 385 | QAbstractItemView::NoEditTriggers 386 | 387 | 388 | QAbstractItemView::NoSelection 389 | 390 | 391 | Qt::DotLine 392 | 393 | 394 | false 395 | 396 | 397 | false 398 | 399 | 400 | false 401 | 402 | 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | 411 | 412 | 413 | 414 | QCustomPlot 415 | QWidget 416 |
qcustomplot-source/qcustomplot.h
417 | 1 418 |
419 |
420 | 421 | 422 |
423 | -------------------------------------------------------------------------------- /settingsdialog.ui: -------------------------------------------------------------------------------- 1 | 2 | 3 | CSettingsDialog 4 | 5 | 6 | 7 | 0 8 | 0 9 | 840 10 | 368 11 | 12 | 13 | 14 | CSV saving parameters 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | CSV files saving 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | &Directory for CSV files 33 | 34 | 35 | editCSVDir 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | ... 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | &File name template 57 | 58 | 59 | editCSVTemplate 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | <html><head/><body><p>This settings only for interactive mode.</p><p>When starting with '-start' key from command promnt, this option is always activated.</p></body></html> 72 | 73 | 74 | Restore CSV recording after connection failure 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | Signal plot 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | Plot &vertical size 93 | 94 | 95 | spinPlotVerticalSize 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 0 104 | 0 105 | 106 | 107 | 108 | pixels 109 | 110 | 111 | 30 112 | 113 | 114 | 4000 115 | 116 | 117 | 100 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | Show scatter points 127 | 128 | 129 | 130 | 131 | 132 | 133 | Antialiasing 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | Qt::Vertical 144 | 145 | 146 | 147 | 20 148 | 40 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | Connection 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | &Max error count before connection stop 169 | 170 | 171 | true 172 | 173 | 174 | spinMaxRecErrorCount 175 | 176 | 177 | 178 | 179 | 180 | 181 | <html><head/><body><p>Maximum error count for daveReadBytes function. </p><p>This counter increases in each PLC cycle on connection failures, inaccessible or incorrect addresses of PLC memory areas, specified in variables.</p></body></html> 182 | 183 | 184 | 99999 185 | 186 | 187 | 188 | 189 | 190 | 191 | (0 - don't stop) 192 | 193 | 194 | 195 | 196 | 197 | 198 | TCP &connect retries when starting connection 199 | 200 | 201 | true 202 | 203 | 204 | spinConnectRetryCount 205 | 206 | 207 | 208 | 209 | 210 | 211 | <html><head/><body><p>TCP connection retries when starting online mode.</p><p>Do not set <span style=" font-weight:600;">this parameter</span> and <span style=" font-weight:600;">reconnection retries count</span> both equal to zero.</p></body></html> 212 | 213 | 214 | 99999 215 | 216 | 217 | 218 | 219 | 220 | 221 | (0 - infinite) 222 | 223 | 224 | 225 | 226 | 227 | 228 | Connection &timeout 229 | 230 | 231 | spinNetTimeout 232 | 233 | 234 | 235 | 236 | 237 | 238 | ms 239 | 240 | 241 | 1000 242 | 243 | 244 | 120000 245 | 246 | 247 | 248 | 249 | 250 | 251 | &Pause before connection retry 252 | 253 | 254 | true 255 | 256 | 257 | spinWaitBeforeRetryConnect 258 | 259 | 260 | 261 | 262 | 263 | 264 | sec 265 | 266 | 267 | 1 268 | 269 | 270 | 99999 271 | 272 | 273 | 274 | 275 | 276 | 277 | Failed connection &retry count 278 | 279 | 280 | true 281 | 282 | 283 | spinTotalRetryCount 284 | 285 | 286 | 287 | 288 | 289 | 290 | 291 | 292 | 293 | (0 - infinite) 294 | 295 | 296 | 297 | 298 | 299 | 300 | 301 | 302 | 303 | 304 | 305 | Interface 306 | 307 | 308 | 309 | 310 | 311 | <html><head/><body><p>Suppress message boxes with error and warning messages. All messages saving to log window.</p><p>Very useful and memory conservative on long background works when starting with '-start' key from command prompt.</p></body></html> 312 | 313 | 314 | Do not show interactive message boxes 315 | 316 | 317 | 318 | 319 | 320 | 321 | 322 | 323 | 324 | Qt::Vertical 325 | 326 | 327 | 328 | 20 329 | 40 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | Qt::Horizontal 344 | 345 | 346 | 347 | 40 348 | 20 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | OK 357 | 358 | 359 | true 360 | 361 | 362 | 363 | 364 | 365 | 366 | Cancel 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | editCSVDir 376 | btnCSVDir 377 | editCSVTemplate 378 | checkRestoreCSV 379 | spinPlotVerticalSize 380 | checkPlotShotScatter 381 | checkAntialiasing 382 | spinMaxRecErrorCount 383 | spinConnectRetryCount 384 | spinNetTimeout 385 | spinWaitBeforeRetryConnect 386 | spinTotalRetryCount 387 | checkSuppressMsgBoxes 388 | pushButton 389 | pushButton_2 390 | 391 | 392 | 393 | 394 | pushButton 395 | clicked() 396 | CSettingsDialog 397 | accept() 398 | 399 | 400 | 342 401 | 126 402 | 403 | 404 | 165 405 | 114 406 | 407 | 408 | 409 | 410 | pushButton_2 411 | clicked() 412 | CSettingsDialog 413 | reject() 414 | 415 | 416 | 419 417 | 130 418 | 419 | 420 | 77 421 | 106 422 | 423 | 424 | 425 | 426 | 427 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /plc.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include "specwidgets.h" 3 | #include "plc.h" 4 | #include "plc_p.h" 5 | 6 | extern "C" { 7 | #include "libnodave/nodave.h" 8 | #include "libnodave/openSocket.h" 9 | } 10 | 11 | #include 12 | 13 | CPLC::CPLC(QObject *parent) : 14 | QObject(parent), 15 | dptr(new CPLCPrivate(this)) 16 | { 17 | dptr->ip = QString(); 18 | dptr->rack = 0; 19 | dptr->slot = 0; 20 | dptr->fds.rfd = 0; 21 | dptr->fds.wfd = 0; 22 | dptr->skippedTicks = 0; 23 | dptr->recErrorsCount = 0; 24 | dptr->updateInterval = 0; 25 | dptr->state = splcDisconnected; 26 | dptr->netTimeout = 5000000; 27 | dptr->tmMaxRecErrorCount = 50; 28 | dptr->tmMaxConnectRetryCount = 1; 29 | dptr->tmWaitReconnect = 2; 30 | 31 | dptr->daveIntf = NULL; 32 | dptr->daveConn = NULL; 33 | 34 | dptr->watchpoints.clear(); 35 | 36 | dptr->mainClock = NULL; 37 | dptr->resClock = NULL; 38 | dptr->infClock = NULL; 39 | 40 | dptr->rearrangeWatchpoints(); 41 | } 42 | 43 | CPLC::~CPLC() 44 | { 45 | dptr->deleteLater(); 46 | } 47 | 48 | void CPLC::plcSetWatchpoints(const CWPList &aWatchpoints) 49 | { 50 | if (dptr->state!=splcDisconnected) { 51 | emit plcError(trUtf8("You can add variables only in disconnected state."),true); 52 | return; 53 | } 54 | 55 | dptr->watchpoints = aWatchpoints; 56 | 57 | if (!dptr->rearrangeWatchpoints()) { 58 | dptr->watchpoints.clear(); 59 | dptr->pairings.clear(); 60 | return; 61 | } 62 | } 63 | 64 | void CPLC::plcSetRetryParams(int maxErrorCnt, int maxRetryCnt, int waitReconnect) 65 | { 66 | dptr->tmMaxRecErrorCount = maxErrorCnt; 67 | dptr->tmMaxConnectRetryCount = maxRetryCnt; 68 | dptr->tmWaitReconnect = waitReconnect; 69 | } 70 | 71 | bool CPLCPrivate::rearrangeWatchpoints() 72 | { 73 | if (state != CPLC::splcDisconnected) { 74 | qDebug() << "ERROR: rearrange called after connection"; 75 | return false; 76 | } 77 | 78 | // clear pairing 79 | pairings.clear(); 80 | 81 | int maxPDU = 200; 82 | 83 | // pairing 84 | for (int i=0;istate!=splcDisconnected) { 118 | emit plcError(trUtf8("Unable to change connection settings in online mode. Disconnect and try again."),true); 119 | return; 120 | } 121 | dptr->ip = Ip; 122 | dptr->rack = Rack; 123 | dptr->slot = Slot; 124 | dptr->netTimeout = Timeout; 125 | } 126 | 127 | void CPLC::plcSetAcqInterval(int Milliseconds) 128 | { 129 | dptr->mainClock->setInterval(Milliseconds); 130 | } 131 | 132 | void CPLC::plcConnect() 133 | { 134 | if (dptr->state!=splcDisconnected) { 135 | emit plcError(trUtf8("Unable to connect - connection is still active. Disconnect and try again."),true); 136 | return; 137 | } 138 | 139 | if (!dptr->rearrangeWatchpoints()) { 140 | emit plcError(trUtf8("Unable to parse and rearrange variable list.\n" 141 | "Possible syntax error in one or more variable definitions.\n" 142 | "PLC connection was stopped."),true); 143 | return; 144 | } 145 | 146 | for (int i=0;itmMaxConnectRetryCount;i++) { 147 | dptr->fds.rfd = openSocket(102,dptr->ip.toLatin1().constData()); 148 | dptr->fds.wfd = dptr->fds.rfd; 149 | 150 | if (dptr->fds.rfd>0) { 151 | char ifname[63]; 152 | strcpy(ifname,"IF1"); 153 | dptr->daveIntf = daveNewInterface(dptr->fds,ifname,0,daveProtoISOTCP, daveSpeed187k); 154 | if (dptr->daveIntf != NULL) { 155 | daveSetTimeout(dptr->daveIntf,dptr->netTimeout); 156 | dptr->daveConn = daveNewConnection(dptr->daveIntf,0,dptr->rack,dptr->slot); 157 | if (dptr->daveConn != NULL) { 158 | int res = daveConnectPLC(dptr->daveConn); 159 | if (res == 0) { 160 | dptr->state = splcConnected; 161 | emit plcOnConnect(); 162 | return; 163 | } else { 164 | daveDisconnectPLC(dptr->daveConn); 165 | daveDisconnectAdapter(dptr->daveIntf); 166 | closeSocket(dptr->fds.rfd); 167 | dptr->daveConn = NULL; 168 | dptr->daveIntf = NULL; 169 | dptr->fds.rfd = 0; dptr->fds.wfd = 0; 170 | emit plcError(trUtf8("Unable to connect to PLC."),false); 171 | } 172 | } else { 173 | daveDisconnectAdapter(dptr->daveIntf); 174 | closeSocket(dptr->fds.rfd); 175 | dptr->daveConn = NULL; 176 | dptr->daveIntf = NULL; 177 | dptr->fds.rfd = 0; dptr->fds.wfd = 0; 178 | emit plcError(trUtf8("Unable to connect to specified IP."),false); 179 | } 180 | } else { 181 | closeSocket(dptr->fds.rfd); 182 | dptr->daveConn = NULL; 183 | dptr->daveIntf = NULL; 184 | dptr->fds.rfd = 0; dptr->fds.wfd = 0; 185 | emit plcError(trUtf8("Unable to create IF1 interface for PLC connection at specified IP."),false); 186 | } 187 | } else { 188 | dptr->daveConn = NULL; 189 | dptr->daveIntf = NULL; 190 | dptr->fds.rfd = 0; dptr->fds.wfd = 0; 191 | emit plcError(trUtf8("Unable to open socked to specified IP."),false); 192 | } 193 | CSleep::sleep(static_cast(dptr->tmWaitReconnect)); 194 | } 195 | emit plcConnectFailed(); 196 | } 197 | 198 | void CPLC::plcStart() 199 | { 200 | if (dptr->mainClock==NULL) return; 201 | if (dptr->state != splcConnected) { 202 | emit plcError(trUtf8("Unable to start PLC recording. libnodave is not ready."),false); 203 | return; 204 | } 205 | if (dptr->pairings.isEmpty()) { 206 | emit plcError(trUtf8("Variables is not parsed and prepared. Recording failure."),false); 207 | emit plcStartFailed(); 208 | return; 209 | } 210 | dptr->updateClock.start(); 211 | dptr->mainClock->start(); 212 | dptr->state = splcRecording; 213 | emit plcOnStart(); 214 | } 215 | 216 | void CPLC::plcStop() 217 | { 218 | if (dptr->state != splcRecording) { 219 | emit plcError(trUtf8("Unable to stop PLC recording, recording was not even started."),true); 220 | return; 221 | } 222 | dptr->state = splcConnected; 223 | dptr->mainClock->stop(); 224 | emit plcOnStop(); 225 | } 226 | 227 | void CPLC::plcDisconnect() 228 | { 229 | if (dptr->state == splcDisconnected) { 230 | emit plcError(trUtf8("Not connected to PLC."),true); 231 | return; 232 | } 233 | 234 | if (dptr->state == splcRecording) 235 | plcStop(); 236 | 237 | if (dptr->state != splcConnected) { 238 | emit plcError(trUtf8("Unable to stop PLC recording."),true); 239 | return; 240 | } 241 | 242 | daveDisconnectPLC(dptr->daveConn); 243 | daveDisconnectAdapter(dptr->daveIntf); 244 | closeSocket(dptr->fds.rfd); 245 | dptr->daveConn = NULL; 246 | dptr->daveIntf = NULL; 247 | dptr->fds.rfd = 0; dptr->fds.wfd = 0; 248 | 249 | dptr->state = splcDisconnected; 250 | 251 | emit plcOnDisconnect(); 252 | } 253 | 254 | void CPLC::correctToThread() 255 | { 256 | dptr->mainClock = new QTimer(this); 257 | dptr->resClock = new QTimer(this); 258 | dptr->infClock = new QTimer(this); 259 | 260 | dptr->mainClock->setInterval(100); 261 | dptr->resClock->setInterval(120*60*1000); // 2 min for reset accumulated record errors 262 | dptr->infClock->setInterval(2000); 263 | 264 | connect(dptr->mainClock,SIGNAL(timeout()),this,SLOT(plcClock())); 265 | connect(dptr->resClock,SIGNAL(timeout()),this,SLOT(resClock())); 266 | connect(dptr->infClock,SIGNAL(timeout()),this,SLOT(infClock())); 267 | 268 | dptr->resClock->start(); 269 | dptr->infClock->start(); 270 | } 271 | 272 | void CPLC::plcClock() 273 | { 274 | if (dptr->state!=splcRecording) return; 275 | if (dptr->mainClock==NULL) return; 276 | if (!dptr->clockInterlock.tryLock()) { 277 | if (dptr->mainClock->interval()>0) 278 | dptr->skippedTicks++; 279 | return; 280 | } 281 | 282 | dptr->updateInterval = dptr->updateClock.restart(); 283 | QDateTime tms = QDateTime::currentDateTime(); 284 | 285 | for (int i=0;ipairings.count();i++) { 286 | int ofs = dptr->pairings[i].offset(); 287 | int sz = dptr->pairings[i].size(); 288 | int area = dptr->pairings.at(i).area; 289 | int db = dptr->pairings.at(i).db; 290 | if ((area!=daveDB) && (area!=daveDI)) 291 | db = 0; 292 | 293 | int res = daveReadBytes(dptr->daveConn,area,db,ofs,sz,NULL); 294 | if (res==0) { 295 | for (int j=0;jpairings.at(i).items.count();j++) { 296 | int idx = dptr->pairings.at(i).items.at(j); 297 | int iofs = dptr->watchpoints.at(idx).offset; 298 | CWP::VType t = dptr->watchpoints.at(idx).vtype; 299 | if (area==CWP::Counters) { 300 | dptr->watchpoints[idx].data = QVariant(daveGetCounterValueAt(dptr->daveConn,0)); 301 | } else if (area==CWP::Timers) { 302 | dptr->watchpoints[idx].data = QVariant(daveGetSecondsAt(dptr->daveConn,0)); 303 | } else { 304 | switch (t) { 305 | case CWP::S7BOOL: 306 | dptr->watchpoints[idx].data = QVariant(((daveGetU8At(dptr->daveConn,iofs-ofs) & 307 | (0x01 << dptr->watchpoints.at(idx).bitnum)) > 0)); 308 | break; 309 | case CWP::S7BYTE: 310 | dptr->watchpoints[idx].data = QVariant(static_cast(daveGetU8At(dptr->daveConn,iofs-ofs))); 311 | break; 312 | case CWP::S7WORD: 313 | dptr->watchpoints[idx].data = QVariant(static_cast(daveGetU16At(dptr->daveConn,iofs-ofs))); 314 | break; 315 | case CWP::S7DWORD: 316 | dptr->watchpoints[idx].data = QVariant(static_cast(daveGetU32At(dptr->daveConn,iofs-ofs))); 317 | break; 318 | case CWP::S7INT: 319 | dptr->watchpoints[idx].data = QVariant(daveGetS16At(dptr->daveConn,iofs-ofs)); 320 | break; 321 | case CWP::S7DINT: 322 | dptr->watchpoints[idx].data = QVariant(daveGetS32At(dptr->daveConn,iofs-ofs)); 323 | break; 324 | case CWP::S7REAL: 325 | dptr->watchpoints[idx].data = QVariant(static_cast(daveGetFloatAt(dptr->daveConn,iofs-ofs))); 326 | break; 327 | case CWP::S7TIME: 328 | if (true) { 329 | QTime t = QTime(0,0,0); 330 | int tm = daveGetS32At(dptr->daveConn,iofs-ofs); 331 | t = t.addMSecs(abs(tm)); 332 | dptr->watchpoints[idx].data = QVariant(t); 333 | dptr->watchpoints[idx].dataSign = (tm>=0); 334 | } 335 | break; 336 | case CWP::S7DATE: 337 | if (true) { 338 | QDate d = QDate(1990,1,1); 339 | d = d.addDays(static_cast(daveGetU16At(dptr->daveConn,iofs-ofs))); 340 | dptr->watchpoints[idx].data = QVariant(d); 341 | } 342 | break; 343 | case CWP::S7S5TIME: 344 | if (true) { 345 | uint s5 = static_cast(daveGetU16At(dptr->daveConn,iofs-ofs)); 346 | uint s5mode = (s5 >> 12) & 0x03; 347 | s5 = s5 & 0x0fff; 348 | uint mult; 349 | if (s5mode == 0) mult=10; 350 | else if (s5mode == 1) mult=100; 351 | else if (s5mode == 2) mult=1000; 352 | else mult = 10000; 353 | uint msecs = ((s5 >> 8) & 0x0f)*100 + ((s5 >> 4) & 0x0f)*10 + (s5 & 0x0f); 354 | QTime t = QTime(0,0,0,0); 355 | t = t.addMSecs(static_cast(msecs*mult)); 356 | dptr->watchpoints[idx].data = QVariant(t); 357 | } 358 | break; 359 | case CWP::S7TIME_OF_DAY: 360 | if (true) { 361 | QTime t = QTime(); 362 | t = t.addMSecs(static_cast(daveGetU32At(dptr->daveConn,iofs-ofs))); 363 | dptr->watchpoints[idx].data = QVariant(t); 364 | } 365 | break; 366 | default: 367 | dptr->watchpoints[idx].data = QVariant(); 368 | break; 369 | } 370 | } 371 | } 372 | } else { 373 | if (dptr->tmMaxRecErrorCount>0) { 374 | dptr->recErrorsCount++; 375 | if (dptr->recErrorsCount>dptr->tmMaxRecErrorCount) { 376 | QString strMsg(daveStrerror(res)); 377 | plcStop(); 378 | plcDisconnect(); 379 | emit plcError(trUtf8("Too many errors on active connection. Recording stopped. %1") 380 | .arg(strMsg),true); 381 | } 382 | } else 383 | dptr->recErrorsCount = 0; 384 | } 385 | } 386 | emit plcVariablesUpdatedConsistent(dptr->watchpoints,tms); 387 | emit plcVariablesUpdated(); 388 | dptr->clockInterlock.unlock(); 389 | } 390 | 391 | void CPLC::resClock() 392 | { 393 | dptr->recErrorsCount = 0; 394 | } 395 | 396 | void CPLC::infClock() 397 | { 398 | if (dptr->state==splcRecording) 399 | emit plcScanTime(trUtf8("%1 ms").arg(dptr->updateInterval)); 400 | else 401 | emit plcScanTime(trUtf8("- ms")); 402 | } 403 | 404 | CWP::CWP() 405 | { 406 | label = QString(); 407 | varea = NoArea; 408 | vtype = S7NoType; 409 | vdb = -1; 410 | offset = -1; 411 | bitnum = -1; 412 | data = QVariant(); 413 | dataSign = true; 414 | uuid = QUuid::createUuid(); 415 | } 416 | 417 | CWP::CWP(QString aLabel, CWP::VArea aArea, VType aType, int aVdb, int aOffset, int aBitnum) 418 | { 419 | label = aLabel; 420 | varea = aArea; 421 | vtype = aType; 422 | vdb = aVdb; 423 | offset = aOffset; 424 | bitnum = aBitnum; 425 | data = QVariant(); 426 | dataSign = true; 427 | uuid = QUuid::createUuid(); 428 | } 429 | 430 | CWP &CWP::operator =(const CWP &other) 431 | { 432 | label = other.label; 433 | varea = other.varea; 434 | vtype = other.vtype; 435 | vdb = other.vdb; 436 | offset = other.offset; 437 | bitnum = other.bitnum; 438 | data = other.data; 439 | dataSign = other.dataSign; 440 | uuid = other.uuid; 441 | return *this; 442 | } 443 | 444 | bool CWP::operator ==(const CWP &ref) const 445 | { 446 | return (uuid==ref.uuid); 447 | } 448 | 449 | bool CWP::operator !=(const CWP &ref) const 450 | { 451 | return (uuid!=ref.uuid); 452 | } 453 | 454 | int CWP::size() 455 | { 456 | if ((varea==Counters) || (varea==Timers)) return 2; 457 | switch (vtype) { 458 | case S7BOOL: 459 | case S7BYTE: 460 | return 1; 461 | case S7WORD: 462 | case S7INT: 463 | case S7S5TIME: 464 | case S7DATE: 465 | return 2; 466 | case S7DWORD: 467 | case S7DINT: 468 | case S7REAL: 469 | case S7TIME: 470 | case S7TIME_OF_DAY: 471 | return 4; 472 | default: 473 | return 0; 474 | } 475 | } 476 | 477 | 478 | CPairing::CPairing() 479 | { 480 | items.clear(); 481 | cnt = -1; 482 | sz = 0; 483 | ofs = -1; 484 | db = -1; 485 | wlist = NULL; 486 | area = CWP::NoArea; 487 | } 488 | 489 | CPairing::CPairing(CWPList *Wlist, CWP::VArea Area, int aDB) 490 | { 491 | items.clear(); 492 | cnt = -1; 493 | sz = 0; 494 | ofs = -1; 495 | db = aDB; 496 | wlist = Wlist; 497 | area = Area; 498 | } 499 | 500 | CPairing &CPairing::operator =(const CPairing &other) 501 | { 502 | items = other.items; 503 | cnt = other.cnt; 504 | ofs = other.ofs; 505 | sz = other.sz; 506 | db = other.db; 507 | wlist = other.wlist; 508 | area = other.area; 509 | return *this; 510 | } 511 | 512 | int CPairing::size() 513 | { 514 | if (cnt != items.count()) 515 | calcSize(); 516 | return sz; 517 | } 518 | 519 | int CPairing::offset() 520 | { 521 | if (cnt != items.count()) 522 | calcSize(); 523 | return ofs; 524 | } 525 | 526 | int CPairing::sizeWith(CWP wp) 527 | { 528 | if ((wp.varea!=area) || (wp.vdb!=db) || (wp.varea==CWP::Counters) || 529 | (wp.varea==CWP::Timers)) return INT_MAX; 530 | 531 | if (cnt != items.count()) 532 | calcSize(); 533 | int start1 = ofs; 534 | int stop1 = ofs + sz; 535 | int start2 = wp.offset; 536 | int stop2 = wp.offset + wp.size(); 537 | if (start2stop1) stop1 = stop2; 539 | return (stop1-start1); 540 | } 541 | 542 | int CPairing::offsetWith(CWP wp) 543 | { 544 | if (cnt != items.count()) 545 | calcSize(); 546 | int start1 = ofs; 547 | int stop1 = ofs + sz; 548 | int start2 = wp.offset; 549 | int stop2 = wp.offset + wp.size(); 550 | if (start2stop1) stop1 = stop2; 552 | return start1; 553 | } 554 | 555 | void CPairing::calcSize() 556 | { 557 | sz = 0; 558 | ofs = -1; 559 | cnt = items.count(); 560 | if (wlist==NULL) { 561 | qDebug() << "ERROR: call calcSize on uninitialized pairing list"; 562 | return; 563 | } 564 | 565 | int start1 = ofs; 566 | int stop1 = ofs + sz; 567 | for (int i=0;iat(items.at(i)).offset; 569 | int stop2 = (*wlist)[i].size() + start2; 570 | if (start1 == -1) { 571 | start1 = start2; 572 | stop1 = stop2; 573 | } else { 574 | if (start2stop1) stop1 = stop2; 576 | } 577 | } 578 | ofs = start1; 579 | sz = stop1-start1; 580 | } 581 | 582 | QDataStream &operator <<(QDataStream &out, const CWP &obj) 583 | { 584 | int a = static_cast(obj.varea); 585 | int b = static_cast(obj.vtype); 586 | out << obj.uuid << a << b << obj.vdb << obj.offset << obj.bitnum << obj.label << obj.data << obj.dataSign; 587 | return out; 588 | } 589 | 590 | QDataStream &operator >>(QDataStream &in, CWP &obj) 591 | { 592 | int a,b; 593 | in >> obj.uuid >> a >> b >> obj.vdb >> obj.offset >> obj.bitnum >> obj.label >> obj.data >> obj.dataSign; 594 | obj.varea = static_cast(a); 595 | obj.vtype = static_cast(b); 596 | return in; 597 | } 598 | -------------------------------------------------------------------------------- /mainwindow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #include "mainwindow.h" 4 | #include "ui_mainwindow.h" 5 | #include "global.h" 6 | #include "varmodel.h" 7 | #include "settingsdialog.h" 8 | #include "specwidgets.h" 9 | #include 10 | 11 | #define PLR_VERSION 2 12 | 13 | CGlobal *gSet = NULL; 14 | 15 | MainWindow::MainWindow(QWidget *parent) : 16 | QMainWindow(parent), 17 | ui(new Ui::MainWindow) 18 | { 19 | ui->setupUi(this); 20 | 21 | appendLog(trUtf8("Initializing.")); 22 | 23 | QIcon appicon; 24 | appicon.addFile(":/icon32"); 25 | appicon.addFile(":/icon40"); 26 | setWindowIcon(appicon); 27 | 28 | gSet = new CGlobal(this); 29 | csvHandler = new CCSVHandler(this); 30 | 31 | agcRestartCounter = 0; 32 | autoOnLogging = false; 33 | savedCSVActive = false; 34 | aggregatedStartActive = false; 35 | 36 | lblState = new QLabel(trUtf8("Offline")); 37 | cbVat = new QCheckBox(trUtf8("Online VAT")); 38 | cbRec = new QCheckBox(trUtf8("CSV recording")); 39 | cbPlot = new QCheckBox(trUtf8("Signal plot")); 40 | ui->statusBar->addPermanentWidget(cbPlot); 41 | ui->statusBar->addPermanentWidget(cbRec); 42 | ui->statusBar->addPermanentWidget(cbVat); 43 | ui->statusBar->addPermanentWidget(lblState); 44 | 45 | connect(ui->actionSettings,SIGNAL(triggered()),this,SLOT(settingsDlg())); 46 | connect(ui->actionLoadConnection,SIGNAL(triggered()),this,SLOT(loadConnection())); 47 | connect(ui->actionSaveConnection,SIGNAL(triggered()),this,SLOT(saveConnection())); 48 | connect(ui->actionForceRotateCSV,SIGNAL(triggered()),csvHandler,SLOT(rotateFile())); 49 | connect(ui->actionAbout,SIGNAL(triggered()),this,SLOT(aboutMsg())); 50 | connect(ui->actionAboutQt,SIGNAL(triggered()),this,SLOT(aboutQtMsg())); 51 | connect(ui->tableVariables,SIGNAL(ctxMenuRequested(QPoint)),this,SLOT(variablesCtxMenu(QPoint))); 52 | 53 | connect(cbVat,SIGNAL(clicked()),this,SLOT(vatControl())); 54 | connect(cbRec,SIGNAL(clicked()),this,SLOT(csvControl())); 55 | connect(cbPlot,SIGNAL(clicked()),this,SLOT(plotControl())); 56 | 57 | plc = new CPLC(); 58 | plcThread = new QThread(); 59 | 60 | vtmodel = new CVarModel(this,plc); 61 | vtmodel->mainWnd = this; 62 | ui->tableVariables->setModel(vtmodel); 63 | 64 | vtdelegate = new CVarDelegate(); 65 | vtdelegate->setVarModel(vtmodel); 66 | ui->tableVariables->setItemDelegate(vtdelegate); 67 | 68 | ui->btnConnect->setEnabled(true); 69 | ui->btnDisconnect->setEnabled(false); 70 | ui->actionLoadConnection->setEnabled(true); 71 | ui->actionSaveConnection->setEnabled(true); 72 | ui->actionForceRotateCSV->setEnabled(false); 73 | cbVat->setEnabled(false); 74 | cbVat->setChecked(false); 75 | cbRec->setEnabled(false); 76 | cbRec->setChecked(false); 77 | cbPlot->setEnabled(false); 78 | cbPlot->setChecked(false); 79 | 80 | plc->moveToThread(plcThread); 81 | plcThread->start(); 82 | 83 | connect(this,SIGNAL(plcCorrectToThread()),plc,SLOT(correctToThread()),Qt::QueuedConnection); 84 | emit plcCorrectToThread(); 85 | 86 | graph = new CGraphForm(this); 87 | graph->setWindowFlags(graph->windowFlags() | Qt::Window); 88 | graph->hide(); 89 | connect(ui->actionShowPlot,SIGNAL(triggered()),graph,SLOT(show())); 90 | 91 | connect(ui->btnConnect,SIGNAL(clicked()),this,SLOT(ctlAggregatedStartForce())); 92 | connect(ui->btnDisconnect,SIGNAL(clicked()),this,SLOT(ctlStop())); 93 | connect(ui->editAcqInterval,SIGNAL(valueChanged(int)), 94 | plc,SLOT(plcSetAcqInterval(int)),Qt::QueuedConnection); 95 | 96 | connect(plc,SIGNAL(plcError(QString,bool)),this,SLOT(plcErrorMsg(QString,bool)),Qt::QueuedConnection); 97 | connect(plc,SIGNAL(plcConnectFailed()),this,SLOT(plcStartFailed()),Qt::QueuedConnection); 98 | connect(plc,SIGNAL(plcStartFailed()),this,SLOT(plcStartFailed()),Qt::QueuedConnection); 99 | connect(plc,SIGNAL(plcOnConnect()),this,SLOT(plcConnected()),Qt::QueuedConnection); 100 | connect(plc,SIGNAL(plcOnDisconnect()),this,SLOT(plcDisconnected()),Qt::QueuedConnection); 101 | connect(plc,SIGNAL(plcOnStart()),this,SLOT(plcStarted()),Qt::QueuedConnection); 102 | connect(plc,SIGNAL(plcOnStop()),this,SLOT(plcStopped()),Qt::QueuedConnection); 103 | connect(plc,SIGNAL(plcVariablesUpdatedConsistent(CWPList,QDateTime)), 104 | this,SLOT(plcVariablesUpdatedConsistent(CWPList,QDateTime)),Qt::QueuedConnection); 105 | connect(plc,SIGNAL(plcScanTime(QString)),ui->lblActualAcqInterval,SLOT(setText(QString)),Qt::QueuedConnection); 106 | 107 | connect(ui->tableVariables,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(variablesCtxMenu(QPoint))); 108 | connect(graph,SIGNAL(logMessage(QString)),this,SLOT(appendLog(QString))); 109 | connect(graph,SIGNAL(stopGraph()),this,SLOT(plotStop())); 110 | 111 | connect(vtmodel,SIGNAL(syncPLCtoModel(CWPList)),plc,SLOT(plcSetWatchpoints(CWPList))); 112 | connect(this,SIGNAL(plcSetAddress(QString,int,int,int)),plc,SLOT(plcSetAddress(QString,int,int,int))); 113 | connect(this,SIGNAL(plcSetRetryParams(int,int,int)),plc,SLOT(plcSetRetryParams(int,int,int))); 114 | connect(this,SIGNAL(plcConnect()),plc,SLOT(plcConnect())); 115 | connect(this,SIGNAL(plcStart()),plc,SLOT(plcStart())); 116 | connect(this,SIGNAL(plcDisconnect()),plc,SLOT(plcDisconnect())); 117 | 118 | QTimer* syncTimer = new QTimer(this); 119 | syncTimer->setInterval(60000); 120 | connect(syncTimer,SIGNAL(timeout()),this,SLOT(syncTimer())); 121 | syncTimer->start(); 122 | 123 | bool needToStart = false; 124 | for (int i=1;igetCWPCount()>0)) { 133 | appendLog(trUtf8("Automatic reconnect after 10 sec from command prompt.")); 134 | autoOnLogging = true; 135 | QTimer::singleShot(10*1000,this,SLOT(ctlAggregatedStartForce())); 136 | } 137 | 138 | connect(csvHandler,SIGNAL(errorMessage(QString)),this,SLOT(csvError(QString))); 139 | connect(csvHandler,SIGNAL(recordingStopped()),this,SLOT(recordingStopped())); 140 | connect(csvHandler,SIGNAL(appendLog(QString)),this,SLOT(appendLog(QString))); 141 | connect(this,SIGNAL(csvSync()),csvHandler,SLOT(timerSync())); 142 | 143 | gSet->loadSettings(); 144 | } 145 | 146 | MainWindow::~MainWindow() 147 | { 148 | delete ui; 149 | } 150 | 151 | void MainWindow::appendLog(const QString &msg) 152 | { 153 | ui->textLog->appendPlainText(trUtf8("%1: %2"). 154 | arg(QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss")). 155 | arg(msg)); 156 | } 157 | 158 | void MainWindow::syncTimer() 159 | { 160 | if (cbRec->isChecked()) 161 | emit csvSync(); 162 | } 163 | 164 | void MainWindow::csvError(const QString &msg) 165 | { 166 | if (!gSet->suppressMsgBox) 167 | QMessageBox::critical(this,trUtf8("PLC recorder error"),msg); 168 | } 169 | 170 | void MainWindow::recordingStopped() 171 | { 172 | cbRec->setChecked(false); 173 | cbRec->setStyleSheet(QString()); 174 | ui->actionForceRotateCSV->setEnabled(false); 175 | } 176 | 177 | void MainWindow::loadConnectionFromFile(const QString &fname) 178 | { 179 | QFile f(fname); 180 | if (f.open(QIODevice::ReadOnly)) { 181 | QDataStream in(&f); 182 | in.setVersion(QDataStream::Qt_4_8); 183 | QString aip; 184 | int acqInt,arack,aslot, v; 185 | in >> v; 186 | if (v==PLR_VERSION) { 187 | in >> aip >> arack >> aslot >> acqInt; 188 | ui->editIP->setText(aip); 189 | ui->editRack->setValue(arack); 190 | ui->editSlot->setValue(aslot); 191 | ui->editAcqInterval->setValue(acqInt); 192 | vtmodel->loadWPList(in); 193 | f.close(); 194 | appendLog(trUtf8("File %1 loaded.").arg(fname)); 195 | return; 196 | } else { 197 | f.close(); 198 | QMessageBox::critical(this,trUtf8("PLC recorder error"), 199 | trUtf8("Unable to load file %1.\n" 200 | "Incompatible version.").arg(fname)); 201 | } 202 | } else 203 | QMessageBox::critical(this,trUtf8("PLC recorder error"), 204 | trUtf8("Unable to load file %1.").arg(fname)); 205 | appendLog(trUtf8("Unable to load file %1.").arg(fname)); 206 | } 207 | 208 | void MainWindow::closeEvent(QCloseEvent *event) 209 | { 210 | if (gSet!=NULL) 211 | gSet->saveSettings(); 212 | event->accept(); 213 | } 214 | 215 | void MainWindow::plcConnected() 216 | { 217 | ui->btnConnect->setEnabled(false); 218 | vtdelegate->setEditEnabled(false); 219 | vtmodel->setEditEnabled(false); 220 | ui->btnDisconnect->setEnabled(true); 221 | cbVat->setEnabled(false); 222 | cbVat->setChecked(false); 223 | cbVat->setStyleSheet(QString()); 224 | cbRec->setEnabled(false); 225 | cbRec->setChecked(false); 226 | cbRec->setStyleSheet(QString()); 227 | cbPlot->setEnabled(false); 228 | cbPlot->setChecked(false); 229 | cbPlot->setStyleSheet(QString()); 230 | 231 | ui->actionLoadConnection->setEnabled(false); 232 | 233 | lblState->setText(trUtf8("Online")); 234 | appendLog(trUtf8("Connected to PLC.")); 235 | 236 | csvHandler->stopClose(); 237 | ui->actionForceRotateCSV->setEnabled(false); 238 | } 239 | 240 | void MainWindow::plcDisconnected() 241 | { 242 | ui->btnConnect->setEnabled(true); 243 | vtdelegate->setEditEnabled(true); 244 | vtmodel->setEditEnabled(true); 245 | ui->btnDisconnect->setEnabled(false); 246 | cbVat->setEnabled(false); 247 | cbVat->setChecked(false); 248 | cbVat->setStyleSheet(QString()); 249 | cbRec->setEnabled(false); 250 | cbRec->setChecked(false); 251 | cbRec->setStyleSheet(QString()); 252 | cbPlot->setEnabled(false); 253 | cbPlot->setChecked(false); 254 | cbPlot->setStyleSheet(QString()); 255 | 256 | ui->actionLoadConnection->setEnabled(true); 257 | lblState->setText(trUtf8("Offline")); 258 | appendLog(trUtf8("Disconnected from PLC.")); 259 | 260 | csvHandler->stopClose(); 261 | ui->actionForceRotateCSV->setEnabled(false); 262 | } 263 | 264 | void MainWindow::plcStarted() 265 | { 266 | agcRestartCounter = 0; 267 | aggregatedStartActive = false; 268 | ui->btnConnect->setEnabled(false); 269 | vtdelegate->setEditEnabled(false); 270 | vtmodel->setEditEnabled(false); 271 | ui->btnDisconnect->setEnabled(true); 272 | cbVat->setEnabled(true); 273 | cbVat->setChecked(false); 274 | cbVat->setStyleSheet(QString()); 275 | cbRec->setEnabled(true); 276 | cbRec->setChecked(false); 277 | cbRec->setStyleSheet(QString()); 278 | cbPlot->setEnabled(true); 279 | cbPlot->setChecked(false); 280 | cbPlot->setStyleSheet(QString()); 281 | 282 | ui->actionLoadConnection->setEnabled(false); 283 | lblState->setText(trUtf8("ONLINE")); 284 | appendLog(trUtf8("Activating ONLINE.")); 285 | 286 | if (autoOnLogging || (gSet->restoreCSV && savedCSVActive)) { 287 | appendLog(trUtf8("Restore CSV recording.")); 288 | cbRec->setChecked(true); 289 | csvControl(); 290 | } 291 | } 292 | 293 | void MainWindow::plcStopped() 294 | { 295 | ui->btnConnect->setEnabled(false); 296 | vtdelegate->setEditEnabled(false); 297 | vtmodel->setEditEnabled(false); 298 | ui->btnDisconnect->setEnabled(true); 299 | cbVat->setEnabled(false); 300 | cbVat->setChecked(false); 301 | cbVat->setStyleSheet(QString()); 302 | cbRec->setEnabled(false); 303 | savedCSVActive = cbRec->isChecked(); 304 | cbRec->setChecked(false); 305 | cbRec->setStyleSheet(QString()); 306 | cbPlot->setEnabled(false); 307 | cbPlot->setChecked(false); 308 | cbPlot->setStyleSheet(QString()); 309 | 310 | ui->actionLoadConnection->setEnabled(false); 311 | lblState->setText(trUtf8("Online")); 312 | appendLog(trUtf8("Deactivating ONLINE.")); 313 | 314 | csvHandler->stopClose(); 315 | ui->actionForceRotateCSV->setEnabled(false); 316 | } 317 | 318 | void MainWindow::plcStartFailed() 319 | { 320 | if (agcRestartCounter!=INT_MAX) { 321 | if (gSet->tmTotalRetryCount==0) 322 | agcRestartCounter = 0; 323 | if (agcRestartCounter<=gSet->tmTotalRetryCount) { 324 | QTimer::singleShot(gSet->tmWaitReconnect*1000,this,SLOT(ctlAggregatedStart())); 325 | } else 326 | ctlStop(); 327 | } 328 | } 329 | 330 | void MainWindow::plcErrorMsg(const QString &msg, bool critical) 331 | { 332 | appendLog(msg); 333 | if (critical && !gSet->suppressMsgBox) 334 | QMessageBox::critical(this,trUtf8("PLC recorder error"),msg); 335 | } 336 | 337 | void MainWindow::plcVariablesUpdatedConsistent(const CWPList &wp, const QDateTime &stm) 338 | { 339 | // Updating VAT 340 | if (cbVat->isChecked()) 341 | vtmodel->loadActualsFromPLC(wp); 342 | 343 | // Updating CSV 344 | if (cbRec->isChecked()) 345 | csvHandler->addData(wp,stm); 346 | 347 | // Updating Plot 348 | if (cbPlot->isChecked()) 349 | graph->addData(wp,stm); 350 | } 351 | 352 | void MainWindow::connectPLC() 353 | { 354 | vtmodel->syncPLC(); 355 | emit plcSetRetryParams(gSet->tmMaxRecErrorCount, gSet->tmMaxConnectRetryCount, gSet->tmWaitReconnect); 356 | emit plcSetAddress(ui->editIP->text(), ui->editRack->value(), ui->editSlot->value(), gSet->tmTCPTimeout); 357 | emit plcConnect(); 358 | } 359 | 360 | void MainWindow::aboutMsg() 361 | { 362 | QMessageBox::about(this,trUtf8("PLC recorder"), 363 | trUtf8("PLC Recorder is a recording and debugging tool for Siemens S7 300/400 PLCs.\n\n" 364 | "Written by kernel1024, 2012-2018, under GPLv2 license.\n\n" 365 | "Includes partial libnodave snapshot.\n" 366 | "libnodave (c) Thomas Hergenhahn (thomas.hergenhahn@web.de) " 367 | "2002-2005, under license GPLv2.\n\n\n" 368 | "BIG FAT WARNING:\n" 369 | "This is beta code and information. You assume all responsibility for its use.\n" 370 | "DANGER: DON'T connect to a PLC unless you are certain it is safe to do so!!!\n" 371 | "It is assumed that you are experienced in PLC programming/troubleshooting and that\n" 372 | "you know EXACTLY what you are doing. PLCs are used to control industrial processes,\n" 373 | "motors, steam valves, hydraulic presses, etc.\n\n" 374 | "You are ABSOLUTELY RESPONSIBLE for ensuring that NO-ONE is in danger of being injured or killed\n" 375 | "because you affected the operation of a running PLC.\n\n" 376 | "Also expect that buggy drivers could write data even when you expect that they will read only!!!")); 377 | } 378 | 379 | void MainWindow::aboutQtMsg() 380 | { 381 | QMessageBox::aboutQt(this,trUtf8("About Qt")); 382 | } 383 | 384 | void MainWindow::variablesCtxMenu(QPoint pos) 385 | { 386 | if (!vtmodel->isEditEnabled()) return; 387 | 388 | QMenu cm(ui->tableVariables); 389 | 390 | QAction* acm; 391 | acm = cm.addAction(QIcon(":/new"),trUtf8("Add variable")); 392 | connect(acm,SIGNAL(triggered()),this,SLOT(ctxNew())); 393 | 394 | acm = cm.addAction(QIcon(":/delete"),trUtf8("Remove variable")); 395 | connect(acm,SIGNAL(triggered()),this,SLOT(ctxRemove())); 396 | acm->setEnabled(!(ui->tableVariables->selectionModel()->selectedIndexes().isEmpty())); 397 | 398 | cm.addSeparator(); 399 | 400 | acm = cm.addAction(trUtf8("Remove all")); 401 | connect(acm,SIGNAL(triggered()),this,SLOT(ctxRemoveAll())); 402 | 403 | QPoint p = pos; 404 | p.setY(p.y()+ui->tableVariables->horizontalHeader()->height()); 405 | p.setX(p.x()+ui->tableVariables->verticalHeader()->width()); 406 | cm.exec(ui->tableVariables->mapToGlobal(p)); 407 | } 408 | 409 | void MainWindow::ctxNew() 410 | { 411 | vtmodel->insertRow(vtmodel->getCWPCount()); 412 | } 413 | 414 | void MainWindow::ctxRemove() 415 | { 416 | QModelIndexList mi = ui->tableVariables->selectionModel()->selectedIndexes(); 417 | QList rows; 418 | for (int i=0;iremoveMultipleRows(rows); 424 | } 425 | 426 | void MainWindow::ctxRemoveAll() 427 | { 428 | vtmodel->removeRows(0,vtmodel->getCWPCount()); 429 | } 430 | 431 | void MainWindow::settingsDlg() 432 | { 433 | CSettingsDialog dlg; 434 | dlg.setParams(gSet->outputCSVDir,gSet->outputFileTemplate,gSet->tmTCPTimeout,gSet->tmMaxRecErrorCount, 435 | gSet->tmMaxConnectRetryCount,gSet->tmWaitReconnect,gSet->tmTotalRetryCount,gSet->suppressMsgBox, 436 | gSet->restoreCSV,gSet->plotVerticalSize,gSet->plotShowScatter,gSet->plotAntialiasing); 437 | if (dlg.exec()) { 438 | gSet->tmTCPTimeout = dlg.getTCPTimeout(); 439 | gSet->tmMaxRecErrorCount = dlg.getMaxRecErrorCount(); 440 | gSet->tmMaxConnectRetryCount = dlg.getMaxConnectRetryCount(); 441 | gSet->tmWaitReconnect = dlg.getWaitReconnect(); 442 | gSet->tmTotalRetryCount = dlg.getTotalRetryCount(); 443 | gSet->suppressMsgBox = dlg.getSuppressMsgBox(); 444 | gSet->restoreCSV = dlg.getRestoreCSV(); 445 | gSet->outputCSVDir = dlg.getOutputDir(); 446 | gSet->outputFileTemplate = dlg.getFileTemplate(); 447 | gSet->plotVerticalSize = dlg.getPlotVerticalSize(); 448 | gSet->plotShowScatter = dlg.getPlotShowScatter(); 449 | gSet->plotAntialiasing = dlg.getPlotAntialiasing(); 450 | } 451 | } 452 | 453 | void MainWindow::loadConnection() 454 | { 455 | QString s = getOpenFileNameD(this,trUtf8("Load connection settings file"),gSet->savedAuxDir, 456 | trUtf8("PLC recorder files (*.plr)")); 457 | if (s.isEmpty()) return; 458 | gSet->savedAuxDir = QFileInfo(s).absolutePath(); 459 | 460 | loadConnectionFromFile(s); 461 | } 462 | 463 | void MainWindow::saveConnection() 464 | { 465 | QString s = getSaveFileNameD(this,trUtf8("Save connection settings file"),gSet->savedAuxDir, 466 | trUtf8("PLC recorder files (*.plr)")); 467 | if (s.isEmpty()) return; 468 | gSet->savedAuxDir = QFileInfo(s).absolutePath(); 469 | 470 | QFile f(s); 471 | if (f.open(QIODevice::WriteOnly)) { 472 | QDataStream out(&f); 473 | out.setVersion(QDataStream::Qt_4_8); 474 | int v = PLR_VERSION; 475 | out << v << ui->editIP->text() << ui->editRack->value() << 476 | ui->editSlot->value() << ui->editAcqInterval->value(); 477 | vtmodel->saveWPList(out); 478 | f.flush(); 479 | f.close(); 480 | appendLog(trUtf8("File was saved %1.").arg(s)); 481 | } else { 482 | appendLog(trUtf8("Unable to save file %1.").arg(s)); 483 | QMessageBox::critical(this,trUtf8("PLC recorder error"),trUtf8("Unable to save file %1.").arg(s)); 484 | } 485 | } 486 | 487 | void MainWindow::csvControl() 488 | { 489 | bool fileOpened = false; 490 | if (cbRec->isChecked()) { 491 | fileOpened = csvHandler->rotateFile(); 492 | if (fileOpened) 493 | cbRec->setStyleSheet("background-color: red; color: white; font: bold;"); 494 | } else { 495 | csvHandler->stopClose(); 496 | cbRec->setStyleSheet(QString()); 497 | } 498 | ui->actionForceRotateCSV->setEnabled(cbRec->isChecked() && fileOpened); 499 | } 500 | 501 | void MainWindow::plotControl() 502 | { 503 | if (cbPlot->isChecked()) { 504 | graph->show(); 505 | cbPlot->setStyleSheet("background-color: blue; color: yellow; font: bold;"); 506 | } else { 507 | graph->hide(); 508 | cbPlot->setStyleSheet(QString()); 509 | } 510 | } 511 | 512 | void MainWindow::plotStop() 513 | { 514 | cbPlot->setChecked(false); 515 | cbPlot->setStyleSheet(QString()); 516 | graph->hide(); 517 | } 518 | 519 | void MainWindow::vatControl() 520 | { 521 | if (cbVat->isChecked()) 522 | cbVat->setStyleSheet("background-color: cyan; color: white; font: bold;"); 523 | else 524 | cbVat->setStyleSheet(QString()); 525 | } 526 | 527 | void MainWindow::ctlAggregatedStart() 528 | { 529 | if (agcRestartCounter==INT_MAX) { 530 | agcRestartCounter = 0; 531 | return; 532 | } 533 | 534 | aggregatedStartActive = true; 535 | ui->btnDisconnect->setEnabled(true); 536 | connectPLC(); 537 | emit plcStart(); 538 | agcRestartCounter++; 539 | appendLog(trUtf8("Activating PLC connection request %1.").arg(agcRestartCounter)); 540 | } 541 | 542 | void MainWindow::ctlAggregatedStartForce() 543 | { 544 | agcRestartCounter = 0; 545 | ctlAggregatedStart(); 546 | } 547 | 548 | void MainWindow::ctlStop() 549 | { 550 | if (qobject_cast(sender())!=NULL) 551 | autoOnLogging = false; 552 | 553 | if (aggregatedStartActive) 554 | agcRestartCounter=INT_MAX; 555 | emit plcDisconnect(); 556 | appendLog(trUtf8("Activation PLC disconnection request.")); 557 | ui->btnDisconnect->setEnabled(false); 558 | } 559 | 560 | void MainWindow::sysSIGPIPE() 561 | { 562 | appendLog(trUtf8("SIGPIPE received. Force reconnect to PLC.")); 563 | emit plcDisconnect(); 564 | ctlAggregatedStartForce(); 565 | } 566 | -------------------------------------------------------------------------------- /global.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #ifdef HAVE_QT5 4 | #include 5 | #else 6 | #include 7 | #endif 8 | 9 | #include "global.h" 10 | #include "plc.h" 11 | 12 | static QSize openFileDialogSize = QSize(); 13 | static QSize saveFileDialogSize = QSize(); 14 | const bool dontUseNativeFileDialog = true; 15 | 16 | CGlobal::CGlobal(QObject *parent) : 17 | QObject(parent) 18 | { 19 | outputCSVDir = QString(); 20 | outputFileTemplate = QString(); 21 | tmTCPTimeout = 5000000; 22 | tmMaxRecErrorCount = 50; 23 | plotVerticalSize = 100; 24 | plotShowScatter = false; 25 | plotAntialiasing = true; 26 | tmMaxConnectRetryCount = 1; 27 | tmWaitReconnect = 2; 28 | tmTotalRetryCount = 1; 29 | suppressMsgBox = false; 30 | restoreCSV = false; 31 | savedAuxDir = QString(); 32 | } 33 | 34 | QString CGlobal::plcGetAddrName(const CWP& aWp) 35 | { 36 | CWP wp = aWp; 37 | QString res; 38 | res.clear(); 39 | if (wp.vtype==CWP::S7NoType) 40 | return trUtf8("Select type ->"); 41 | 42 | switch (wp.varea) { 43 | case CWP::Inputs: res = "I"; break; 44 | case CWP::Outputs: res = "Q"; break; 45 | case CWP::Merkers: res = "M"; break; 46 | case CWP::DB: res = QString("DB%1.DB").arg(wp.vdb); break; 47 | case CWP::IDB: res = QString("IDB%1.DB").arg(wp.vdb); break; 48 | case CWP::Counters: res = "C"; break; 49 | case CWP::Timers: res = "T"; break; 50 | default: return QString(); 51 | } 52 | if ((wp.varea!=CWP::Counters) && (wp.varea!=CWP::Timers)) { 53 | switch (wp.vtype) { 54 | case CWP::S7BOOL: 55 | if ((wp.varea==CWP::DB) || (wp.varea==CWP::IDB)) 56 | res += QString("X%1.%2").arg(wp.offset).arg(wp.bitnum); 57 | else 58 | res += QString("%1.%2").arg(wp.offset).arg(wp.bitnum); 59 | break; 60 | case CWP::S7BYTE: 61 | res += QString("B%1").arg(wp.offset); 62 | break; 63 | case CWP::S7WORD: 64 | case CWP::S7INT: 65 | case CWP::S7S5TIME: 66 | case CWP::S7DATE: 67 | res += QString("W%1").arg(wp.offset); 68 | break; 69 | case CWP::S7DWORD: 70 | case CWP::S7DINT: 71 | case CWP::S7REAL: 72 | case CWP::S7TIME: 73 | case CWP::S7TIME_OF_DAY: 74 | res += QString("D%1").arg(wp.offset); 75 | break; 76 | 77 | default: return QString(); 78 | } 79 | } else { 80 | res += QString("%1").arg(wp.offset); 81 | } 82 | return res; 83 | } 84 | 85 | QString CGlobal::plcGetTypeName(const CWP& aWp) 86 | { 87 | if (aWp.varea==CWP::Timers) 88 | return QString("TIMER"); 89 | if (aWp.varea==CWP::Counters) 90 | return QString("COUNTER"); 91 | switch (aWp.vtype) { 92 | case CWP::S7BOOL: return QString("BOOL"); 93 | case CWP::S7BYTE: return QString("BYTE"); 94 | case CWP::S7WORD: return QString("WORD"); 95 | case CWP::S7INT: return QString("INT"); 96 | case CWP::S7S5TIME: return QString("S5TIME"); 97 | case CWP::S7DATE: return QString("DATE"); 98 | case CWP::S7DWORD: return QString("DWORD"); 99 | case CWP::S7DINT: return QString("DINT"); 100 | case CWP::S7REAL: return QString("REAL"); 101 | case CWP::S7TIME: return QString("TIME"); 102 | case CWP::S7TIME_OF_DAY: return QString("TOD"); 103 | default: return QString("----"); 104 | } 105 | } 106 | 107 | QStringList CGlobal::plcAvailableTypeNames() 108 | { 109 | QStringList sl; 110 | sl << QString("BOOL"); 111 | sl << QString("BYTE"); 112 | sl << QString("WORD"); 113 | sl << QString("INT"); 114 | sl << QString("S5TIME"); 115 | sl << QString("DATE"); 116 | sl << QString("DWORD"); 117 | sl << QString("DINT"); 118 | sl << QString("REAL"); 119 | sl << QString("TIME"); 120 | sl << QString("TOD"); 121 | sl << QString("TIMER"); 122 | sl << QString("COUNTER"); 123 | return sl; 124 | } 125 | 126 | bool CGlobal::plcSetTypeForName(const QString &tname, CWP& wp) 127 | { 128 | if (tname.toUpper().compare("BOOL")==0) { 129 | if (wp.offset<0) wp.offset = 0; 130 | wp.vtype=CWP::S7BOOL; 131 | return true; 132 | } 133 | if (tname.toUpper().compare("BYTE")==0) { 134 | if (wp.offset<0) wp.offset = 0; 135 | wp.vtype=CWP::S7BYTE; 136 | return true; 137 | } 138 | if (tname.toUpper().compare("WORD")==0) { 139 | if (wp.offset<0) wp.offset = 0; 140 | wp.vtype=CWP::S7WORD; 141 | return true; 142 | } 143 | if (tname.toUpper().compare("INT")==0) { 144 | if (wp.offset<0) wp.offset = 0; 145 | wp.vtype=CWP::S7INT; 146 | return true; 147 | } 148 | if (tname.toUpper().compare("S5TIME")==0) { 149 | if (wp.offset<0) wp.offset = 0; 150 | wp.vtype=CWP::S7S5TIME; 151 | return true; 152 | } 153 | if (tname.toUpper().compare("DATE")==0) { 154 | if (wp.offset<0) wp.offset = 0; 155 | wp.vtype=CWP::S7DATE; 156 | return true; 157 | } 158 | if (tname.toUpper().compare("DWORD")==0) { 159 | if (wp.offset<0) wp.offset = 0; 160 | wp.vtype=CWP::S7DWORD; 161 | return true; 162 | } 163 | if (tname.toUpper().compare("DINT")==0) { 164 | if (wp.offset<0) wp.offset = 0; 165 | wp.vtype=CWP::S7DINT; 166 | return true; 167 | } 168 | if (tname.toUpper().compare("REAL")==0) { 169 | if (wp.offset<0) wp.offset = 0; 170 | wp.vtype=CWP::S7REAL; 171 | return true; 172 | } 173 | if (tname.toUpper().compare("TIME")==0) { 174 | if (wp.offset<0) wp.offset = 0; 175 | wp.vtype=CWP::S7TIME; 176 | return true; 177 | } 178 | if (tname.toUpper().compare("TOD")==0) { 179 | if (wp.offset<0) wp.offset = 0; 180 | wp.vtype=CWP::S7TIME_OF_DAY; 181 | return true; 182 | } 183 | if (tname.toUpper().compare("TIMER")==0) { 184 | if (wp.offset<1) wp.offset = 1; 185 | wp.vtype=CWP::S7WORD; 186 | wp.varea=CWP::Timers; 187 | return true; 188 | } 189 | if (tname.toUpper().compare("COUNTER")==0) { 190 | if (wp.offset<1) wp.offset = 1; 191 | wp.vtype=CWP::S7INT; 192 | wp.varea=CWP::Counters; 193 | return true; 194 | } 195 | return false; 196 | } 197 | 198 | bool CGlobal::plcParseAddr(const QString &addr, CWP &wp) 199 | { 200 | // plcSetTypeForName must be called before this on same wp 201 | QString s = addr.toUpper().trimmed(); 202 | if (wp.varea==CWP::Timers) { 203 | if (!s.startsWith('T')) return false; 204 | s.remove('T'); 205 | bool okconv; 206 | int t = s.toInt(&okconv); 207 | if (!okconv) return false; 208 | if (t<0) return false; 209 | wp.offset = t; 210 | wp.bitnum = -1; 211 | wp.vdb = -1; 212 | } else if (wp.varea==CWP::Counters) { 213 | if (!s.startsWith('C')) return false; 214 | s.remove('C'); 215 | bool okconv; 216 | int t = s.toInt(&okconv); 217 | if (!okconv) return false; 218 | if (t<0) return false; 219 | wp.offset = t; 220 | wp.bitnum = -1; 221 | wp.vdb = -1; 222 | } else { 223 | CWP::VArea tarea; 224 | if (s.startsWith("IDB")) tarea = CWP::IDB; 225 | else if (s.startsWith('I')) tarea = CWP::Inputs; 226 | else if (s.startsWith('Q')) tarea = CWP::Outputs; 227 | else if (s.startsWith('M')) tarea = CWP::Merkers; 228 | else if (s.startsWith("DB")) tarea = CWP::DB; 229 | else return false; 230 | bool okconv1,okconv2; 231 | int ofs, bit; 232 | QStringList sl; 233 | 234 | if ((tarea==CWP::Inputs) || (tarea==CWP::Outputs) || (tarea==CWP::Merkers)) { 235 | if ((tarea==CWP::Inputs) && (!s.startsWith('I'))) return false; 236 | if ((tarea==CWP::Outputs) && (!s.startsWith('Q'))) return false; 237 | if ((tarea==CWP::Merkers) && (!s.startsWith('M'))) return false; 238 | s.remove(0,1); 239 | switch (wp.vtype) { 240 | case CWP::S7BOOL: 241 | if ((!s.at(0).isDigit()) || (!s.contains('.')) || (!s.at(s.length()-1).isDigit())) return false; 242 | sl = s.split('.'); 243 | if (sl.count()!=2) return false; 244 | ofs = sl.first().toInt(&okconv1); 245 | bit = sl.last().toInt(&okconv2); 246 | if ((!okconv1) || (!okconv2)) return false; 247 | if ((bit>7) || (bit<0) || (ofs<0)) return false; 248 | wp.varea = tarea; 249 | wp.offset = ofs; 250 | wp.bitnum = bit; 251 | wp.vdb = -1; 252 | break; 253 | case CWP::S7BYTE: 254 | if (!s.startsWith('B')) return false; 255 | s.remove(0,1); 256 | ofs = s.toInt(&okconv1); 257 | if (!okconv1) return false; 258 | if (ofs<0) return false; 259 | wp.varea = tarea; 260 | wp.offset = ofs; 261 | wp.bitnum = -1; 262 | wp.vdb = -1; 263 | break; 264 | case CWP::S7WORD: 265 | case CWP::S7INT: 266 | case CWP::S7S5TIME: 267 | case CWP::S7DATE: 268 | if (!s.startsWith('W')) return false; 269 | s.remove(0,1); 270 | ofs = s.toInt(&okconv1); 271 | if (!okconv1) return false; 272 | if (ofs<0) return false; 273 | wp.varea = tarea; 274 | wp.offset = ofs; 275 | wp.bitnum = -1; 276 | wp.vdb = -1; 277 | break; 278 | case CWP::S7DWORD: 279 | case CWP::S7DINT: 280 | case CWP::S7REAL: 281 | case CWP::S7TIME: 282 | case CWP::S7TIME_OF_DAY: 283 | if (!s.startsWith('D')) return false; 284 | s.remove(0,1); 285 | ofs = s.toInt(&okconv1); 286 | if (!okconv1) return false; 287 | if (ofs<0) return false; 288 | wp.varea = tarea; 289 | wp.offset = ofs; 290 | wp.bitnum = -1; 291 | wp.vdb = -1; 292 | break; 293 | default: 294 | return false; 295 | } 296 | } else if ((tarea==CWP::DB) || (tarea==CWP::IDB)) { 297 | if ((tarea==CWP::DB) && (!s.startsWith("DB"))) return false; 298 | if ((tarea==CWP::IDB) && (!s.startsWith("IDB"))) return false; 299 | if (tarea==CWP::DB) s.remove(0,2); 300 | if (tarea==CWP::IDB) s.remove(0,3); 301 | 302 | QString dotDB = QString(".DB"); 303 | if (!s.contains(dotDB)) return false; 304 | int tdb = s.left(s.indexOf(dotDB)).toInt(&okconv1); 305 | if (!okconv1) return false; 306 | s.remove(0,s.indexOf(dotDB)+dotDB.length()); 307 | 308 | switch (wp.vtype) { 309 | case CWP::S7BOOL: 310 | if (!s.startsWith('X')) return false; 311 | s.remove(0,1); 312 | if ((!s.at(0).isDigit()) || 313 | (!s.contains('.')) || 314 | (!s.at(s.length()-1).isDigit())) return false; 315 | sl = s.split('.'); 316 | if (sl.count()!=2) return false; 317 | ofs = sl.first().toInt(&okconv1); 318 | bit = sl.last().toInt(&okconv2); 319 | if ((!okconv1) || (!okconv2)) return false; 320 | if ((bit>7) || (bit<0) || (ofs<0)) return false; 321 | wp.varea = tarea; 322 | wp.offset = ofs; 323 | wp.bitnum = bit; 324 | wp.vdb = tdb; 325 | break; 326 | case CWP::S7BYTE: 327 | if (!s.startsWith('B')) return false; 328 | s.remove(0,1); 329 | ofs = s.toInt(&okconv1); 330 | if (!okconv1) return false; 331 | if (ofs<0) return false; 332 | wp.varea = tarea; 333 | wp.offset = ofs; 334 | wp.bitnum = -1; 335 | wp.vdb = tdb; 336 | break; 337 | case CWP::S7WORD: 338 | case CWP::S7INT: 339 | case CWP::S7S5TIME: 340 | case CWP::S7DATE: 341 | if (!s.startsWith('W')) return false; 342 | s.remove(0,1); 343 | ofs = s.toInt(&okconv1); 344 | if (!okconv1) return false; 345 | if (ofs<0) return false; 346 | wp.varea = tarea; 347 | wp.offset = ofs; 348 | wp.bitnum = -1; 349 | wp.vdb = tdb; 350 | break; 351 | case CWP::S7DWORD: 352 | case CWP::S7DINT: 353 | case CWP::S7REAL: 354 | case CWP::S7TIME: 355 | case CWP::S7TIME_OF_DAY: 356 | if (!s.startsWith('D')) return false; 357 | s.remove(0,1); 358 | ofs = s.toInt(&okconv1); 359 | if (!okconv1) return false; 360 | if (ofs<0) return false; 361 | wp.varea = tarea; 362 | wp.offset = ofs; 363 | wp.bitnum = -1; 364 | wp.vdb = tdb; 365 | break; 366 | default: 367 | return false; 368 | } 369 | } else 370 | return false; 371 | } 372 | wp.data=QVariant(); 373 | return true; 374 | } 375 | 376 | QString CGlobal::plcFormatActualValue(const CWP &wp) 377 | { 378 | if (wp.data.isNull() || !wp.data.isValid()) return QString(); 379 | double data; 380 | switch (wp.vtype) { 381 | case CWP::S7BYTE: 382 | return trUtf8("0x%1").arg(wp.data.toInt(),2,16,QChar('0')); 383 | case CWP::S7WORD: 384 | return trUtf8("0x%1").arg(wp.data.toInt(),4,16,QChar('0')); 385 | case CWP::S7DWORD: 386 | return trUtf8("0x%1").arg(wp.data.toInt(),8,16,QChar('0')); 387 | case CWP::S7S5TIME: 388 | case CWP::S7TIME_OF_DAY: 389 | return trUtf8("%1").arg(wp.data.toTime().toString("hh:mm:ss.zzz")); 390 | case CWP::S7TIME: 391 | if (wp.dataSign) 392 | return trUtf8("%1").arg(wp.data.toTime().toString("hh:mm:ss.zzz")); 393 | else 394 | return trUtf8("-%1").arg(wp.data.toTime().toString("hh:mm:ss.zzz")); 395 | case CWP::S7REAL: 396 | data = wp.data.toDouble(); 397 | if (qAbs(data)>1e6 || qAbs(data)<0.001) 398 | return QString::number(data,'e',4); 399 | else 400 | return QString::number(data,'f',3); 401 | default: 402 | return wp.data.toString(); 403 | } 404 | } 405 | 406 | bool CGlobal::plcIsPlottableType(const CWP &aWp) 407 | { 408 | switch (aWp.vtype) { 409 | case CWP::S7BOOL: 410 | case CWP::S7BYTE: 411 | case CWP::S7WORD: 412 | case CWP::S7DWORD: 413 | case CWP::S7INT: 414 | case CWP::S7DINT: 415 | case CWP::S7REAL: 416 | return true; 417 | default: 418 | return false; 419 | } 420 | } 421 | 422 | void CGlobal::loadSettings() 423 | { 424 | #ifdef HAVE_QT5 425 | QString docs = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); 426 | #else 427 | QString docs = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); 428 | #endif 429 | 430 | QSettings settings("kernel1024", "plcrecorder"); 431 | settings.beginGroup("Settings"); 432 | gSet->outputCSVDir = settings.value("outputCSVDir",docs).toString(); 433 | gSet->outputFileTemplate = settings.value("outputFileTemplate",QString()).toString(); 434 | gSet->tmTCPTimeout = settings.value("timeTCPTimeout",5000000).toInt(); 435 | gSet->tmMaxRecErrorCount = settings.value("timeMaxRecErrorCount",50).toInt(); 436 | gSet->tmMaxConnectRetryCount = settings.value("timeMaxConnectRetryCount",1).toInt(); 437 | gSet->tmTotalRetryCount = settings.value("timeTotalRetryCount",1).toInt(); 438 | gSet->tmWaitReconnect = settings.value("timeWaitReconnect",2).toInt(); 439 | gSet->suppressMsgBox = settings.value("suppressMsgBox",false).toBool(); 440 | gSet->restoreCSV = settings.value("restoreCSV",false).toBool(); 441 | gSet->plotVerticalSize = settings.value("plotVerticalSize",100).toInt(); 442 | gSet->plotShowScatter = settings.value("plotShowScatter",false).toBool(); 443 | gSet->plotAntialiasing = settings.value("plotAntialiasing",true).toBool(); 444 | gSet->savedAuxDir = settings.value("savedAuxDir",QString()).toString(); 445 | settings.endGroup(); 446 | } 447 | 448 | void CGlobal::saveSettings() 449 | { 450 | QSettings settings("kernel1024", "plcrecorder"); 451 | settings.beginGroup("Settings"); 452 | settings.setValue("outputCSVDir",gSet->outputCSVDir); 453 | settings.setValue("outputFileTemplate",gSet->outputFileTemplate); 454 | settings.setValue("timeTCPTimeout",gSet->tmTCPTimeout); 455 | settings.setValue("timeMaxRecErrorCount",gSet->tmMaxRecErrorCount); 456 | settings.setValue("timeMaxConnectRetryCount",gSet->tmMaxConnectRetryCount); 457 | settings.setValue("timeTotalRetryCount",gSet->tmTotalRetryCount); 458 | settings.setValue("timeWaitReconnect",gSet->tmWaitReconnect); 459 | settings.setValue("suppressMsgBox",gSet->suppressMsgBox); 460 | settings.setValue("restoreCSV",gSet->restoreCSV); 461 | settings.setValue("plotVerticalSize",gSet->plotVerticalSize); 462 | settings.setValue("plotShowScatter",gSet->plotShowScatter); 463 | settings.setValue("plotAntialiasing",gSet->plotAntialiasing); 464 | settings.setValue("savedAuxDir",gSet->savedAuxDir); 465 | settings.endGroup(); 466 | } 467 | 468 | QString getOpenFileNameD (QWidget * parent, const QString & caption, const QString & dir, 469 | const QString & filter, QString * selectedFilter) 470 | { 471 | QFileDialog::Options opts = 0; 472 | if (dontUseNativeFileDialog) 473 | opts = QFileDialog::DontUseNativeDialog | QFileDialog::DontUseCustomDirectoryIcons; 474 | 475 | QFileDialog dialog(parent,caption,dir,filter); 476 | dialog.setOptions(opts); 477 | dialog.setAcceptMode(QFileDialog::AcceptOpen); 478 | dialog.setFileMode(QFileDialog::ExistingFile); 479 | if (openFileDialogSize.isValid()) 480 | dialog.resize(openFileDialogSize); 481 | 482 | QString res; 483 | if (selectedFilter && !selectedFilter->isEmpty()) 484 | dialog.selectNameFilter(*selectedFilter); 485 | if (dialog.exec() == QDialog::Accepted) { 486 | if (selectedFilter) 487 | *selectedFilter = dialog.selectedNameFilter(); 488 | if (!dialog.selectedFiles().isEmpty()) 489 | res = dialog.selectedFiles().first(); 490 | } 491 | 492 | openFileDialogSize = dialog.size(); 493 | return res; 494 | } 495 | 496 | QStringList getOpenFileNamesD (QWidget * parent, const QString & caption, const QString & dir, 497 | const QString & filter, QString * selectedFilter) 498 | { 499 | QFileDialog::Options opts = 0; 500 | if (dontUseNativeFileDialog) 501 | opts = QFileDialog::DontUseNativeDialog | QFileDialog::DontUseCustomDirectoryIcons; 502 | 503 | QFileDialog dialog(parent,caption,dir,filter); 504 | dialog.setOptions(opts); 505 | dialog.setAcceptMode(QFileDialog::AcceptOpen); 506 | dialog.setFileMode(QFileDialog::ExistingFiles); 507 | if (openFileDialogSize.isValid()) 508 | dialog.resize(openFileDialogSize); 509 | 510 | QStringList res; 511 | if (selectedFilter && !selectedFilter->isEmpty()) 512 | dialog.selectNameFilter(*selectedFilter); 513 | if (dialog.exec() == QDialog::Accepted) { 514 | if (selectedFilter) 515 | *selectedFilter = dialog.selectedNameFilter(); 516 | res = dialog.selectedFiles(); 517 | } 518 | 519 | openFileDialogSize = dialog.size(); 520 | return res; 521 | } 522 | 523 | QStringList getSuffixesFromFilter(const QString& filter) 524 | { 525 | QStringList res; 526 | res.clear(); 527 | if (filter.isEmpty()) return res; 528 | 529 | QStringList filters = filter.split(";;",QString::SkipEmptyParts); 530 | if (filters.isEmpty()) return res; 531 | 532 | for (int i=0;iisEmpty()) 561 | dialog.selectNameFilter(*selectedFilter); 562 | 563 | if (!preselectFileName.isEmpty()) 564 | dialog.selectFile(preselectFileName); 565 | 566 | QString res; 567 | if (dialog.exec()==QDialog::Accepted) { 568 | QString userFilter = dialog.selectedNameFilter(); 569 | if (selectedFilter!=NULL) 570 | *selectedFilter=userFilter; 571 | if (!userFilter.isEmpty()) 572 | dialog.setDefaultSuffix(getSuffixesFromFilter(userFilter).first()); 573 | 574 | if (!dialog.selectedFiles().isEmpty()) 575 | res = dialog.selectedFiles().first(); 576 | } 577 | 578 | saveFileDialogSize = dialog.size(); 579 | return res; 580 | } 581 | 582 | QString getExistingDirectoryD ( QWidget * parent, const QString & caption, const QString & dir, QFileDialog::Options options ) 583 | { 584 | QFileDialog::Options opts = options; 585 | if (dontUseNativeFileDialog) 586 | opts = QFileDialog::DontUseNativeDialog | QFileDialog::DontUseCustomDirectoryIcons; 587 | 588 | return QFileDialog::getExistingDirectory(parent,caption,dir,opts); 589 | } 590 | -------------------------------------------------------------------------------- /graphform.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include "ui_graphform.h" 9 | #include "graphform.h" 10 | #include 11 | 12 | static QList validArea; 13 | const static double zoomIncrements = 0.2; // in percents of actual data range 14 | 15 | void initGraphFormData() 16 | { 17 | validArea.clear(); 18 | validArea << CWP::Inputs << CWP::Outputs << CWP::Merkers << CWP::DB << CWP::IDB; 19 | } 20 | 21 | CGraphForm::CGraphForm(QWidget *parent) : 22 | QWidget(parent), 23 | ui(new Ui::CGraphForm) 24 | { 25 | ui->setupUi(this); 26 | 27 | moveSplitterOnce = true; 28 | runningCursor = NULL; 29 | leftCursor = NULL; 30 | rightCursor = NULL; 31 | watchpoints.clear(); 32 | 33 | ui->plot->setContextMenuPolicy(Qt::CustomContextMenu); 34 | 35 | connect(ui->plot,SIGNAL(mouseMove(QMouseEvent*)),this,SLOT(plotMouseMove(QMouseEvent*))); 36 | connect(ui->btnLoadCSV,SIGNAL(clicked()),this,SLOT(loadCSV())); 37 | connect(ui->btnExport,SIGNAL(clicked()),this,SLOT(exportGraph())); 38 | connect(ui->horizontalScrollBar,SIGNAL(valueChanged(int)),this,SLOT(scrollBarMoved(int))); 39 | connect(ui->plot,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(plotContextMenu(QPoint))); 40 | 41 | ui->splitter->setCollapsible(0,false); 42 | ui->splitter->setCollapsible(1,true); 43 | 44 | clearData(); 45 | } 46 | 47 | CGraphForm::~CGraphForm() 48 | { 49 | delete ui; 50 | } 51 | 52 | void CGraphForm::setupGraphs(const CWPList &wp) 53 | { 54 | bool lazyModification = ((wp.count()>watchpoints.count()) && // new WP added, check old WPs 55 | (watchpoints == wp.mid(0,watchpoints.count()))); // old WPs still here, new WPs added to the end 56 | clearDataEx(lazyModification); 57 | 58 | QCPRange xRange(qQNaN(),qQNaN()); 59 | int idx = 0; 60 | for (int i=0;iplcIsPlottableType(wp.at(i))) continue; 63 | 64 | if (lazyModification && iplot->graph(idx)->keyAxis()->range(); 68 | // skip old WPs initialization 69 | idx++; 70 | continue; 71 | } 72 | 73 | // default value ranges 74 | double yMin, yMax; 75 | switch (wp.at(i).vtype) { 76 | case CWP::S7BOOL: 77 | yMin = 0.0; 78 | yMax = 1.0; 79 | break; 80 | case CWP::S7BYTE: 81 | case CWP::S7WORD: 82 | case CWP::S7DWORD: 83 | case CWP::S7INT: 84 | case CWP::S7DINT: 85 | case CWP::S7REAL: 86 | yMin = -5.0; 87 | yMax = 50.0; 88 | break; 89 | default: 90 | idx++; 91 | continue; // Special type, no visualization 92 | } 93 | 94 | QCPLayoutGrid* grid = ui->plot->plotLayout(); 95 | 96 | // create axis grid, placed in new layout element 97 | QCPAxisRect* rect = new QCPAxisRect(ui->plot,false); 98 | grid->addElement(idx,0,rect); 99 | 100 | // grid geometry, affects scrolling and sizeHint's 101 | grid->setRowSpacing(0); 102 | rect->setMinimumMargins(QMargins(0,0,0,0)); 103 | rect->setMinimumSize(100,gSet->plotVerticalSize); 104 | rect->setMaximumSize(getScreenWidth(),gSet->plotVerticalSize); 105 | 106 | // enable drag and zoom for xAxis 107 | QCPAxis* xAxis = rect->addAxis(QCPAxis::atTop); 108 | QCPAxis* yAxis = rect->addAxis(QCPAxis::atLeft); 109 | rect->setRangeDragAxes(xAxis,NULL); 110 | rect->setRangeZoomAxes(xAxis,NULL); 111 | 112 | // WP name as yAxis title 113 | QFont font = yAxis->labelFont(); 114 | font.setPointSize(6); 115 | yAxis->setLabelFont(font); 116 | QFontMetrics fm(font); 117 | QString yLabel = fm.elidedText(wp.at(i).label,Qt::ElideRight,gSet->plotVerticalSize); 118 | yAxis->setLabel(QString("%1\n%2").arg(yLabel,gSet->plcGetAddrName(wp.at(i)))); 119 | 120 | // value ticks for analogue WPs at yAxis 121 | if (wp.at(i).vtype==CWP::S7BOOL) 122 | yAxis->setTickLabels(false); 123 | else { 124 | yAxis->setTickLabels(true); 125 | yAxis->setTickLabelSide(QCPAxis::lsInside); 126 | yAxis->setTickLabelFont(font); 127 | } 128 | 129 | // date/time ticks for xAxis 130 | if (idx==0) { 131 | QSharedPointer dateTicker(new QCPAxisTickerDateTime); 132 | dateTicker->setDateTimeFormat("h:mm:ss.zzz\nd.MM.yyyy"); 133 | xAxis->setTicker(dateTicker); 134 | xAxis->setTickLabelFont(font); 135 | } else 136 | xAxis->setTickLabels(false); 137 | 138 | xAxis->grid()->setVisible(true); 139 | yAxis->grid()->setVisible(true); 140 | 141 | // graph parameters 142 | QCPGraph* graph = ui->plot->addGraph(xAxis,yAxis); 143 | graph->setAntialiased(gSet->plotAntialiasing); 144 | graph->setAdaptiveSampling(true); 145 | graph->setLineStyle(QCPGraph::lsStepLeft); 146 | if (gSet->plotShowScatter) 147 | graph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssPlus)); 148 | 149 | // visible graph xRange, 1 min for complete init, copy from old WPs for lazy init 150 | if (lazyModification && QCPRange::validRange(xRange)) 151 | xAxis->setRange(xRange); 152 | else { 153 | double time = static_cast(QDateTime::currentDateTime().toMSecsSinceEpoch())/1000.0; 154 | xAxis->setRange(time,time+60); 155 | } 156 | 157 | // default yRange for data type 158 | double yRange = abs(yMax-yMin); 159 | yAxis->setRange(yMin-(yRange*0.1),yMax+(yRange*0.1)); 160 | 161 | // handle xAxis drag 162 | connect(xAxis,SIGNAL(rangeChanged(QCPRange)),this,SLOT(plotRangeChanged(QCPRange))); 163 | 164 | idx++; 165 | } 166 | ui->plot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables); 167 | 168 | watchpoints = wp; 169 | } 170 | 171 | void CGraphForm::addData(const CWPList &wp, const QDateTime& time, bool noReplot) 172 | { 173 | if (wp!=watchpoints) { // comparing by uuid, WP must be same count, same order 174 | emit logMessage(trUtf8("Variables list changed. Initializing graphs.")); 175 | setupGraphs(wp); 176 | } 177 | 178 | double key = static_cast(time.toMSecsSinceEpoch())/1000.0; 179 | int idx = 0; 180 | 181 | for (int i=0;iplcIsPlottableType(wp.at(i))) continue; 184 | 185 | double val = 0.0; 186 | QVariant dt = wp.at(i).data; 187 | switch (wp.at(i).vtype) { 188 | case CWP::S7BOOL: 189 | if (dt.toBool()) 190 | val = 1.0; 191 | else 192 | val = 0.0; 193 | break; 194 | case CWP::S7BYTE: 195 | val = static_cast(dt.toUInt()); 196 | break; 197 | case CWP::S7WORD: 198 | val = static_cast(dt.toUInt()); 199 | break; 200 | case CWP::S7DWORD: 201 | val = static_cast(dt.toUInt()); 202 | break; 203 | case CWP::S7INT: 204 | val = static_cast(dt.toInt()); 205 | break; 206 | case CWP::S7DINT: 207 | val = static_cast(dt.toInt()); 208 | break; 209 | case CWP::S7REAL: 210 | val = dt.toDouble(); 211 | break; 212 | default: 213 | continue; 214 | } 215 | 216 | QCPGraph* graph = ui->plot->graph(idx); 217 | graph->addData(key,val); 218 | 219 | // dynamically correct yAxis range for analogue WPs 220 | if (wp.at(i).vtype!=CWP::S7BOOL) { 221 | QCPAxis* yAxis = graph->valueAxis(); 222 | bool foundRange; 223 | QCPRange dataRange = graph->getValueRange(foundRange, QCP::sdBoth); 224 | if (foundRange && 225 | (dataRange.lower < yAxis->range().lower || 226 | dataRange.upper > yAxis->range().upper)) { 227 | double increment = dataRange.size()*zoomIncrements; 228 | yAxis->setRange(dataRange.lower-increment, 229 | dataRange.upper+increment); 230 | } 231 | } 232 | idx++; 233 | } 234 | 235 | // Check visible range, move range if needed 236 | if (ui->checkAutoScroll->isChecked() && !ui->plot->axisRect(0)->axis(QCPAxis::atTop)->range().contains(key)) { 237 | double size = ui->plot->axisRect(0)->axis(QCPAxis::atTop)->range().size(); 238 | double start = key-(size*0.1); 239 | for (int i=0;iplot->axisRectCount();i++) 240 | ui->plot->axisRect(i)->axis(QCPAxis::atTop)->setRange(start,start+size); 241 | } 242 | 243 | // silent update (file loading) enabled 244 | if (!noReplot) { 245 | updateScrollBarRange(); 246 | ui->plot->replot(); 247 | } 248 | } 249 | 250 | int CGraphForm::getScreenWidth() 251 | { 252 | int screen = 0; 253 | QWidget *w = window(); 254 | QDesktopWidget *desktop = QApplication::desktop(); 255 | if (w) { 256 | screen = desktop->screenNumber(w); 257 | } else if (desktop->isVirtualDesktop()) { 258 | screen = desktop->screenNumber(QCursor::pos()); 259 | } else { 260 | screen = desktop->screenNumber(this); 261 | } 262 | QRect rect(desktop->availableGeometry(screen)); 263 | return rect.width(); 264 | } 265 | 266 | void CGraphForm::closeEvent(QCloseEvent *event) 267 | { 268 | emit stopGraph(); 269 | event->ignore(); 270 | } 271 | 272 | void CGraphForm::showEvent(QShowEvent *) 273 | { 274 | if (moveSplitterOnce) { 275 | int min, max; 276 | ui->splitter->getRange(0,&min,&max); 277 | ui->splitter->setSizes(QList() << max << 10); 278 | moveSplitterOnce = false; 279 | } 280 | } 281 | 282 | void CGraphForm::clearData() 283 | { 284 | clearDataEx(false); 285 | } 286 | 287 | void CGraphForm::clearDataEx(bool clearOnlyCursors) 288 | { 289 | if (runningCursor!=NULL) ui->plot->removeItem(runningCursor); 290 | if (leftCursor!=NULL) ui->plot->removeItem(leftCursor); 291 | if (rightCursor!=NULL) ui->plot->removeItem(rightCursor); 292 | runningCursor = NULL; 293 | leftCursor = NULL; 294 | rightCursor = NULL; 295 | 296 | ui->listRunning->clear(); 297 | ui->listRunning->setColumnCount(0); 298 | ui->listRunning->setRowCount(0); 299 | ui->listLeft->clear(); 300 | ui->listLeft->setColumnCount(0); 301 | ui->listLeft->setRowCount(0); 302 | ui->listRight->clear(); 303 | ui->listRight->setColumnCount(0); 304 | ui->listRight->setRowCount(0); 305 | 306 | if (clearOnlyCursors) { 307 | ui->plot->replot(); 308 | return; 309 | } 310 | 311 | ui->plot->clearGraphs(); 312 | ui->plot->plotLayout()->clear(); 313 | 314 | ui->plot->replot(); 315 | 316 | watchpoints.clear(); 317 | ui->horizontalScrollBar->setRange(0,0); 318 | ui->horizontalScrollBar->setEnabled(false); 319 | } 320 | 321 | QCPRange CGraphForm::getTotalKeyRange() 322 | { 323 | QCPRange res(qQNaN(),qQNaN()); 324 | for (int i=0;iplot->graphCount();i++) { 325 | bool foundRange; 326 | QCPRange dataRange = ui->plot->graph(i)->getKeyRange(foundRange, QCP::sdBoth); 327 | if (foundRange) 328 | res.expand(dataRange); 329 | } 330 | 331 | return res; 332 | } 333 | 334 | void CGraphForm::updateScrollBarRange() 335 | { 336 | QCPRange xRange = getTotalKeyRange(); 337 | if (xRange.size()>0.0) { 338 | ui->horizontalScrollBar->setMaximum(static_cast(xRange.size())); // scrollbar range from 0, in seconds 339 | if (!ui->horizontalScrollBar->isEnabled()) 340 | ui->horizontalScrollBar->setEnabled(true); 341 | } 342 | } 343 | 344 | void CGraphForm::zoomAll() 345 | { 346 | if (ui->plot->axisRectCount()<1 || 347 | ui->plot->graphCount()<1) return; 348 | 349 | QCPRange totalRange = getTotalKeyRange(); 350 | if (QCPRange::validRange(totalRange)) 351 | for (int i=0;iplot->axisRectCount();i++) 352 | ui->plot->axisRect(i)->axis(QCPAxis::atTop)->setRange(totalRange); 353 | 354 | ui->plot->replot(); 355 | } 356 | 357 | void CGraphForm::plotRangeChanged(const QCPRange &newRange) 358 | { 359 | QCPAxis* xAxis = qobject_cast(sender()); 360 | for (int i=0;iplot->axisRectCount();i++) { 361 | QCPAxis* ax = ui->plot->axisRect(i)->axis(QCPAxis::atTop); 362 | if (ax!=xAxis) 363 | ax->setRange(newRange); 364 | } 365 | 366 | QCPRange totalRange = getTotalKeyRange(); 367 | if (xAxis!=NULL && // null axis sender when updating from scrollbar 368 | QCPRange::validRange(totalRange)) { 369 | ui->horizontalScrollBar->setValue(static_cast(newRange.center()-totalRange.lower)); 370 | ui->horizontalScrollBar->setPageStep(static_cast(newRange.size())); 371 | } 372 | } 373 | 374 | void CGraphForm::plotMouseMove(QMouseEvent *event) 375 | { 376 | QPointF pos(event->pos()); 377 | 378 | QCPAxisRect *rect = ui->plot->axisRectAt(pos); 379 | if (rect!=NULL) { 380 | 381 | // create 'cursors' layer if needed 382 | QCPLayer *cursors = ui->plot->layer("cursor"); 383 | if (cursors==NULL) { 384 | ui->plot->addLayer("cursor"); 385 | ui->plot->setCurrentLayer("main"); 386 | cursors = ui->plot->layer("cursor"); 387 | } 388 | 389 | double x = rect->axis(QCPAxis::atTop)->pixelToCoord(pos.x()); 390 | 391 | // cursor type selection 392 | QCPItemStraightLine* cursor; 393 | if (event->modifiers() & Qt::ControlModifier) cursor = leftCursor; 394 | else if (event->modifiers() & Qt::AltModifier) cursor = rightCursor; 395 | else cursor = runningCursor; 396 | 397 | if (cursor!=NULL) 398 | ui->plot->removeItem(cursor); 399 | 400 | // cursor init 401 | cursor = new QCPItemStraightLine(ui->plot); 402 | cursor->setLayer(cursors); 403 | cursor->setClipToAxisRect(false); 404 | cursor->setClipAxisRect(rect); 405 | cursor->point1->setAxes(rect->axis(QCPAxis::atTop),rect->axis(QCPAxis::atLeft)); 406 | cursor->point2->setAxes(rect->axis(QCPAxis::atTop),rect->axis(QCPAxis::atLeft)); 407 | cursor->point1->setCoords(x,QCPRange::minRange); 408 | cursor->point2->setCoords(x,QCPRange::maxRange); 409 | 410 | if (event->modifiers() & Qt::ControlModifier) { 411 | cursor->setPen(QPen(QBrush(QColor(Qt::green)),2)); 412 | leftCursor = cursor; 413 | createCursorSignal(ctLeft,x); 414 | } else if (event->modifiers() & Qt::AltModifier) { 415 | cursor->setPen(QPen(QBrush(QColor(Qt::red)),2)); 416 | rightCursor = cursor; 417 | createCursorSignal(ctRight,x); 418 | } else { 419 | cursor->setPen(QPen(QBrush(QColor(Qt::black)),2)); 420 | runningCursor = cursor; 421 | createCursorSignal(ctRunning,x); 422 | } 423 | 424 | cursors->replot(); 425 | } 426 | } 427 | 428 | void CGraphForm::scrollBarMoved(int value) 429 | { 430 | QCPRange totalRange = getTotalKeyRange(); 431 | if (!QCPRange::validRange(totalRange) || 432 | ui->plot->axisRectCount()<1) return; 433 | 434 | double newCenter = totalRange.lower + static_cast(value); 435 | QCPRange currentRange = ui->plot->axisRect(0)->axis(QCPAxis::atTop)->range(); 436 | 437 | // check delta for recursion prevention 438 | if (qAbs(newCenter-currentRange.center()) > 0.05) 439 | { 440 | currentRange += newCenter - currentRange.center(); 441 | plotRangeChanged(currentRange); 442 | ui->plot->replot(); 443 | } 444 | } 445 | 446 | void CGraphForm::plotContextMenu(const QPoint &pos) 447 | { 448 | QMenu cm(ui->plot); 449 | 450 | QAction* acm; 451 | acm = cm.addAction(QIcon(":/zoom"),trUtf8("Zoom all")); 452 | connect(acm,SIGNAL(triggered()),this,SLOT(zoomAll())); 453 | cm.addSeparator(); 454 | 455 | acm = cm.addAction(QIcon(":/trash-empty"),trUtf8("Clear plot")); 456 | connect(acm,SIGNAL(triggered()),this,SLOT(clearData())); 457 | 458 | QPoint p = pos; 459 | cm.exec(ui->plot->mapToGlobal(p)); 460 | } 461 | 462 | void CGraphForm::loadCSV() 463 | { 464 | QString fname = getOpenFileNameD(this,trUtf8("Load CSV file"),gSet->savedAuxDir, 465 | trUtf8("CSV files (*.csv)")); 466 | if (fname.isEmpty()) return; 467 | gSet->savedAuxDir = QFileInfo(fname).absolutePath(); 468 | 469 | clearData(); 470 | 471 | QFile f(fname); 472 | if (!f.open(QIODevice::ReadOnly)) { 473 | QMessageBox::critical(this,trUtf8("PLC recorder error"), 474 | trUtf8("Unable to open file %1.").arg(fname)); 475 | return; 476 | } 477 | QTextStream in(&f); 478 | QString s = in.readLine(); 479 | if (!s.startsWith("\"Time\"; ")) { 480 | QMessageBox::critical(this,trUtf8("PLC recorder error"), 481 | trUtf8("Unrecognized CSV file %1.").arg(fname)); 482 | f.close(); 483 | return; 484 | } 485 | int lineNum = 2; 486 | while (!in.atEnd()) { 487 | s = in.readLine().trimmed(); 488 | 489 | // skip empty lines and additional title lines 490 | // this is support for merged files 491 | if (s.isEmpty() || 492 | s.startsWith("\"Time\"; ")) continue; 493 | 494 | int idx = s.lastIndexOf("; "); 495 | if (idx<0) { 496 | QMessageBox::critical(this,trUtf8("PLC recorder error"), 497 | trUtf8("Unexpected end of file %1 at line %2.").arg(fname).arg(lineNum)); 498 | f.close(); 499 | return; 500 | } 501 | s = s.section("; ",-1,-1,QString::SectionSkipEmpty); 502 | QByteArray ba = QByteArray::fromBase64(s.toLatin1()); 503 | if (ba.isEmpty()) { 504 | QMessageBox::critical(this,trUtf8("PLC recorder error"), 505 | trUtf8("Corrupted scan data in file %1 at line %2.").arg(fname).arg(lineNum)); 506 | f.close(); 507 | return; 508 | } 509 | ba = qUncompress(ba); 510 | if (ba.isEmpty()) { 511 | QMessageBox::critical(this,trUtf8("PLC recorder error"), 512 | trUtf8("Corrupted compressed data in file %1 at line %2.").arg(fname).arg(lineNum)); 513 | f.close(); 514 | return; 515 | } 516 | 517 | QBuffer buf(&ba); 518 | buf.open(QIODevice::ReadOnly); 519 | QDataStream in(&buf); 520 | 521 | CWPList wp; 522 | QDateTime dt; 523 | in >> dt >> wp; 524 | buf.close(); 525 | ba.clear(); 526 | 527 | if (wp.isEmpty()) { 528 | QMessageBox::critical(this,trUtf8("PLC recorder error"), 529 | trUtf8("Scan data is empty in file %1 at line %2.").arg(fname).arg(lineNum)); 530 | f.close(); 531 | return; 532 | } 533 | 534 | addData(wp,dt,true); 535 | qApp->processEvents(); 536 | 537 | lineNum++; 538 | } 539 | f.close(); 540 | updateScrollBarRange(); 541 | zoomAll(); 542 | qApp->processEvents(); 543 | QMessageBox::information(this,trUtf8("PLC recorder"), 544 | trUtf8("File successfully loaded.")); 545 | } 546 | 547 | void CGraphForm::exportGraph() 548 | { 549 | QString fname = getSaveFileNameD(this,tr("Save to file"),gSet->savedAuxDir, 550 | tr("PDF file (*.pdf);;PNG file (*.png);;" 551 | "Jpeg file (*.jpg);;BMP file (*.bmp)")); 552 | 553 | if (fname.isNull() || fname.isEmpty()) return; 554 | gSet->savedAuxDir = QFileInfo(fname).absolutePath(); 555 | 556 | QFileInfo fi(fname); 557 | if (fi.suffix().toLower()=="pdf") 558 | ui->plot->savePdf(fname); 559 | else if (fi.suffix().toLower()=="png") 560 | ui->plot->savePng(fname); 561 | else if (fi.suffix().toLower()=="jpg") 562 | ui->plot->saveJpg(fname); 563 | else if (fi.suffix().toLower()=="bmp") 564 | ui->plot->saveBmp(fname); 565 | } 566 | 567 | void CGraphForm::createCursorSignal(CGraphForm::CursorType cursor, double timestamp) 568 | { 569 | QDateTime time = QDateTime::fromMSecsSinceEpoch(static_cast(timestamp*1000.0)); 570 | 571 | CWPList res = watchpoints; 572 | int idx = 0; 573 | for (int i=0;iplcIsPlottableType(res.at(i))) { 576 | res[i].data = QVariant(); 577 | continue; 578 | } 579 | 580 | bool dataValid = false; 581 | double data = 0.0; 582 | const QCPGraph* graph = ui->plot->graph(idx); 583 | 584 | // find nearest value to cursor 585 | bool foundRange; 586 | QCPGraphDataContainer::const_iterator it = graph->data()->findBegin(timestamp); 587 | QCPRange dataRange = graph->getKeyRange(foundRange, QCP::sdBoth); 588 | if (foundRange && 589 | (it != graph->data()->constEnd())) 590 | { 591 | // key must be inside actual graph 592 | if ((it->key > dataRange.lower) && 593 | (it->key < dataRange.upper)) { 594 | data = it->value; 595 | dataValid = true; 596 | } 597 | } 598 | 599 | // cast aquired data to our data types 600 | if (dataValid) { 601 | switch (watchpoints.at(i).vtype) { 602 | case CWP::S7BOOL: 603 | res[i].data = QVariant(data>0.5); 604 | break; 605 | case CWP::S7BYTE: 606 | case CWP::S7WORD: 607 | case CWP::S7DWORD: 608 | res[i].data = QVariant(static_cast(data)); 609 | break; 610 | case CWP::S7INT: 611 | case CWP::S7DINT: 612 | res[i].data = QVariant(static_cast(data)); 613 | break; 614 | case CWP::S7REAL: 615 | res[i].data = QVariant(data); 616 | break; 617 | default: 618 | res[i].data = QVariant(); 619 | break; 620 | }; 621 | } else 622 | res[i].data = QVariant(); 623 | 624 | idx++; 625 | } 626 | 627 | // cursor type selection 628 | QTableWidget* list = NULL; 629 | QLabel* timeLabel = NULL; 630 | switch (cursor) { 631 | case ctRunning: 632 | list = ui->listRunning; 633 | timeLabel = ui->lblTimeRunning; 634 | break; 635 | case ctLeft: 636 | list = ui->listLeft; 637 | timeLabel = ui->lblTimeLeft; 638 | break; 639 | case ctRight: 640 | list = ui->listRight; 641 | timeLabel = ui->lblTimeRight; 642 | break; 643 | } 644 | 645 | if (list!=NULL && timeLabel!=NULL) { 646 | QFontMetrics fm(list->font()); 647 | // cursor properties list initialization 648 | if (list->rowCount()!=res.count()) { 649 | list->clearContents(); 650 | list->setRowCount(res.count()); 651 | list->setColumnCount(2); 652 | for (int i=0;isetItem(i,0,new QTableWidgetItem(QString())); 654 | list->setItem(i,1,new QTableWidgetItem(QString())); 655 | list->setRowHeight(i,fm.height()+5); 656 | } 657 | } 658 | 659 | for (int i=0;iitem(i,0)->text()!=res.at(i).label) 661 | list->item(i,0)->setText(res.at(i).label); 662 | list->item(i,1)->setText(gSet->plcFormatActualValue(res.at(i))); 663 | } 664 | 665 | timeLabel->setText(time.toString("h:mm:ss.zzz d.MM.yy")); 666 | } 667 | 668 | emit cursorMoved(cursor,time,res); 669 | } 670 | --------------------------------------------------------------------------------