summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authortpearson <tpearson@283d02a7-25f6-0310-bc7c-ecb5cbfe19da>2010-02-19 18:17:02 +0000
committertpearson <tpearson@283d02a7-25f6-0310-bc7c-ecb5cbfe19da>2010-02-19 18:17:02 +0000
commitf867212c1762e156553d039319b904a17f7b563d (patch)
tree461c1a743b3ff8291e03360742dbbfb4cc0087e4 /src
downloadknutclient-f867212c1762e156553d039319b904a17f7b563d.tar.gz
knutclient-f867212c1762e156553d039319b904a17f7b563d.zip
Added KDE3 version of knutclient
git-svn-id: svn://anonsvn.kde.org/home/kde/branches/trinity/applications/knutclient@1092914 283d02a7-25f6-0310-bc7c-ecb5cbfe19da
Diffstat (limited to 'src')
-rw-r--r--src/Makefile.am41
-rw-r--r--src/hi16-app-knutclient.pngbin0 -> 313 bytes
-rwxr-xr-xsrc/hi16-app-knutclientconn.pngbin0 -> 865 bytes
-rw-r--r--src/hi16-app-knutclienterr.pngbin0 -> 521 bytes
-rw-r--r--src/hi32-app-knutclient.pngbin0 -> 523 bytes
-rw-r--r--src/hi48-app-knutclient.pngbin0 -> 962 bytes
-rw-r--r--src/knutanalog.cpp911
-rw-r--r--src/knutanalog.h452
-rwxr-xr-xsrc/knutclient.cpp1237
-rw-r--r--src/knutclient.desktop20
-rwxr-xr-xsrc/knutclient.h210
-rw-r--r--src/knutclientui.rc24
-rwxr-xr-xsrc/knutconst.h58
-rwxr-xr-xsrc/knutdock.cpp976
-rwxr-xr-xsrc/knutdock.h525
-rwxr-xr-xsrc/knutfrontpanel.cpp676
-rwxr-xr-xsrc/knutfrontpanel.h333
-rwxr-xr-xsrc/knutinstcomms.cpp137
-rwxr-xr-xsrc/knutinstcomms.h97
-rw-r--r--src/knutmainwindow.cpp813
-rw-r--r--src/knutmainwindow.h346
-rw-r--r--src/knutmessage.cpp95
-rw-r--r--src/knutmessage.h126
-rw-r--r--src/knutmessagemanager.cpp121
-rw-r--r--src/knutmessagemanager.h131
-rwxr-xr-xsrc/knutnet.cpp1941
-rwxr-xr-xsrc/knutnet.h869
-rw-r--r--src/knutnewupsdlg.cpp294
-rw-r--r--src/knutnewupsdlg.h160
-rw-r--r--src/knutpanelmeter.cpp353
-rw-r--r--src/knutpanelmeter.h210
-rw-r--r--src/knutprefdlg.cpp979
-rw-r--r--src/knutprefdlg.h359
-rw-r--r--src/knutprintupsvar.cpp210
-rwxr-xr-xsrc/knutprintupsvar.h160
-rwxr-xr-xsrc/knutrwvar.cpp217
-rwxr-xr-xsrc/knutrwvar.h140
-rw-r--r--src/knutupsdata.cpp78
-rw-r--r--src/knutupsdata.h161
-rwxr-xr-xsrc/knutvardata.cpp242
-rwxr-xr-xsrc/knutvardata.h261
-rw-r--r--src/lo16-app-knutclient.pngbin0 -> 167 bytes
-rw-r--r--src/lo16-app-knutclientconn.pngbin0 -> 648 bytes
-rw-r--r--src/lo16-app-knutclienterr.pngbin0 -> 262 bytes
-rw-r--r--src/lo32-app-knutclient.pngbin0 -> 330 bytes
-rw-r--r--src/main.cpp78
46 files changed, 14041 insertions, 0 deletions
diff --git a/src/Makefile.am b/src/Makefile.am
new file mode 100644
index 0000000..5c68efa
--- /dev/null
+++ b/src/Makefile.am
@@ -0,0 +1,41 @@
+# set the include path for X, qt and KDE
+INCLUDES = $(all_includes)
+
+# these are the headers for your project
+noinst_HEADERS = knutclient.h knutmainwindow.h knutprefdlg.h knutnewupsdlg.h \
+ knutupsdata.h knutvardata.h knutnet.h knutfrontpanel.h knutpanelmeter.h knutdock.h \
+ knutprintupsvar.h knutinstcomms.h knutrwvar.h knutanalog.h knutmessagemanager.h \
+ knutmessage.h
+
+# let automoc handle all of the meta source files (moc)
+METASOURCES = AUTO
+
+messages: rc.cpp
+ $(EXTRACTRC) `find . -name \*.ui -o -name \*.rc` > rc.cpp
+ $(XGETTEXT) *.cpp -o $(podir)/knutclient.pot
+
+KDE_ICON = AUTO
+
+#########################################################################
+# APPLICATION SECTION
+#########################################################################
+# this is the program that gets installed. it's name is used for all
+# of the other Makefile.am variables
+bin_PROGRAMS = knutclient
+
+# the application source, library search path, and link libraries
+knutclient_SOURCES = main.cpp knutclient.cpp knutmainwindow.cpp knutprefdlg.cpp \
+ knutnewupsdlg.cpp knutupsdata.cpp knutvardata.cpp knutnet.cpp knutfrontpanel.cpp \
+ knutpanelmeter.cpp knutdock.cpp knutprintupsvar.cpp knutinstcomms.cpp knutrwvar.cpp \
+ knutanalog.cpp knutmessagemanager.cpp knutmessage.cpp
+knutclient_LDFLAGS = $(KDE_RPATH) $(all_libraries)
+knutclient_LDADD = $(LIB_KDEUI)
+
+# this is where the desktop file will go
+shelldesktopdir = $(kde_appsdir)/Utilities
+shelldesktop_DATA = knutclient.desktop
+
+# this is where the shell's XML-GUI resource file goes
+shellrcdir = $(kde_datadir)/knutclient
+shellrc_DATA = knutclientui.rc
+
diff --git a/src/hi16-app-knutclient.png b/src/hi16-app-knutclient.png
new file mode 100644
index 0000000..2583d9a
--- /dev/null
+++ b/src/hi16-app-knutclient.png
Binary files differ
diff --git a/src/hi16-app-knutclientconn.png b/src/hi16-app-knutclientconn.png
new file mode 100755
index 0000000..e298e09
--- /dev/null
+++ b/src/hi16-app-knutclientconn.png
Binary files differ
diff --git a/src/hi16-app-knutclienterr.png b/src/hi16-app-knutclienterr.png
new file mode 100644
index 0000000..61c9b28
--- /dev/null
+++ b/src/hi16-app-knutclienterr.png
Binary files differ
diff --git a/src/hi32-app-knutclient.png b/src/hi32-app-knutclient.png
new file mode 100644
index 0000000..f5c9beb
--- /dev/null
+++ b/src/hi32-app-knutclient.png
Binary files differ
diff --git a/src/hi48-app-knutclient.png b/src/hi48-app-knutclient.png
new file mode 100644
index 0000000..b26d5c9
--- /dev/null
+++ b/src/hi48-app-knutclient.png
Binary files differ
diff --git a/src/knutanalog.cpp b/src/knutanalog.cpp
new file mode 100644
index 0000000..c240523
--- /dev/null
+++ b/src/knutanalog.cpp
@@ -0,0 +1,911 @@
+ /***************************************************************************
+ * Copyright (C) 2007 by Daniel Prynych *
+ * Daniel.Prynych@buzuluk.cz *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#include "knutanalog.h"
+
+/* pocitani uhlu */
+/* nula je ve 3 hodiny */
+/* prirustek je kladny ve smeru hod rucicek */
+
+#include <stdio.h>
+#include <math.h>
+
+#include <qpainter.h>
+#include <qframe.h>
+#include <qfontmetrics.h>
+#include <qfont.h>
+#include <qbitmap.h>
+#include <qpaintdevice.h>
+#include <qcolor.h>
+
+#include <kapp.h>
+
+
+
+KNutAnalog::KNutAnalog( QWidget *parent, const char *name, int bottomLimit, int topLimit, int typeOfView, int countOfParts, int countOfSubParts, QColor pointerColor, QColor scaleColor, QColor textColor, QFont *analogFonts, int qualityOfPointer, bool makeBG )
+ : QFrame( parent, name ), m_bottomLimit(bottomLimit), m_topLimit(topLimit), m_typeOfView(typeOfView), m_countOfParts(countOfParts), m_countOfSubParts(countOfSubParts), m_pointerColor(pointerColor), m_scaleColor(scaleColor) ,m_textColor(textColor) {
+
+
+ if ( qualityOfPointer==0) {
+ m_speedOfAAlias=none;
+ m_makeBlurMotion=false;
+ }
+ else {
+ if ((qualityOfPointer==2) || (qualityOfPointer== 4)) m_speedOfAAlias=slow; else m_speedOfAAlias=fast;
+ if ((qualityOfPointer==3) || (qualityOfPointer== 4)) m_makeBlurMotion=true; else m_makeBlurMotion=false;
+ }
+
+// m_showBackGround = true;
+// m_showPointer = true;
+
+ if (m_countOfParts > 6) m_countOfParts=6;
+ else if (m_countOfParts < 2) m_countOfParts=2;
+
+
+ if ( m_countOfSubParts > 6 ) m_countOfSubParts = 6;
+ if ( m_countOfSubParts == 0 ) {
+ if (m_countOfParts < 4) m_countOfSubParts =5;
+ else {
+ if (m_countOfParts < 6) m_countOfSubParts=4;
+ else m_countOfSubParts =3;
+ }
+ }
+
+ m_valueOfPointer=m_bottomLimit;
+ /* hodnoty zavisle na typu zobrazeni */
+ switch (m_typeOfView) {
+ case 1 :
+ m_direction = 1; /* smer =1 ve smeru (clockwise), smer =-1 proti smeru hod. rucicek */
+ m_angleOfViewer=270;
+ m_startAngle=225;
+ m_centerX=m_widthOfBackGround/2;
+ m_centerY=m_widthOfBackGround/2;
+ m_widthOfScale=118;
+ m_radiusOfScaleNumbers=37;
+ break;
+ case 2 :
+ m_direction = -1; /* smer =1 ve smeru (clockwise), smer =-1 proti smeru hod. rucicek */
+ m_angleOfViewer=90;
+ m_startAngle=0;
+ m_centerX=13;
+ m_centerY=110;
+ m_widthOfScale=210;
+ m_radiusOfScaleNumbers=83;
+ break;
+ case 3 :
+ m_direction = 1; /* smer =1 ve smeru (clockwise), smer =-1 proti smeru hod. rucicek */
+ m_angleOfViewer=90;
+ m_startAngle=135;
+ m_centerX=m_widthOfBackGround/2;
+ m_centerY=m_widthOfBackGround-15;
+ m_widthOfScale=170;
+ m_radiusOfScaleNumbers=65;
+ break;
+ }
+ // konec hodnot zavislych na typu zobrazeni
+
+ if (analogFonts == 0) { // pokud neni predan font nastavi se systemovy font
+ m_scaleFont = kapp->font();
+ m_textFont = kapp->font();
+ }
+ else {
+ m_scaleFont= *analogFonts;
+ m_textFont= *analogFonts;
+ }
+
+ m_countOfColorParts = 0;
+ setMinimumSize( AnalogWidth, AnalogWidth );
+ setMaximumSize( AnalogWidth, AnalogWidth );
+ setFrameStyle( QFrame::Box | QFrame::Raised );
+ setLineWidth( 2 );
+
+ m_backgroudLayerBig = new QPixmap( (AnalogWidth-8) * 3,(AnalogWidth-8)*3 );
+
+ m_scaleLayerBig = new QPixmap ( (AnalogWidth-8)*3, (AnalogWidth-8)*3 ); //
+ m_scaleLayerSmall = new QPixmap ( (AnalogWidth-8), (AnalogWidth-8)); //
+
+ m_wholeLayer = new QPixmap ( AnalogWidth-8, AnalogWidth-8 ); //
+
+ m_pointerLayerBig = new QPixmap ( (AnalogWidth-8)*3, (AnalogWidth-8)*3 ); //
+ m_pointerLayerSmall = new QPixmap ( (AnalogWidth-8), (AnalogWidth-8)); //
+
+ setDefaultArcColor(false); // sets standard registers // nastavime standartni registry
+
+ if (makeBG) {
+ paintBackGround();
+ m_showBackGround = true;
+ m_showPointer = true;
+ }
+ }
+
+KNutAnalog::~KNutAnalog() {
+
+ delete (m_backgroudLayerBig);
+
+ delete (m_scaleLayerBig);
+ delete (m_scaleLayerSmall);
+
+ delete (m_pointerLayerBig);
+ delete (m_pointerLayerSmall);
+
+ delete (m_wholeLayer);
+}
+
+
+void KNutAnalog::makeBackground (bool run) {
+
+ paintBackGround();
+ m_showBackGround = true;
+ if (run) {
+ repaint();
+ }
+ }
+
+
+void KNutAnalog::setText (QString inscription, QString text_up, bool run) {
+
+ m_inscription=inscription;
+ AnMJ=text_up;
+ if (run) {
+ paintBackGround();
+ m_showBackGround = true;
+ repaint();
+ }
+ }
+
+void KNutAnalog::setDefaultArcColor(bool run) {
+
+ m_arcColors[0] = Qt::white;
+ m_arcColors[1] = Qt::green;
+ m_arcColors[2] = Qt::yellow;
+ m_arcColors[3] = Qt::red;
+ m_arcColors[4] = Qt::blue;
+ m_arcColors[5] = Qt::cyan;
+ m_arcColors[6] = Qt::magenta;
+ m_arcColors[7] = Qt::gray;
+ m_arcColors[8] = Qt::black;
+ if (run) {
+ paintBackGround();
+ m_showBackGround=true;
+ repaint();
+ }
+ }
+
+
+void KNutAnalog::setArcColor(int reg, QColor color ) {
+ if ((reg > -1) && (reg < 9)) m_arcColors[reg] = color;
+ }
+
+
+void KNutAnalog::addArc (double startOfCircle, double endOfCircle, int regColor, bool run) {
+
+ if (m_countOfColorParts < 5) {
+ m_extentOfDye[m_countOfColorParts].start=startOfCircle;
+ m_extentOfDye[m_countOfColorParts].end=endOfCircle;
+ if ((regColor <0) || (regColor > 8)) regColor=0;
+ m_extentOfDye[m_countOfColorParts++].color=regColor;
+ }
+ if (run) {
+ paintBackGround();
+ m_showBackGround = true;
+ repaint ();
+ }
+ }
+
+
+void KNutAnalog::delArc (bool run) {
+
+ m_countOfColorParts = 0;
+ if (run) {
+ paintBackGround();
+ m_showBackGround = true;
+ repaint ();
+ }
+ }
+
+
+
+void KNutAnalog::setRange (int Astart, int Aend , bool run) {
+
+ m_bottomLimit=Astart;
+ m_topLimit=Aend;
+ // pokud zmenime rozasah musime prekrelit i rucicku
+ m_showPointer = true;
+ if (run) {
+ paintBackGround();
+ m_showBackGround = true;
+ repaint ();
+ }
+ }
+
+
+
+void KNutAnalog::setMember (int Count, bool run) {
+
+ m_countOfParts=Count;
+ if (run) {
+ paintBackGround();
+ m_showBackGround = true;
+ repaint ();
+ }
+ }
+
+
+
+void KNutAnalog::setPointerColor (QColor pointerColor, bool run ) {
+
+ m_pointerColor = pointerColor;
+ paintPointer();
+ m_showPointer = true;
+ if (run) {
+ repaint ();
+ }
+ }
+
+
+void KNutAnalog::repaintPointer ( bool run ) {
+
+ paintPointer();
+ m_showPointer = true;
+ if (run) {
+ repaint ();
+ }
+ }
+
+
+void KNutAnalog::setFontColor (QColor fontColor, bool run ) {
+
+ m_textColor = fontColor;
+// paintBackGround();
+// m_showBackGround = true;
+ if (run) {
+ paintBackGround();
+ m_showBackGround = true;
+ repaint ();
+ }
+ }
+
+
+void KNutAnalog::setScaleColor (QColor scaleColor, bool run) {
+
+ m_scaleColor = scaleColor;
+ if (run) {
+ paintBackGround();
+ m_showBackGround = true;
+ repaint ();
+ }
+ }
+
+
+void KNutAnalog::setDigitalProcesing (int qualityOfPointer, bool run ) {
+
+ if (qualityOfPointer < 0) qualityOfPointer = 0;
+ if (qualityOfPointer > 4) qualityOfPointer = 4;
+ if ( qualityOfPointer==0) {
+ m_speedOfAAlias=none;
+ m_makeBlurMotion=false;
+ }
+ else {
+ if ((qualityOfPointer==2) || (qualityOfPointer== 4)) m_speedOfAAlias=slow; else m_speedOfAAlias=fast;
+ if ((qualityOfPointer==3) || (qualityOfPointer== 4)) m_makeBlurMotion=true; else m_makeBlurMotion=false;
+ }
+ paintPointer();
+ m_showPointer = true; // pri jakemkoliv prekresleni prekreslime rucicku
+ if (run) repaint ();
+}
+
+
+
+void KNutAnalog::setPointer (double pointerValue, bool run ) {
+ if (m_valueOfPointer != pointerValue) {
+ m_valueOfPointer = pointerValue;
+ paintPointer();
+ m_showPointer = true; // pri jakemkoliv prekresleni prekreslime rucicku
+ if (run) {
+// paintPointer();
+ m_showPointer = true; // pri jakemkoliv prekresleni prekreslime rucicku
+ repaint ();
+ }
+ }
+}
+
+
+
+//************** PUBLIC SLOTS **********************************
+
+void KNutAnalog::slotSetScaleFont(QFont newScaleFont){
+ m_scaleFont = newScaleFont;
+ paintBackGround();
+ m_showBackGround=true;
+ repaint();
+ }
+
+void KNutAnalog::slotSetTextFont(QFont newTextFont){
+ m_textFont = newTextFont;
+ paintBackGround();
+ paintPointer(); // repaint values if pointer
+ m_showBackGround=true;
+ m_showPointer=true;
+ repaint();
+ }
+
+void KNutAnalog::slotSetAllFont(QFont newAllFont){
+ m_scaleFont = newAllFont;
+ m_textFont = newAllFont;
+ paintBackGround();
+ paintPointer(); // repaint values if pointer
+ m_showBackGround=true;
+ m_showPointer=true;
+ repaint();
+ }
+
+
+void KNutAnalog::repaintAll (void) {
+ paintBackGround();
+ m_showBackGround = true;
+ m_showPointer = true;
+ repaint ();
+ }
+
+
+//************** protected ****************************
+
+void KNutAnalog::resizeEvent( QResizeEvent * ) {
+}
+
+
+void KNutAnalog::paintEvent( QPaintEvent *e ) {
+
+ if (isVisible()) {
+ QFrame::paintEvent(e);
+ if ((m_showBackGround) || (m_showPointer)) { // novou kompletni vrstvu sestavime jen pokud doslo ke zmene
+ bitBlt( m_wholeLayer, 0, 0, m_scaleLayerSmall, 0, 0, m_widthOfBackGround, m_widthOfBackGround, CopyROP); //nakopirujeme vrstvu
+ bitBlt( m_wholeLayer, 0, 0, m_pointerLayerSmall, 0, 0, m_widthOfBackGround, m_widthOfBackGround, AndROP ); //nakopirujeme rucicku
+ }
+ bitBlt( this , m_startOfBackGround, m_startOfBackGround, m_wholeLayer, 0, 0, m_widthOfBackGround, m_widthOfBackGround, CopyROP); //nakopirujeme vrstvu
+ m_showBackGround = false;
+ m_showPointer = false;
+ }
+ }
+
+
+//***************private ************************
+
+void KNutAnalog::paintBackGround ( void ) {
+ QPainter paint;
+ QImage myImage; //big image
+
+//qDebug ("KNutAnalog::paintBackGround");
+
+ m_scaleLayerBig->fill( this,0,0); //color if background
+
+ paint.begin ( m_scaleLayerBig );
+ paint.setBackgroundMode(Qt::OpaqueMode);
+ paint.setBackgroundColor(backgroundColor());
+ paintPartOfCircle(&paint, m_centerX*3, m_centerY*3,m_widthOfScale*3); //CMK pro inter
+ paintScale(&paint, m_centerX*3, m_centerY*3,m_widthOfScale*3); // Scale
+ paint.end();
+
+ myImage = m_scaleLayerBig->convertToImage();
+
+ makeMotionBlur(&myImage,myImage.pixel(1,1),m_typeOfView);
+ makeAntialiasing(&myImage,m_scaleLayerSmall,myImage.pixel(1,1),slow,m_typeOfView);
+
+ paint.begin( m_scaleLayerSmall ); // paint on layer of scale
+ // painting numbers
+ paintScaleNumbers( &paint ); //painting of numbers
+ // painting texts
+ paintText( &paint );
+ paint.end ();
+ }
+
+
+
+void KNutAnalog::paintPointer ( void ) {
+
+
+//qDebug ("KNutAnalog::paintPointer");
+ if (m_speedOfAAlias == none) paintPointerFastly (m_valueOfPointer);
+ else paintPointerSlowly ( m_valueOfPointer, m_centerX*3, m_centerY*3,m_widthOfScale*3);
+}
+
+
+void KNutAnalog::paintPointerSlowly ( double position, int centerX , int centerY, int widthOfCircle) {
+ QPainter paint;
+
+ QImage myImage; //big image
+ double angle;
+ int lengthOfPointer = widthOfCircle / 2 - 12;
+
+ if (position < m_bottomLimit) position=m_bottomLimit;
+ else {
+ if (position > m_topLimit) position = m_topLimit;
+ }
+ // painting of pointer
+ angle = ((m_angleOfViewer/(m_topLimit-m_bottomLimit))*(position-m_bottomLimit))*((-1)*m_direction)+m_startAngle;
+
+ m_pointerLayerBig->fill( Qt::white ); //color if beckground
+ paint.begin( m_pointerLayerBig ); // paints of pointer
+ paint.setBackgroundMode(Qt::TransparentMode);
+
+ paint.setBrush( m_pointerColor ); // sets color
+ paint.setPen ( m_pointerColor );
+ QPointArray pts;
+ // k posuvu a k otoceni pouziva funkce paintu
+ // for rotate and translate uses functions of paint
+ paint.translate (centerX, centerY);
+ paint.rotate(-angle);
+ pts.setPoints( 4, -6, 0, 0, -6, lengthOfPointer, 0, 0, 6 );
+ paint.drawConvexPolygon( pts );
+
+ paint.end ();
+ //m_pointerMutex.lock();
+
+ myImage = m_pointerLayerBig->convertToImage();
+
+ if (m_makeBlurMotion) makeMotionBlur(&myImage,myImage.pixel(1,1));
+ makeAntialiasing(&myImage,m_pointerLayerSmall,myImage.pixel(1,1),m_speedOfAAlias,0);
+
+ paint.begin( m_pointerLayerSmall ); // paints on layer's background
+ paintValueOfPointer ( &paint, m_valueOfPointer);
+ paint.end ();
+ // m_pointerMutex.unlock();
+ }
+
+
+
+void KNutAnalog::paintPointerFastly (double position) {
+ QPainter paint;
+ double uhel;
+
+ int delka = m_widthOfScale / 2 - 4;
+
+ //m_pointerMutex.lock();
+ m_pointerLayerSmall->fill( Qt::white ); //background color
+ paint.begin( m_pointerLayerSmall ); // kreslime na plochu rucicky
+ paint.setBackgroundMode(Qt::TransparentMode);
+ paintValueOfPointer ( &paint, m_valueOfPointer);
+
+
+ if (position < m_bottomLimit) position=m_bottomLimit;
+ else {
+ if (position > m_topLimit) position = m_topLimit;
+ }
+ /* painting of pointer*/
+ uhel = ((m_angleOfViewer/(m_topLimit-m_bottomLimit))*(position-m_bottomLimit))*((-1)*m_direction)+m_startAngle;
+
+ paint.setBrush( m_pointerColor ); // nastavime barvu
+ paint.setPen ( m_pointerColor );
+ QPointArray pts;
+ // for translate a rotate uses functions of paint // k posuvu a k otoceni pouziva funkce paintu
+ paint.translate (m_centerX, m_centerY);
+ paint.rotate(-uhel);
+ pts.setPoints( 4, -2, 0, 0, -2, delka, 0, 0, 2 );
+ paint.drawPolygon( pts );
+
+ paint.end();
+ //m_pointerMutex.unlock();
+ }
+
+
+
+void KNutAnalog::paintPartOfCircle ( QPainter *paint, int centerX , int centerY, int widthOfCircle ) {
+ double Astart, Aend;
+
+ // pocitani uhlu
+ //nula je ve 3 hodiny
+ // prirustek je kladny proti smeru hod rucicek
+
+ //int extent = m_topLimit-m_bottomLimit; //rozsah
+// double extent = m_topLimit-m_bottomLimit; //rozsah
+// double jednotka = ((double)m_angleOfViewer/extent);
+ double jednotka = ((double)m_angleOfViewer/(m_topLimit-m_bottomLimit));
+ bool painted = false;
+
+// int smerMK = (-1)*m_direction;
+ // paints parts of circle
+ for (int i=0;i<m_countOfColorParts;i++) {
+ if ((m_extentOfDye[i].start < m_topLimit) && (m_extentOfDye[i].end > m_bottomLimit)) {
+ if (m_extentOfDye[i].start < m_bottomLimit) Astart = m_bottomLimit; else Astart = m_extentOfDye[i].start;
+ if (m_extentOfDye[i].end > m_topLimit) Aend = m_topLimit; else Aend = m_extentOfDye[i].end;
+ paint->setBrush ( m_arcColors[m_extentOfDye[i].color] );
+ paint->setPen (NoPen);
+ paint->drawPie((centerX-widthOfCircle/2),(centerY-widthOfCircle/2),widthOfCircle,widthOfCircle,(int)((((Astart-m_bottomLimit)*jednotka)*((-1)*m_direction)+m_startAngle)*16),(int)(((-1)*m_direction)*((Aend-Astart)*jednotka)*16));
+ painted = true; // bylo provedeno vykresleni
+ }
+ }
+ if ((m_countOfColorParts > 0) && (painted)) { // kreslime jen pokud bylo kreslena kruhova vysec
+ // musime vybarvit stred kotouce
+ //fills center of circle
+ paint->setBrush ( paint->backgroundColor() ); //The angles are 1/16th of a degree
+ paint->drawPie((centerX-(widthOfCircle/2)+18),(centerY-(widthOfCircle/2)+18),widthOfCircle-36,widthOfCircle-36,(int)(m_startAngle*16+90*m_direction),(int)((-m_direction)*(m_angleOfViewer*16+180)));
+ }
+ }
+
+
+
+void KNutAnalog::paintScale ( QPainter *paint , int centerX , int centerY, int widthOfCircle) {
+
+ int bottomMax = widthOfCircle/2 - 29;
+ int bottom = widthOfCircle/2 -17 ;
+ int smer_stup = (-1)*m_direction;
+ paint->save();
+ paint->setPen ( m_scaleColor);
+
+ paint->translate( centerX, centerY );
+
+ double stupne = smer_stup * (m_angleOfViewer/(m_countOfParts*(m_countOfSubParts)));
+
+ // nakresleni prvni linky
+ //paints of the first line
+ paint->rotate( -m_startAngle);
+ paint->setBrush ( m_scaleColor );
+ paint->drawRect( bottomMax,-1,30,3 );
+
+ for ( int i=0; i<(m_countOfParts); i++ ) {
+ for ( int j=0; j<(m_countOfSubParts-1); j++) {
+ paint->rotate( -stupne );
+ paint->drawRect( bottom,-1,18,2 );
+ }
+ paint->rotate( -stupne );
+ paint->drawRect( bottomMax,-1,30,3 );
+ }
+ paint->restore();
+ }
+
+
+
+void KNutAnalog::makeAntialiasing (QImage* bigImage, QPixmap* smallPixmap, const QRgb colorOfBG, speedOfAAlias speed, int typeOfView) {
+ ulong imageRed, imageGreen, imageBlue;
+ QRgb imageRgb;
+ QImage* smallImage;
+ bool computeAverage;
+ ulong sumOfRed, sumOfGreen, sumOfBlue;
+
+ if (speed == slow) {
+ sumOfRed = (qRed ( colorOfBG ))*9;
+ sumOfGreen = (qGreen ( colorOfBG ))*9;
+ sumOfBlue = (qBlue ( colorOfBG ))*9;
+ }
+ else {
+ sumOfRed = (qRed ( colorOfBG ))*16;
+ sumOfGreen = (qGreen ( colorOfBG ))*16;
+ sumOfBlue = (qBlue ( colorOfBG ))*16;
+ }
+ int smallImageWidth=bigImage->width()/3;
+ int smallImageHeight=bigImage->height()/3;
+
+
+ smallImage = new QImage(smallImageWidth,smallImageHeight, bigImage->depth());
+
+// imageRgb = bigImage->pixel(1,1);
+
+ for (int x = 0; x < smallImageWidth; x++) {
+ for (int y = 0; y < smallImageHeight; y++) {
+ imageRed = 0;
+ imageGreen = 0;
+ imageBlue = 0;
+
+ switch (typeOfView) {
+ case 0:
+ //nothing
+ computeAverage=true;
+ break;
+ case 1:
+ if ((y>25) and (x >30) and (x < 92)) computeAverage=false;
+ else computeAverage=true;
+ break;
+ case 2:
+ if ((y < 15) || ((x+15) > y)) computeAverage=true;
+ else computeAverage=false;
+ break;
+ case 3:
+ //computes top part only
+ if ((y < 60) && (y>15)) computeAverage=true;
+ else computeAverage=false;
+ break;
+ default:
+ computeAverage=true;
+ }
+
+ if (speed == slow) {
+//// uses divide, slowly compute
+ if (computeAverage) {
+ for (int xi = 0 ; xi < 3; xi ++) {
+ for (int yi = 0 ; yi < 3; yi ++) {
+ imageRgb = bigImage->pixel(x*3+xi,y*3+yi);
+ imageRed += qRed ( imageRgb );
+ imageGreen += qGreen ( imageRgb );
+ imageBlue += qBlue ( imageRgb );
+ }
+ }
+ if (((imageRed == sumOfRed) && (imageGreen == sumOfGreen) && (imageBlue == sumOfBlue))) {
+ smallImage->setPixel (x,y,colorOfBG);
+ }
+ else {
+ imageRed = imageRed / 9;
+ imageGreen = imageGreen/9;
+ imageBlue = imageBlue/9;
+ smallImage->setPixel (x,y,qRgb(imageRed,imageGreen,imageBlue));
+ }
+ }
+ else {
+ smallImage->setPixel (x,y,bigImage->pixel(x*3,y*3));
+ }
+ }
+ else {
+//// uses bitmove, fastly compute
+ if (computeAverage) {
+ for (int xi = 0 ; xi < 3; xi ++) {
+ for (int yi = 0 ; yi < 3; yi ++) {
+ if ((xi == 1) && (yi == 1)) { // center of 3x3 area
+ imageRgb = bigImage->pixel(x*3+xi,y*3+yi);
+ imageRed += qRed ( imageRgb )*4;
+ imageGreen += qGreen ( imageRgb )*4;
+ imageBlue += qBlue ( imageRgb )*4;
+ }
+ else {
+ if ((xi == 1) || (yi == 1)) {
+ imageRgb = bigImage->pixel(x*3+xi,y*3+yi);
+ imageRed += qRed ( imageRgb )*2;
+ imageGreen += qGreen ( imageRgb )*2;
+ imageBlue += qBlue ( imageRgb )*2;
+ }
+ else {
+ imageRgb = bigImage->pixel(x*3+xi,y*3+yi);
+ imageRed += qRed ( imageRgb );
+ imageGreen += qGreen ( imageRgb );
+ imageBlue += qBlue ( imageRgb );
+ }
+ }
+ }
+ }
+ if ((imageRed == sumOfRed) && (imageGreen == sumOfGreen) && (imageBlue == sumOfBlue)) {
+ smallImage->setPixel (x,y,colorOfBG);
+ }
+ else {
+ imageRed = imageRed >> 4;
+ imageGreen = imageGreen >> 4;
+ imageBlue = imageBlue >> 4;
+ smallImage->setPixel (x,y,qRgb(imageRed,imageGreen,imageBlue));
+ }
+ }
+ else {
+ smallImage->setPixel (x,y,bigImage->pixel(x*3,y*3));
+ }
+ } //end of fastly
+ }
+ }
+ smallPixmap->convertFromImage(*smallImage);
+ delete smallImage;
+}
+
+
+void KNutAnalog::makeMotionBlur (QImage* image, const QRgb colorOfBG, int typeOfView) {
+
+ ulong imageRed, imageGreen, imageBlue;
+ QRgb imageRgb;
+ QImage *layerImageBlur;
+ bool computeAverage;
+ int startHeight, stopHeight;
+ ulong sumOfRed, sumOfGreen, sumOfBlue;
+
+ sumOfRed = (qRed ( colorOfBG ))*9;
+ sumOfGreen = (qGreen ( colorOfBG ))*9;
+ sumOfBlue = (qBlue ( colorOfBG ))*9;
+
+ int imageWidth=image->width();
+ int imageHeight=image->height();
+
+ layerImageBlur = new QImage(*image);
+ layerImageBlur->detach(); //costructor makes swallow copy, have to use detach
+
+
+ switch (typeOfView) {
+ case 0:
+ //nothing
+ startHeight =1;
+ stopHeight =imageHeight-2;
+ break;
+ case 2:
+ startHeight =1;
+ stopHeight =imageHeight-2;
+ break;
+ case 3:
+ startHeight =45;
+ stopHeight =180;
+ break;
+ default:
+ startHeight =1;
+ stopHeight =imageHeight-2;
+ }
+
+
+ for (int x = 1; x < imageWidth-2; x++) {
+ for (int y = startHeight; y < stopHeight; y++) {
+ imageRed = 0;
+ imageGreen = 0;
+ imageBlue = 0;
+
+ switch (typeOfView) {
+ case 0:
+ //nothing
+ computeAverage=true;
+ break;
+ case 1:
+ if ((y>75) and (x >90) and (x < 274)) computeAverage=false;
+ else computeAverage=true;
+ break;
+ case 2:
+ if ((y < 45) || ((x+45) > y)) computeAverage=true;
+ else computeAverage=false;
+ break;
+ case 3:
+ //computes top part only
+ if ((y < 180) && (y>45)) computeAverage=true;
+ else computeAverage=false;
+ break;
+ default:
+ computeAverage=true;
+ }
+
+
+ if (computeAverage) {
+ for (int xi = -1 ; xi < 2; xi ++) {
+ for (int yi = -1 ; yi < 2; yi ++) {
+ imageRgb = layerImageBlur->pixel(x+xi,y+yi);
+ imageRed += qRed ( imageRgb );
+ imageGreen += qGreen ( imageRgb );
+ imageBlue += qBlue ( imageRgb );
+ }
+ }
+
+ if (!((imageRed == sumOfRed) && (imageGreen == sumOfGreen) && (imageBlue == sumOfBlue))) {
+ imageRed = (int)(imageRed / 9);
+ imageGreen = (int)(imageGreen/9);
+ imageBlue = (int)(imageBlue/9);
+ image->setPixel (x,y,qRgb(imageRed,imageGreen,imageBlue));
+ }
+ }
+ }
+ }
+ delete layerImageBlur;
+}
+
+
+
+
+
+
+void KNutAnalog::paintScaleNumbers ( QPainter *paint ) {
+ //paintig of scaleNumbers
+
+ int poz_x, poz_y, r_vyska, r_sirka;
+ double posun, angle;
+
+ double upi = 0.0174532;
+ int smer_st = -m_direction;
+
+ paint->save(); // ulozime
+ QString cislo;
+ paint->setPen(m_textColor);
+ paint->setFont(m_scaleFont);
+
+ QFontMetrics fm = paint->fontMetrics();
+ r_vyska = ((fm.ascent()) / 2);
+ posun = ((double)(m_topLimit-m_bottomLimit))/m_countOfParts;
+ for (int i=0; i<=(m_countOfParts);i++) {
+ cislo.sprintf( "%3.0f",m_bottomLimit+i*posun);
+ cislo=cislo.stripWhiteSpace();
+ r_sirka = (fm.width(cislo))/2;
+ angle = (m_startAngle+ ((m_angleOfViewer/m_countOfParts)*i*smer_st))*upi;
+ poz_x = (int)((cos(angle)*m_radiusOfScaleNumbers+m_centerX) - r_sirka);
+ poz_y = (int)((m_centerY-sin(angle)*m_radiusOfScaleNumbers) + r_vyska);
+ paint->drawText (poz_x,poz_y,cislo);
+ }
+ paint->restore();
+ }
+
+
+void KNutAnalog::paintText ( QPainter *paint ) {
+ QString nadpis1;
+ QString nadpis2;
+ int index;
+
+ if (m_inscription.length() >1) {
+ if ((index = m_inscription.find(" ")) != -1) {
+ // mezera nalezena space found
+ nadpis1 = m_inscription.left(index);
+ nadpis2 = m_inscription.mid(index+1,(uint)(m_inscription.length() - index - 1));
+ }
+ } else index = -1;
+
+ paint->setPen(m_textColor);
+ paint->setFont(m_textFont);
+ QFontMetrics fm = paint->fontMetrics();
+ int r_vyska = fm.height()/ 2;
+ switch (m_typeOfView) {
+ // kruznice - kreslime dve radky nad sebou cemtrovane
+ case 1 :
+ if (index == -1 ) paint->drawText( m_centerX - fm.width(m_inscription)/2, 104 + r_vyska , m_inscription);
+ else {
+ // mame dve slova
+ paint->drawText( m_centerX - fm.width(nadpis1)/2, 106 + r_vyska/2 - 2, nadpis1);
+ paint->drawText( m_centerX - fm.width(nadpis2)/2, 106 + (r_vyska*3)/2 + 2, nadpis2);
+ }
+ paint->drawText( m_centerX - fm.width(AnMJ)/2, 44 + r_vyska , AnMJ);
+ break;
+ // ctvrt oblouk kreslime dve radky nad sebou centrovane v pravem hornim rohu
+ case 2 :
+ if (index == -1 ) paint->drawText( 121 - fm.width(m_inscription) , 6 + r_vyska , m_inscription);
+ else {
+ paint->drawText( 121 - fm.width(nadpis1) , 6 + r_vyska , nadpis1);
+ paint->drawText( 121 - fm.width(nadpis2) , 10 + r_vyska*2 , nadpis2);
+ }
+ paint->drawText( m_centerX , 68 + r_vyska*2 , AnMJ);
+ break;
+ // horni oblouk
+ case 3 :
+ paint->drawText( m_centerX - fm.width(m_inscription)/2, 6 + r_vyska , m_inscription);
+ paint->drawText( m_widthOfBackGround -5 -fm.width(AnMJ), m_widthOfBackGround -r_vyska, AnMJ);
+
+ break;
+ }
+ }
+
+
+
+void KNutAnalog::paintValueOfPointer ( QPainter *p, double value) {
+
+ QString cislo;
+ cislo.sprintf( "%5.1f",value);
+ cislo=cislo.stripWhiteSpace();
+
+ if (value < m_bottomLimit) value=m_bottomLimit;
+ else {
+ if (value > m_topLimit) value = m_topLimit;
+ }
+ /* nakresleni rucicky*/
+// uhel = ((uhel_zobrazeni/(horni_mez-dolni_mez))*(value-dolni_mez))*((-1)*smer)+m_startAngle;
+
+ p->setPen(m_textColor);
+ p->setFont(m_textFont);
+ QFontMetrics fm = p->fontMetrics();
+ int r_vyska = fm.height()/ 2;
+
+
+ switch (m_typeOfView) {
+ case 1 :
+ p->drawText( m_centerX - fm.width(cislo)/2, 75 + r_vyska , cislo);
+ break;
+ case 2 :
+ p->drawText( m_centerX , 57 + r_vyska , cislo);
+ break;
+ case 3 :
+ p->drawText( 5, m_widthOfBackGround -r_vyska, cislo);
+ break;
+ }
+ }
+
+
+
+#include "knutanalog.moc"
+
+
+
diff --git a/src/knutanalog.h b/src/knutanalog.h
new file mode 100644
index 0000000..b0b64f5
--- /dev/null
+++ b/src/knutanalog.h
@@ -0,0 +1,452 @@
+/***************************************************************************
+ * Copyright (C) 2007 by Daniel Prynych *
+ * Daniel.Prynych@buzuluk.cz *
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ * This program is distributed in the hope that it will be useful, *
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of *
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
+ * GNU General Public License for more details. *
+ * *
+ * You should have received a copy of the GNU General Public License *
+ * along with this program; if not, write to the *
+ * Free Software Foundation, Inc., *
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
+ ***************************************************************************/
+#ifndef KNUTANALOG_H
+#define KNUTANALOG_H
+
+#include <qframe.h>
+
+#include <qpixmap.h> // po odladeni smazat
+#include <qimage.h>
+#include <qmutex.h>
+
+
+class QPainter;
+class QFont;
+
+enum speedOfAAlias { none,fast,slow};
+
+
+/**
+ * This class shows analog measuring panels
+ *
+ * @author Daniel Prynych
+ * @short analog measuring panels
+ * @version 0.1
+*/
+
+class KNutAnalog : public QFrame {
+ Q_OBJECT
+public:
+
+
+ struct extentOfDyeDef {
+ double start,end;
+ int color;
+ };
+
+
+
+/**
+ * Construct - makes object for analog measuring panel about size 130 x 130 points
+ * Konstruktor - vytvori objekt pro analogovy merici panel o rozmerech 130 x 130 bodu
+ *
+ * When you need paint or repainr panel you have to call functiin reapaint
+ * other functions calls this function theirself, when run = true
+ * Pokud je potreba vykreslit nebo prekreslit panel je nutno zavolat funkci repaint,
+ * ostatni funkce ji zavolaji sami pokud je run = TRUE.
+ *
+ * @param bottomLimit Is bottom value of scale..
+ * @param topLimit is end value of scale.
+ * @param typeOfView determine type view of scale 1- circle 2- right part of circle, 3 - top part of circle
+ * @param countOfParts determine count of big parts (parents parts) of scale.
+ * @param countOfSubParts determine count small parts (children parts) id scale, evere big part include e few small part.
+ * @param pointerColor determine color of pointer.
+ * @param scaleColor determine color of scale.
+ * @param textColor determine color of text.
+ * @param analogFonts determine fonts for text and scale.
+ * @param qualityOfPainter determine quality painting of pointer- 0 nothing. 1 fast antialiasing, 2 slow antialiasing, 3 blur motion + fast antialiasing, 4 blur motion + slow antialiasing
+ * @since 0.3
+ **/
+ KNutAnalog(QWidget *parent = 0, const char *name = 0, int Astart = 0, int topLimit = 100, int typeOfView = 1, int countOfParts = 5, int countOfSubParts = 0, QColor pointerColor = Qt::black, QColor m_scaleColor = Qt::black, QColor textColor = Qt::black, QFont *analogFonts = 0, int qualityOfPointer = 4, bool makeBG = false );
+
+/**
+ * Destruktor
+ * @since 0.1
+ **/
+ ~KNutAnalog();
+
+
+/**
+ * Sets text for top and bottom text of panel.
+ * Nastavi text dolni a horni text na panelu.
+ *
+ * @param m_inscription determinuje inscription , bottom text , usually.
+ * @param m_inscription Udava nadpis, "dolni" text, obvykle co je mereno.
+ * @param text_up Udava mernou jednotku "horni" text, obvykle merna jednotka.
+ * @param run = TRUE makes immediately repaint of panel
+ * @param run = TRUE provede okamzite prekresleni panelu.
+ *
+ * @since 0.1
+ **/
+ void setText (QString m_inscription, QString text_up, bool run=false);
+
+
+/**
+ * Makes background of analog panel.
+ * Vytvori pozadi analogoveho panelu.
+ *
+ * @param run = TRUE makes immediately repaint of panel
+ * @param run = TRUE provede okamzite prekresleni panelu.
+ *
+ * @since 0.2
+ **/
+ void makeBackground (bool run=false);
+
+
+/**
+ * Repaint pointer of analog panel.
+ * Prekresli rucicku analogoveho panelu.
+ *
+ * @param run = TRUE makes immediately repaint of panel
+ * @param run = TRUE provede okamzite prekresleni panelu.
+ *
+ * @since 0.2
+ **/
+ void repaintPointer ( bool run );
+
+
+
+/**
+ * Nastavuje devet zakladnich barev pro mezikruzi.
+ * Sets nine basic color for circle in scale
+ *
+ * @param run = TRUE provede okamzite prekresleni panelu.
+ * @param run = TRUE makes immediately repaint of panel
+ *
+ * @since 0.1
+ **/
+ void setDefaultArcColor(bool run=false);
+
+
+/**
+ * Nastavi zakladni barvu pro mezikruzi.
+ * Sets basic color for circle in scale
+ *
+ * @param reg Poradove cislo barvy (barevneho registru).
+ * @param color Barva na kterou bude nastaven registr barvy.
+ *
+ * @since 0.1
+ **/
+ void setArcColor(int reg, QColor color );
+
+
+
+/**
+ * Vybarvi cast stupnice zadanou barvou.
+ * Nastavi rozsah mezikruzi, podle stupnice od pocatecni hodnoty do koncove hodnoty stupnice
+ * Barevne casti se barvy postupne, podel poradoveho cisla, mohou se prekryvat.
+ * Je mozno nastavit jen 5 casti !!
+ *
+ * @param startOfCircle Urcuje zazatek mezikruzi.
+ * @param endOfCircle Urcuje konec mezikruzi.
+ * @param color Urcuje barvu.
+ * @param run = TRUE makes immediately repaint of panel
+ * @param run = TRUE provede okamzite prekresleni panelu.
+ *
+ * @since 0.2
+ **/
+ void addArc (double startOfCircle, double endOfCircle, int regColor, bool run=false);
+
+
+
+/**
+ * Clear colors of scale
+ * Zrusi vybarveni stupnice.
+ *
+ * @param run = TRUE makes immediately repaint of panel
+ * @param run = TRUE provede okamzite prekresleni panelu.
+ *
+ * @since 0.1
+ **/
+ void delArc (bool run=false);
+
+
+
+/**
+ *
+ * Nastavi rozsah stupnice.
+ *
+ * @param Astart Urcuje pocatecni hodnotu stupnice.
+ * @param AEND Urcuje koncovou hodnotu stupnice.
+ * @param run = TRUE makes immediately repaint of panel
+ * @param run = TRUE provede okamzite prekresleni panelu.
+ *
+ * @since 0.2
+ */
+ void setRange (int Astart = 0, int Aend = 100, bool run=false);
+
+/**
+ * Sets number of parts od scale
+ * Nastavi pocet dilku stupnice.
+ *
+ * @param Count Determine number of parts of pointer..
+ * @param Count Urcuje pocet casti stupnice.
+ * @param run = TRUE makes immediately repaint of panel
+ * @param run = TRUE provede okamzite prekresleni panelu.
+ *
+ * @since 0.1
+ */
+ void setMember (int Count, bool run=false);
+
+/**
+ * Sets color of analog pointer.
+ * Nastavi barvu analogove rucicky.
+ *
+ * @param pointerColor determine color of pointer.
+ * @param pointerColor Urcuje barvu rucicky.
+ * @param run = TRUE makes immediately repaint of panel
+ * @param run = TRUE provede okamzite prekresleni panelu.
+ * @since 0.2
+ */
+ void setPointerColor (QColor pointerColor, bool run=false);
+
+/**
+ * sets color of text;
+ * Nastavi barvu textu.
+ *
+ * @param fontColor determine color of font.
+ * @param fontColor urcuje barvu fontu.
+ * @param run = TRUE makes immediately repaint of panel
+ * @param run = TRUE provede okamzite prekresleni panelu.
+ *
+ * @since 0.1
+ */
+ void setFontColor (QColor fontColor, bool run=false );
+
+
+
+/**
+ * Sets color of scale
+ * Nastavi barvu stupnice.
+ *
+ * @param scaleColor determine color if scale.
+ * @param scaleColor urcuje barvu stupnice.
+ * @param run = TRUE makes immediately repaint of panel
+ * @param run = TRUE provede okamzite prekresleni panelu.
+ *
+ * @since 0.1
+ */
+ void setScaleColor (QColor scaleColor, bool run=false);
+
+
+/**
+ * Sets type of digital processing of pointer. 0 nothing. 1 fast antialiasing, 2 slow antialiasing, 3 blur motion + fast antialiasing, 4 blur motion + slow antialiasing.
+ *
+ * @param qualityOfPointer determine quality of pointer's digital procesing
+ * @param run = TRUE makes immediately repaint of panel
+ * @param run = TRUE provede okamzite prekresleni panelu.
+ *
+ * @since 0.1
+ */
+ void setDigitalProcesing (int qualityOfPointer, bool run =false );
+
+
+
+/**
+ * Sets pointer on value pointerValue.
+ * Posune rucicku na hodnotu pointerValue.
+ *
+ * @param pointerValue Urcuje hodnotu na jakou bude nastavena rucicka.
+ * @param run = TRUE makes immediately repaint of panel
+ * @param run = TRUE provede okamzite prekresleni panelu.
+ *
+ * @since 0.1
+ */
+ void setPointer (double pointerValue, bool run=true );
+
+
+/**
+ * Const. determines width of analog panel in points
+ * Konstanta, udava velikost analogoveho panelu v bodech.
+ *
+ * @since 0.1
+ */
+ static const int AnalogWidth = 130;
+
+
+ public slots:
+
+/**
+ * Sets font of scale, change is doing immediately
+ * Nastavi font stupnice, zmena je provedena okamzite.
+ *
+ * @param newScaleFont Urcuje novy font hodnot stupnice.
+ * @param newScaleFont Urcuje novy font hodnot stupnice.
+ *
+ * @since 0.1
+ */
+ void slotSetScaleFont(QFont newScaleFont);
+
+
+/**
+ * Sets font of text. change is doing immediately.
+ * Nastavi font textu, zmena je provedena okamzite.
+ *
+ * @param newTextFont Urcuje novy font pro texty.
+ *
+ * @since 0.1
+ */
+ void slotSetTextFont(QFont newTextFont);
+
+
+/**
+ * Nastavi font stupnice a textu, zmena je provedena okamzite.
+ *
+ * @param newTextFont Urcuje novy font pro texty a hodnoty stupnice.
+ *
+ * @since 0.1
+ */
+ void slotSetAllFont(QFont newAllFont);
+
+
+/**
+ * Repaint layer of backgroud and layer of pointer,
+ * all panel will be repainted
+ * Da povel k prekreseni urovne pozadi a urovne rucicky.
+ * To znamena, ze bude prekreslen kompletne cely panel.
+ *
+ * @since 0.1
+ */
+ void repaintAll (void);
+
+
+ protected:
+ virtual void resizeEvent( QResizeEvent * );
+ virtual void paintEvent( QPaintEvent * );
+
+ private:
+
+
+/**
+ * @internal
+ */
+ void paintBackGround ( void );
+
+
+/**
+ * @internal
+ */
+ void paintPointer ( void );
+
+
+/**
+ * @internal
+ */
+ void paintPointerSlowly ( double position, int centerX , int centerY, int widthOfCircle);
+
+/**
+ * @internal
+ */
+ void paintPointerFastly ( double position);
+
+
+/**
+ * @internal
+ */
+ void paintPartOfCircle ( QPainter *paint, int centerX , int centerY, int widthOfCircle );
+
+
+/**
+ * @internal
+ */
+ void paintScale ( QPainter *paint , int centerX , int centerY, int widthOfCircle);
+
+
+/**
+ * @internal
+ */
+ void makeAntialiasing (QImage* myImage, QPixmap* smallPixmap, const QRgb colorOfBG, speedOfAAlias speed = slow , int typeOfView = 0);
+
+
+/**
+ * @internal
+ */
+ void makeMotionBlur (QImage* myImage, const QRgb colorOfBG, int typeOfView = 0);
+
+
+/**
+ * @internal
+ */
+ void paintScaleNumbers ( QPainter *paint );
+
+/**
+ * @internal
+ */
+ void paintText ( QPainter *paint );
+
+
+/**
+ * @internal
+ */
+ void paintValueOfPointer ( QPainter *p, double value);
+
+
+
+ static const int m_widthOfBackGround = 122;
+ static const int m_startOfBackGround = 4;
+
+ bool m_showBackGround;
+ bool m_showPointer;
+
+ int m_bottomLimit;
+ int m_topLimit;
+ int m_typeOfView; // udava typ meraku
+ int m_countOfParts; // pocet policek na stupnici
+ int m_countOfSubParts; // pocet dilku v policku na stupnici
+ QColor m_pointerColor, m_scaleColor, m_textColor; // colors of pointer, text and scale
+
+ QColor m_arcColors[9];
+ QString m_inscription;
+ QString AnMJ;
+ int m_countOfColorParts; // count of color parts on scale
+ double m_valueOfPointer; // position of pointer;
+ double m_angleOfViewer, m_startAngle; //pocatecni_uhel;
+ int m_centerX;
+ int m_centerY;
+ int m_direction;
+ int m_widthOfScale;
+ int m_radiusOfScaleNumbers;
+
+
+ speedOfAAlias m_speedOfAAlias;
+ bool m_makeBlurMotion;
+
+ QFont m_scaleFont;
+ QFont m_textFont;
+
+ QPixmap *m_wholeLayer;
+
+ QPixmap *m_backgroudLayerBig;
+
+
+ QPixmap *m_scaleLayerBig;
+ QPixmap *m_scaleLayerSmall;
+
+ QPixmap *m_pointerLayerBig;
+ QPixmap *m_pointerLayerSmall;
+
+
+ extentOfDyeDef m_extentOfDye[5];
+
+ QMutex m_pointerMutex;
+};
+
+
+#endif
diff --git a/src/knutclient.cpp b/src/knutclient.cpp
new file mode 100755
index 0000000..f7d7157
--- /dev/null
+++ b/src/knutclient.cpp
@@ -0,0 +1,1237 @@
+/***************************************************************************
+ knutclient.cpp - description
+ -------------------
+ begin : Út srp 21 19:12:20 CEST 2001
+ copyright : (C) 2001 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#include "knutupsdata.h"
+#include "knutvardata.h"
+#include "knutprefdlg.h"
+#include "knutprintupsvar.h"
+#include "knutinstcomms.h"
+#include "knutrwvar.h"
+#include "knutclient.h"
+
+#include <qdatetime.h>
+#include <qmutex.h>
+
+#include <kconfig.h>
+#include <ksimpleconfig.h>
+
+#include <kwin.h>
+
+#include <unistd.h> // for function sleep and other ...
+
+//#include <iostream>
+
+
+
+
+// const char *nameUpsVars1[] = {
+// "NONE", "UTILITY", "BATTPCT", "UPSTEMP", "ACFREQ", "LOADPCT", "AMBTEMP", "AMBHUMID","BATTVOLT","OUTVOLT",CURRENT};
+// const char *nameUpsVars2[] = {
+// "none", "input.voltage", "battery.charge", "ups.temperature", "input.frequency", "ups.load", "ambient.temperature",
+//"ambient.humidity","battery.voltage","output.voltage","output.current","battery.temperature","battery.current"};
+
+ extern const char *nameUpsVars1[];
+ extern const char *nameUpsVars2[];
+
+KNutClient::KNutClient(bool noDock, QObject* parent, const char *name) : QObject(parent, name) {
+
+ upsRecords = new KNutUpsData();
+ analogRecords = new KNutVarData();
+
+ m_upsTimer = new QTimer (this);
+ connect( m_upsTimer, SIGNAL(timeout()), SLOT(slotTimeout()) );
+
+ m_reconnectTimer = new QTimer(this);
+ connect( m_reconnectTimer, SIGNAL(timeout()), SLOT(slotReconnectTimeout()) );
+
+
+ // data for combo
+ m_listKNutEvent = new QStringList();
+
+ // init and load of configuration
+ initVars();
+
+ loadConfiguration();
+
+ if (!noDock) {
+ m_myDock = new KNutDock(&m_mainUpsInfo,&settingData,upsRecords);
+
+ m_myDock->show();
+ connect(m_myDock, SIGNAL(endApplication()), this, SLOT(slotExitApplication()));
+ connect(m_myDock, SIGNAL(activeMainWindow()), this, SLOT(slotActiveMainWindow()));
+ connect(m_myDock, SIGNAL(minimize()), this, SLOT(closeMainWindow()));
+ connect(m_myDock, SIGNAL(UPSChanged(QString)), this, SLOT(slotSetNewUPS (QString)));
+
+ connect(m_myDock, SIGNAL(preferences()),this, SLOT(slotPreferenceUps()));
+ connect(m_myDock, SIGNAL(printUPSVars()),this, SLOT(slotPrintUPSVars()));
+ connect(m_myDock, SIGNAL(instComms()),this, SLOT(slotInstComms()));
+ connect(m_myDock, SIGNAL(RWVars()),this, SLOT(slotRWVars()));
+ connect(m_myDock, SIGNAL(makeRefreshConnection()),this, SLOT(slotRefreshConnection()));
+ }
+
+ addEventString(i18n("Ready."));
+
+
+ // nastavime data pro vybranou polozku
+ // sets data for selected item
+ setActiveUpsInfo(m_mainUpsInfo.record.name);
+
+ // sets mainUpsInfo.oldState to const value KNutNet::initStatus
+ m_mainUpsInfo.oldState=KNutNet::initState;
+
+
+ //makes connect to UPS, connection is non blocking operation
+ //we have to use signal firstConnection and connectionError from KNutNet class
+ m_mainUpsInfo.upsNet = new KNutNet( m_mainUpsInfo.record.upsAddress, m_mainUpsInfo.record.upsName, m_mainUpsInfo.record.port,5,200);
+
+
+ connect(m_mainUpsInfo.upsNet, SIGNAL(firstConnection(void)),this, SLOT(slotFirstConnection(void)));
+ connect(m_mainUpsInfo.upsNet, SIGNAL(connectionError(int)),this, SLOT(slotErrorConnection(int)));
+ connect(m_mainUpsInfo.upsNet, SIGNAL(connectionClosed(void )),this, SLOT(slotConnectionClosed(void)));
+ connect(m_mainUpsInfo.upsNet, SIGNAL(tryFirstConnection(int )),this, SLOT(slotTryFirstConnection(int)));
+ connect(m_mainUpsInfo.upsNet, SIGNAL(tryRepeatFirstConnection(int )),this, SLOT(slotTryReepatFirstConnection( int )));
+
+
+// state of connection to usbd, this isn't state of knutnet
+// if (mainUpsInfo.record.upsName !="") {
+// mainUpsInfo.upsDriverState=knc::connecting;
+ // }
+ // else mainUpsInfo.upsDriverState=knc::notConnected;
+
+ // repaints the dock
+ if (m_myDock) m_myDock->clearDockValues();
+
+ if (settingData.useMainWindow == KNutVarData::mw_yes || noDock ||
+ (settingData.useMainWindow == KNutVarData::mw_auto && settingData.activatedMainWindow )) makeMainWindow ();
+
+ if (m_myDock) m_myMessMan = new KNutMessageManager(this);
+
+ //tries connecting to server
+ m_mainUpsInfo.upsDriverState=knc::connecting;
+ m_mainUpsInfo.upsNet->open();
+ }
+
+
+KNutClient::~KNutClient(void) {
+
+ if (m_myMessMan) delete m_myMessMan;
+
+ // melo by uz byt zruseno - jistota
+ if (m_myDock) { m_myDock->close(); m_myDock=0l;}
+
+ if (m_mainUpsInfo.upsNet) {
+ // melo by uz byt zruseno - jistota
+ delete m_mainUpsInfo.upsNet;
+ m_mainUpsInfo.upsNet = 0;
+ }
+ m_listKNutEvent->clear();
+ delete m_listKNutEvent;
+
+ // melo by uz byt zruseno - jistota
+ if (mainWindow) delete mainWindow;
+
+ delete upsRecords;
+ delete analogRecords;
+ }
+
+
+
+void KNutClient::slotTryFirstConnection (int maxCount) {
+//qDebug ("KNutClient::slotTryFirstConnection");
+
+//knutNet begin the first test of connection (connectToHost will be made after emiting signal tryFirstConnection )
+// repaints icon
+ if (m_myDock) m_myDock->repaintDock(true);
+ if (mainWindow) mainWindow->startConnectPB(maxCount);
+ }
+
+
+void KNutClient::slotTryReepatFirstConnection (int number ) {
+//qDebug ("KNutClient::slotTryFirstConnection");
+//knutNet begin nexts test of connection
+
+ if (mainWindow) mainWindow->setProgressConnectPB (number);
+ }
+
+
+
+void KNutClient::slotFirstConnection (void) {
+//qDebug ("sKNutClient::slotFirstConnection");
+//TCP - UDP connection to server was made
+
+ bool reconnecting = m_mainUpsInfo.reconnecting;
+
+
+ m_mainUpsInfo.reconnecting =false;
+ m_reconnectTimer->stop();
+
+ m_mainUpsInfo.nutVariables = m_mainUpsInfo.upsNet->getNutVariables();
+ m_mainUpsInfo.nutProtocol = m_mainUpsInfo.upsNet->getNutProtocol();
+
+ if (mainWindow) mainWindow->hideConnectPB();
+
+
+ // reads UPS's variables
+
+ int countRevision = 2; // pocet max opakovani po kterych muzeme zjistovat hodnoty
+ do {
+ if (!(m_mainUpsInfo.netError = m_mainUpsInfo.upsNet->getUpsVars())) break;
+ if (!(m_mainUpsInfo.netError)) break; // no error
+ if (m_mainUpsInfo.netError == KNutNet::UnknownUps) break;
+ if (m_mainUpsInfo.netError == KNutNet::DriverNotConnected) break;
+ countRevision--;
+ if (countRevision) sleep (2);
+ }
+ while (countRevision);
+
+ if (m_mainUpsInfo.netError) {
+ m_mainUpsInfo.errorUpsData=true;
+ // mainUpsInfo.upsDriverState is state of connection to usbd, this isn't state of knutnet
+ if (m_mainUpsInfo.netError == KNutNet::DriverNotConnected)
+ m_mainUpsInfo.upsDriverState=knc::notConnected;
+ else
+ m_mainUpsInfo.upsDriverState=knc::error;
+
+ if (m_myDock) m_myDock->repaintDock(true);
+ addEventString (KNutVarData::errorToText(m_mainUpsInfo.netError),m_mainUpsInfo.record.name);
+// KNutVarData::showError (mainUpsInfo.netError);
+ if ((m_myMessMan)) m_myMessMan->addMessage(KNutVarData::errorToText(m_mainUpsInfo.netError),knc::errorLevel,true);
+ }
+ else {
+
+ if (reconnecting) {
+ addEventString(i18n("The connection was renewed."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("The connection was renewed."),knc::errorLevel,true,true);
+ }
+
+
+ m_mainUpsInfo.upsDriverState=knc::connected;
+ m_mainUpsInfo.errorUpsData=false;
+
+ switch (m_mainUpsInfo.nutVariables) { // type of variables, old or new (with dot)
+ case 1:
+//qDebug ("sKNutClient::slotFirstConnection - var 1");
+ if (!(m_mainUpsInfo.upsNet->existName("BATT_RUNTIME"))) m_mainUpsInfo.runtimeVar="BATT_RUNTIME";
+ else m_mainUpsInfo.runtimeVar="RUNTIME";
+ m_mainUpsInfo.upsLoadVar="LOADPCT";
+ m_mainUpsInfo.lowxferVar="LOWXFER";
+ m_mainUpsInfo.highxferVar="HIGHXFER";
+ m_mainUpsInfo.statusVar="STATUS";
+ break;
+ case 2:
+//qDebug ("sKNutClient::slotFirstConnection - var 2");
+ m_mainUpsInfo.runtimeVar="battery.runtime";
+ m_mainUpsInfo.upsLoadVar="ups.load";
+ m_mainUpsInfo.lowxferVar="input.transfer.low";
+ m_mainUpsInfo.highxferVar="input.transfer.high";
+ m_mainUpsInfo.statusVar="ups.status";
+ }
+
+
+ if ((settingData.useDescription) && (!m_mainUpsInfo.upsNet->isDescription())) m_mainUpsInfo.upsNet->getDescription();
+ // test presunut do setActiveUpsVars
+ if (mainWindow) setActiveUpsVars(true);
+ else setActiveUpsVars(false);
+
+ // repaints main window and dock immediately
+ if (mainWindow) mainWindow->showUpsData();
+// if (myDock) myDock->repaintDock(mainUpsInfo.netError,true); // dock is repainting always
+ if (m_myDock) m_myDock->repaintDock(true); // dock is repainting always
+
+ m_panelsAreZeroing=false; // analog panels isn't setting to zero
+ }
+ if ((m_mainUpsInfo.upsNet->getState() == KNutNet::Connected) && (!m_mainUpsInfo.errorUpsData)) {
+ showStatusEvent();
+ // getUpsVars loads informations about variables, but their values too
+ m_upsTimer->start( m_mainUpsInfo.record.delay, TRUE ); // nastartujeme casovac - starts timer
+ }
+ }
+
+
+void KNutClient::slotErrorConnection (int error) {
+
+//qDebug ("KNutClient::slotErrorConnection (1)");
+
+ if (mainWindow) mainWindow->hideConnectPB();
+
+ m_mainUpsInfo.netError = error;
+ m_mainUpsInfo.errorUpsData=true;
+ if (m_mainUpsInfo.netError == KNutNet::DriverNotConnected)
+ m_mainUpsInfo.upsDriverState=knc::notConnected;
+ else
+ m_mainUpsInfo.upsDriverState=knc::error;
+ if (m_myDock) m_myDock->repaintDock(true);
+
+ if (m_mainUpsInfo.reconnecting) {
+//qDebug ("KNutClient::slotErrorConnection (2)");
+ m_mainUpsInfo.reconnectCount++;
+ if (m_mainUpsInfo.reconnectCount > countNextConnDelay) m_mainUpsInfo.reconnectCount = countNextConnDelay;
+
+ addEventString(i18n("The connection failed. The next connection will make after %1 sec.").arg(nextConnDelay[m_mainUpsInfo.reconnectCount-1]),m_mainUpsInfo.record.name);
+ m_reconnectTimer->start( nextConnDelay[m_mainUpsInfo.reconnectCount-1]*1000, TRUE ); // starts reconnect timer again
+ }
+ else {
+//qDebug ("KNutClient::slotErrorConnection (3)");
+ addEventString (KNutVarData::errorToText(m_mainUpsInfo.netError),m_mainUpsInfo.record.name);
+// KNutVarData::showError (mainUpsInfo.netError);
+ if ((m_myMessMan)) m_myMessMan->addMessage(KNutVarData::errorToText(m_mainUpsInfo.netError),knc::errorLevel,true);
+
+
+ }
+ }
+
+
+
+void KNutClient::initVars (void) {
+// Nasledujici data jsou nastavena pri natazeni konfigurace
+//Next data is setted when konfiguration is loaded
+ settingData.panelFlags = KNutFrontPanel::DefaultPanelFlags; // informace v hlavnim panelu // information in main panel
+ settingData.toolTipFlags = KNutDock::DefaultToolTipFlags; // informace v hlavnim panelu // information in main panel
+
+ m_mainUpsInfo.record.name="";
+ m_mainUpsInfo.upsNet=0L;
+ m_mainUpsInfo.netError=0; // no error zadna chyba
+ m_mainUpsInfo.name="";
+ m_mainUpsInfo.password="";
+ m_mainUpsInfo.errorUpsData=false;
+ m_mainUpsInfo.nutVariables=0;
+ m_mainUpsInfo.runtimeVar="";
+ m_mainUpsInfo.lowxferVar="";
+ m_mainUpsInfo.highxferVar="";
+ m_mainUpsInfo.statusVar="";
+ m_mainUpsInfo.upsLoadVar="";
+ m_mainUpsInfo.upsDriverState=knc::notConnected;
+ m_mainUpsInfo.reconnectCount = 1;
+ m_mainUpsInfo.reconnecting = false;
+
+ m_panelsAreZeroing=false;
+ m_lastError=0; // no error
+
+
+ mainWindow=0;
+ m_myDock=0;
+ m_myMessMan=0;
+ settingData.activatedMainWindow=false;
+ }
+
+
+ void KNutClient::loadConfiguration ( void ) {
+
+ QString groupName;
+ KNutUpsData::upsRecordDef upsData; // structure includes informations about UPS // struktura obsahuje udaje o UPS
+ QFont appFont = kapp->font(); // systemovy font pri startu
+ kapp->config()->setGroup ("");
+ settingData.areYouSure=kapp->config()->readBoolEntry("AreYouSure",FALSE);
+
+ int helpInt=kapp->config()->readNumEntry("UseMainWindow",TRUE);
+
+//std::cout << "readNumEntry " << helpInt << "--" << std::endl;
+ switch (helpInt) {
+ case 0 : settingData.useMainWindow=KNutVarData::mw_yes;break;
+ case 1 : settingData.useMainWindow=KNutVarData::mw_no;break;
+ default : settingData.useMainWindow=KNutVarData::mw_auto;break;
+ }
+
+
+ settingData.useMessageWindow=kapp->config()->readBoolEntry("UseMessageWindow",FALSE);
+ settingData.activatedMainWindow=kapp->config()->readBoolEntry("PreviousMainWindow",FALSE);
+ settingData.x=kapp->config()->readNumEntry("PosX",0);
+ settingData.y=kapp->config()->readNumEntry("PosY",0);
+ settingData.width=kapp->config()->readNumEntry("Width",300);
+ settingData.height=kapp->config()->readNumEntry("Height",200);
+ settingData.useDescription=kapp->config()->readBoolEntry("UseDescription",FALSE);
+ settingData.countCols=kapp->config()->readNumEntry("NumberOfCols",knc::DefaultCountCols);
+ settingData.panelFlags=kapp->config()->readUnsignedNumEntry("PanelFlags",KNutFrontPanel::DefaultPanelFlags);
+ settingData.inputFrequency=kapp->config()->readNumEntry("InputFrequency",knc::DefaultInputFrequency);
+ settingData.inputVoltage=kapp->config()->readNumEntry("InputVoltage",knc::DefaultInputVoltage);
+ settingData.lowHighXfer=kapp->config()->readBoolEntry("LowHighXfer",FALSE);
+ settingData.customFont=kapp->config()->readBoolEntry("CustomFont",FALSE);
+ settingData.aPanelFont=kapp->config()->readFontEntry("AnalogPanelFont",&appFont);
+ settingData.mPanelFont=kapp->config()->readFontEntry("MainPanelFont",&appFont);
+ int upsCount=kapp->config()->readNumEntry("NumberOfUpsRecords",0);
+ settingData.customBColor=kapp->config()->readBoolEntry("CustomBColor",FALSE);
+ settingData.mainBackgroundColor=kapp->config()->readColorEntry ("MainBackGroundColor",& DEFAULT_BG_COLOR);
+ settingData.customBPanelColor=kapp->config()->readBoolEntry("CustomBPanelColor",FALSE);
+ settingData.customBAnalogColor=kapp->config()->readBoolEntry("CustomBAnalogColor",FALSE);
+ settingData.customOAnalogColor=kapp->config()->readBoolEntry("CustomOAnalogColor",FALSE);
+ settingData.mPanelBackgroundColor=kapp->config()->readColorEntry ("MPanelBackGroundColor",& DEFAULT_BG_COLOR);
+ settingData.aPanelBackgroundColor=kapp->config()->readColorEntry ("APanelBackGroundColor",& DEFAULT_BG_COLOR);
+ settingData.analogFingerColor=kapp->config()->readColorEntry ("AnalogFingerColor",& DEFAULT_FINGER_COLOR);
+ settingData.analogOKColor=kapp->config()->readColorEntry ("AnalogOKColor",& DEFAULT_OK_COLOR);
+ settingData.analogWarnningColor=kapp->config()->readColorEntry ("AnalogWarnningColor",& DEFAULT_WARNNING_COLOR);
+ settingData.analogErrorColor=kapp->config()->readColorEntry ("AnalogErrorColor",& DEFAULT_ERROR_COLOR);
+ settingData.analogScaleColor=kapp->config()->readColorEntry ("AnalogScaleColor",& DEFAULT_SCALE_COLOR);
+ settingData.analogFontColor=kapp->config()->readColorEntry ("AnalogFontColor",& DEFAULT_FONT_COLOR);
+ settingData.toolTipFlags=kapp->config()->readUnsignedNumEntry("ToolTipFlags",KNutDock::DefaultToolTipFlags);
+ settingData.customKIconColor=kapp->config()->readBoolEntry("CustomKIconColor",FALSE);
+ settingData.kIconBackgroundColor=kapp->config()->readColorEntry ("KIconBackGroundColor",& DEFAULT_KICON_COLOR);
+ settingData.typeOfKIcon=kapp->config()->readBoolEntry("TypeOfKIcon", KNutDock::pictureKI);
+ settingData.typeDigitalProcessing=kapp->config()->readNumEntry("DigitalProcessingOfPointers", 2);
+
+
+ m_mainUpsInfo.record.name=kapp->config()->readEntry("ActiveUps","");
+
+
+ for (int i = 0; i < upsCount; i++) {
+ groupName.sprintf ("UPS %d",i);
+ kapp->config()->setGroup (groupName);
+ if ((upsData.name = kapp->config()->readEntry ("Name")) != QChar::null) {
+ // record exist, we will go next part
+ //if ActiveUps is empty, we use name of first ups from ups list
+ if ((m_mainUpsInfo.record.name.isEmpty()) && (!(upsData.name.isEmpty())))
+ m_mainUpsInfo.record.name = upsData.name;
+ upsData.upsName = kapp->config()->readEntry ("UpsName","");
+ if (((upsData.upsAddress = kapp->config()->readEntry ("UpsAddress")) != QChar::null)
+ || (( upsData.upsAddress == QChar::null) && (upsData.upsName != QChar::null ))) {
+
+ // only for backwards compatibility with older release then 0.7
+ if (upsData.upsAddress.isEmpty()) {
+ int charPos;
+ if ((charPos=upsData.upsName.find('@')) == -1) {
+ upsData.upsAddress=upsData.upsName;
+ upsData.upsName="";
+ }
+ else {
+ upsData.upsAddress=upsData.upsName.mid(charPos+1);
+ upsData.upsName=upsData.upsName.left(charPos);
+ }
+ }
+ // zaznam existuje pokracujeme dale a nacteme zbytek hodnotet
+ // record exists, we go next and will read rest of values
+ upsData.delay = kapp->config()->readNumEntry("Delay",knc::DefaultDelay);
+ upsData.port = (unsigned short)kapp->config()->readNumEntry("Port",knc::DefaultPort);
+ upsData.userName=kapp->config()->readEntry("UserName","");
+ upsData.password=kapp->config()->readEntry("Password","");
+ upsData.savePassword=kapp->config()->readBoolEntry("SavePassword",false);
+ for (int j=0; j < knc::NumberOfVars; j++) {
+ groupName.sprintf ("Var %d",j);
+ upsData.upsVarCode[j]=kapp->config()->readNumEntry (groupName,0);
+ if ((upsData.upsVarCode[j] < 0) || (upsData.upsVarCode[j] > knc::NumberOfTypes))
+ upsData.upsVarCode[j] = 0;
+ }
+ upsRecords->add (upsData);
+ }
+ }
+ }
+ }
+
+void KNutClient::saveConfiguration ( bool all ) {
+ QString groupName;
+ QString codeName;
+ KNutUpsData::upsRecordDef upsData; // struktura obsahuje udaje o UPS // structure includes information about UPS
+ int upsCount = upsRecords->getCount();
+
+ kapp->config()->setGroup ("");
+
+ if (all) {
+ kapp->config()->writeEntry ("DigitalProcessingOfPointers",settingData.typeDigitalProcessing);
+ kapp->config()->writeEntry ("TypeOfKIcon",settingData.typeOfKIcon);
+ kapp->config()->writeEntry ("KIconBackGroundColor",settingData.kIconBackgroundColor);
+ kapp->config()->writeEntry ("CustomKIconColor",(settingData.customKIconColor));
+ kapp->config()->writeEntry ("ToolTipFlags",(settingData.toolTipFlags));
+ }
+
+ //if name of active ups isn't knowly, will use name of the firt ups from ups list
+ if ((m_mainUpsInfo.record.name.isEmpty()) && (upsCount > 0)) {
+ upsRecords->get(0,upsData);
+ kapp->config()->writeEntry ("ActiveUps",upsData.name);
+ }
+ else kapp->config()->writeEntry ("ActiveUps",(QString)m_mainUpsInfo.record.name); //
+
+ if (all) {
+ kapp->config()->writeEntry ("AnalogFontColor",settingData.analogFontColor);
+ kapp->config()->writeEntry ("AnalogScaleColor",settingData.analogScaleColor);
+ kapp->config()->writeEntry ("AnalogErrorColor",settingData.analogErrorColor);
+ kapp->config()->writeEntry ("AnalogWarnningColor",settingData.analogWarnningColor);
+ kapp->config()->writeEntry ("AnalogOKColor",settingData.analogOKColor);
+ kapp->config()->writeEntry ("AnalogFingerColor",settingData.analogFingerColor);
+ kapp->config()->writeEntry ("APanelBackGroundColor",settingData.aPanelBackgroundColor);
+ kapp->config()->writeEntry ("MPanelBackGroundColor",settingData.mPanelBackgroundColor);
+ kapp->config()->writeEntry ("MainBackGroundColor",settingData.mainBackgroundColor);
+ kapp->config()->writeEntry ("NumberOfUpsRecords",upsCount);
+ kapp->config()->writeEntry ("CustomFont",settingData.customFont);
+ kapp->config()->writeEntry ("AnalogPanelFont",settingData.aPanelFont);
+ kapp->config()->writeEntry ("MainPanelFont",settingData.mPanelFont);
+ kapp->config()->writeEntry ("CustomBColor",(settingData.customBColor));
+ kapp->config()->writeEntry ("CustomBPanelColor",(settingData.customBPanelColor));
+ kapp->config()->writeEntry ("CustomBAnalogColor",(settingData.customBAnalogColor));
+ kapp->config()->writeEntry ("CustomOAnalogColor",(settingData.customOAnalogColor));
+ kapp->config()->writeEntry ("LowHighXfer",(settingData.lowHighXfer));
+ kapp->config()->writeEntry ("InputVoltage",(settingData.inputVoltage));
+ kapp->config()->writeEntry ("InputFrequency",(settingData.inputFrequency));
+ kapp->config()->writeEntry ("PanelFlags",(settingData.panelFlags | 3));
+ kapp->config()->writeEntry ("NumberOfCols",settingData.countCols);
+ kapp->config()->writeEntry ("UseDescription",settingData.useDescription);
+ kapp->config()->writeEntry ("AreYouSure",settingData.areYouSure);
+ kapp->config()->writeEntry ("UseMainWindow",settingData.useMainWindow);
+ kapp->config()->writeEntry ("UseMessageWindow",settingData.useMessageWindow);
+ }
+
+ kapp->config()->writeEntry ("Height",settingData.height); //
+ kapp->config()->writeEntry ("Width",settingData.width); //
+ kapp->config()->writeEntry ("PosY",settingData.y); //
+ kapp->config()->writeEntry ("PosX",settingData.x); //
+ kapp->config()->writeEntry ("PreviousMainWindow",settingData.activatedMainWindow);
+
+ if (all) {
+ for (int i=0; i<upsCount; i++) {
+ groupName.sprintf ("UPS %d",i);
+ kapp->config()->setGroup (groupName);
+ upsRecords->get(i,upsData);
+ kapp->config()->writeEntry ("Port",upsData.port);
+ kapp->config()->writeEntry ("Delay",upsData.delay);
+ kapp->config()->writeEntry ("UpsAddress",upsData.upsAddress);
+ kapp->config()->writeEntry ("UpsName",upsData.upsName);
+ kapp->config()->writeEntry ("Name",upsData.name);
+ if (upsData.savePassword) {
+ kapp->config()->writeEntry ("UserName",upsData.userName);
+ kapp->config()->writeEntry ("Password",upsData.password);
+ }
+ kapp->config()->writeEntry ("SavePassword",upsData.savePassword);
+ for (int j=0; j < knc::NumberOfVars; j++) {
+ groupName.sprintf ("Var %d",j);
+ kapp->config()->writeEntry (groupName,upsData.upsVarCode[j]);
+ }
+ kapp->config()->setGroup ("");
+ }
+ }
+ kapp->config()->sync();
+ }
+
+
+bool KNutClient::commitData (QSessionManager&) {
+
+ saveConfiguration(false);
+ return true;
+ }
+
+ bool KNutClient::saveState (QSessionManager&) {
+
+ saveConfiguration(false);
+ return true;
+ }
+
+
+
+void KNutClient::upsActivate (void) {
+
+//qDebug ("KNutClient::upsActivate");
+
+ m_mainUpsInfo.upsNet = new KNutNet( m_mainUpsInfo.record.upsAddress,m_mainUpsInfo.record.upsName,m_mainUpsInfo.record.port,0,1);
+ if (m_mainUpsInfo.upsNet->getState() != KNutNet::Connected) {
+ m_mainUpsInfo.netError=m_mainUpsInfo.upsNet->getError(); // aktivace ups skoncila s chybou
+// KNutVarData::showError(mainUpsInfo.netError);
+
+ if ((m_myMessMan)) m_myMessMan->addMessage(KNutVarData::errorToText(m_mainUpsInfo.netError),knc::errorLevel,true);
+
+
+ m_mainUpsInfo.errorUpsData=true;
+ m_mainUpsInfo.upsDriverState=knc::notConnected;
+ }
+ else {
+ if (m_mainUpsInfo.upsNet->switchedToTCP())
+ addEventString (i18n("upsd > 1.2 doesn't support UDP. Connection is switched to TCP"),m_mainUpsInfo.record.name);
+ m_mainUpsInfo.nutVariables = m_mainUpsInfo.upsNet->getNutVariables();
+ m_mainUpsInfo.nutProtocol = m_mainUpsInfo.upsNet->getNutProtocol();
+
+ int countRevision = 2; // pocet max opakovani po kterych muzeme zjistovat hodnoty
+ do {
+ if (!(m_mainUpsInfo.netError = m_mainUpsInfo.upsNet->getUpsVars())) break;
+ if (m_mainUpsInfo.netError == KNutNet::UnknownUps) break;
+ if (m_mainUpsInfo.netError == KNutNet::DriverNotConnected) break;
+ countRevision--;
+ if (countRevision) sleep (2);
+ }
+ while (countRevision);
+
+ if (m_mainUpsInfo.netError) {
+ addEventString (KNutVarData::errorToText(m_mainUpsInfo.netError),m_mainUpsInfo.record.name);
+// KNutVarData::showError (mainUpsInfo.netError);
+
+ if ((m_myMessMan)) m_myMessMan->addMessage(KNutVarData::errorToText(m_mainUpsInfo.netError),knc::errorLevel,true);
+
+ m_mainUpsInfo.errorUpsData=true;
+ if (m_mainUpsInfo.netError == KNutNet::DriverNotConnected)
+ m_mainUpsInfo.upsDriverState=knc::notConnected;
+ else
+ m_mainUpsInfo.upsDriverState=knc::error;
+ }
+ else {
+ m_mainUpsInfo.upsDriverState=knc::connected;
+
+ switch (m_mainUpsInfo.nutVariables) {
+ case 1:
+ if (!(m_mainUpsInfo.upsNet->existName("BATT_RUNTIME"))) m_mainUpsInfo.runtimeVar="BATT_RUNTIME";
+ else m_mainUpsInfo.runtimeVar="RUNTIME";
+ m_mainUpsInfo.upsLoadVar="LOADPCT";
+ m_mainUpsInfo.lowxferVar="LOWXFER";
+ m_mainUpsInfo.highxferVar="HIGHXFER";
+ m_mainUpsInfo.statusVar="STATUS";
+ break;
+ case 2:
+ m_mainUpsInfo.runtimeVar="battery.runtime";
+ m_mainUpsInfo.upsLoadVar="ups.load";
+ m_mainUpsInfo.lowxferVar="input.transfer.low";
+ m_mainUpsInfo.highxferVar="input.transfer.high";
+ m_mainUpsInfo.statusVar="ups.status";
+ }
+
+ if ((settingData.useDescription) && (!m_mainUpsInfo.upsNet->isDescription())) m_mainUpsInfo.upsNet->getDescription();
+ // test presunut do setActiveUpsVars
+ if (mainWindow) setActiveUpsVars(true);
+ else setActiveUpsVars(false);
+ }
+ }
+ }
+
+void KNutClient::upsDeactivate (void) {
+
+ // this function isn't interuptable function
+// upsDeactivateMutex.lock();
+ QMutexLocker upsDeactivateLocker( &m_upsDeactivateMutex );
+ m_mainUpsInfo.upsNet->close(); // close connection
+ // state of connection to usbd, this isn't state of knutnet
+ m_mainUpsInfo.upsDriverState=knc::notConnected;
+ m_mainUpsInfo.netError=0; // no error
+ m_mainUpsInfo.nutVariables=0;
+// upsDeactivateMutex.unlock();
+ }
+
+void KNutClient::setActiveUpsVars (bool mWindow) {
+ // nastavujeme jen pokud existuji nejake promene
+ if ( m_mainUpsInfo.upsNet->readNumberVars() > 0) {
+ // deaktivujeme veskere promene
+ m_mainUpsInfo.upsNet->unSetActivateAll();
+
+ if (mWindow) {
+ for (int j=0; j < knc::NumberOfVars; j++) {
+ switch (m_mainUpsInfo.nutVariables) {
+ case 1:
+ if (m_mainUpsInfo.record.upsVarCode[j] != 0 ) m_mainUpsInfo.upsNet->setActivate(nameUpsVars1[m_mainUpsInfo.record.upsVarCode[j]]);
+ break;
+ case 2:
+ if (m_mainUpsInfo.record.upsVarCode[j] != 0 ) m_mainUpsInfo.upsNet->setActivate(nameUpsVars2[m_mainUpsInfo.record.upsVarCode[j]]);
+ break;
+ }
+ }
+ }
+ m_mainUpsInfo.upsNet->setActivate(m_mainUpsInfo.runtimeVar); //runtime je vzdy pridano v merenym polozkam
+ if (m_myDock) m_mainUpsInfo.upsNet->setActivate(m_mainUpsInfo.upsLoadVar);
+ // status se nastavi vzdy
+ m_mainUpsInfo.upsNet->setActivate(m_mainUpsInfo.statusVar);
+ // xfer se nastavi vzdy pokud existuje
+ // podrebujeme ho znat jeste pred startem a pak behen behu programu
+ setActiveXFerVars(true);
+ }
+ }
+
+
+void KNutClient::setActiveXFerVars (bool activate) {
+ if (activate) {
+ // podkud neexistuje jedna z promenych neaktivujeme ani jednu
+ if (!(m_mainUpsInfo.upsNet->setActivate(m_mainUpsInfo.lowxferVar)))
+ if (m_mainUpsInfo.upsNet->setActivate(m_mainUpsInfo.highxferVar))
+ m_mainUpsInfo.upsNet->unSetActivate(m_mainUpsInfo.lowxferVar);
+ }
+ else {
+ m_mainUpsInfo.upsNet->unSetActivate(m_mainUpsInfo.lowxferVar);
+ m_mainUpsInfo.upsNet->unSetActivate(m_mainUpsInfo.highxferVar);
+ }
+ }
+
+void KNutClient::setActiveUpsInfo (QString name) {
+ //presuneme jmena z databaze ups-ek - je nahrana z config. souboru
+ KNutUpsData::upsRecordDef* upsRecordPointer;
+
+ if ((!name.isNull()) && (!name.isEmpty()) && ((upsRecordPointer = upsRecords->findName(name)) != 0L)) {
+
+ m_mainUpsInfo.record.upsName = upsRecordPointer->upsName;
+ m_mainUpsInfo.record.upsAddress = upsRecordPointer->upsAddress;
+ m_mainUpsInfo.record.delay = upsRecordPointer->delay;
+ m_mainUpsInfo.record.port = upsRecordPointer->port;
+// mainUpsInfo.record.tcp = upsRecordPointer->tcp;
+ m_mainUpsInfo.record.userName = upsRecordPointer->userName;
+ m_mainUpsInfo.record.password = upsRecordPointer->password;
+ for (int i =0; i < knc::NumberOfVars; i++) m_mainUpsInfo.record.upsVarCode[i] = 0; // vynulujeme polozky
+ int ii = 0;
+ for (int i =0; i < knc::NumberOfVars; i++)
+ if (upsRecordPointer->upsVarCode[i]>0) m_mainUpsInfo.record.upsVarCode[ii++] = upsRecordPointer->upsVarCode[i];
+ }
+ }
+
+
+void KNutClient::getUpsData (void) {
+ int runNetError;
+
+//qDebug("KNutClient::getUpsData");
+
+ //loads values for selected variables <getUpsValues(false)> / activate values
+ if (!(runNetError=m_mainUpsInfo.upsNet->getUpsValues(false))) { // data from upsNet is ok
+ // we read all values of UPS
+ // nacetli jsme vsechny hodnoty pro ups
+ m_mainUpsInfo.netError=runNetError;
+ if (m_mainUpsInfo.errorUpsData) { // changes status from error to ok
+ m_mainUpsInfo.errorUpsData=false;
+ addEventString (i18n("Data OK"),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("Data OK"),knc::errorLevel,true,true);
+ }
+ }
+ else { // data from upsNet isn't ok
+ m_mainUpsInfo.netError=runNetError;
+ if (!m_mainUpsInfo.errorUpsData) { //change status from ok to error
+ addEventString (KNutVarData::errorToText(runNetError), m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(KNutVarData::errorToText(runNetError),knc::errorLevel);
+ m_lastError=runNetError;
+ m_mainUpsInfo.errorUpsData=true;
+ }
+ else {
+ if (m_lastError != runNetError) { // change status from error to other error
+ addEventString (KNutVarData::errorToText(runNetError),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(KNutVarData::errorToText(runNetError),knc::errorLevel);
+ m_lastError=runNetError;
+ }
+ }
+ }
+ }
+
+
+void KNutClient::addEventString (const QString text, const QString UPSAddress) {
+
+ if (mainWindow)
+ mainWindow->addComboStatusItem (text,UPSAddress);
+ else
+ {
+ QString dateTime(QDate::currentDate().toString());
+ dateTime +=" " + QTime::currentTime().toString();
+ if (UPSAddress.isEmpty()) m_listKNutEvent->append(dateTime+" "+text);
+ else m_listKNutEvent->append(dateTime+" "+UPSAddress+" : "+text);
+ if (m_listKNutEvent->count() > knc::maxCountKNutEvent) m_listKNutEvent->remove(m_listKNutEvent->begin());
+ }
+ }
+
+/*********************************************************************************************/
+/* */
+/* PRIVATE SLOTS */
+/* */
+/*********************************************************************************************/
+
+
+void KNutClient::slotReconnectTimeout (void) {
+
+ m_mainUpsInfo.netError=0; //clears netError
+ m_mainUpsInfo.upsDriverState=knc::connecting;
+ m_mainUpsInfo.upsNet->open();
+ }
+
+
+
+void KNutClient::slotTimeout (void) {
+
+ getUpsData();
+ if (!m_mainUpsInfo.errorUpsData) { // no error
+ if (mainWindow) {
+ mainWindow->repaintPanel();
+ mainWindow->repaintAnalogs();
+ }
+ m_panelsAreZeroing=false;
+ showStatusEvent();
+ }
+ else { // error
+ if ((mainWindow) && (!m_panelsAreZeroing)) mainWindow->zeroingPanels();
+ m_panelsAreZeroing=true;
+ if (m_myDock) m_myDock->clearDockValues();
+ }
+ if (m_myDock) m_myDock->repaintDock();
+ m_upsTimer->start( m_mainUpsInfo.record.delay, TRUE ); // nastartujem znovu
+ }
+
+
+void KNutClient::slotConnectionClosed(void) {
+//qDebug("KNutClient::slotConnectionClosed");
+
+ m_mainUpsInfo.netError = KNutNet::ConnetionClosedByServer;
+
+ m_upsTimer->stop();
+ upsDeactivate();
+ //sets netError this, because procedure upsDeactivate sets netError to zero
+ m_mainUpsInfo.netError = KNutNet::ConnetionClosedByServer;
+
+ if (mainWindow) {
+ mainWindow->hideConnectPB();
+ mainWindow->cleanPanels();
+ }
+ if (m_myDock) {
+ // clears values of dock and set standard icon of dock
+ m_myDock->clearDockValues();
+ }
+
+ addEventString(i18n("The connection was closed by the second side (upsd)."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("The connection was closed by the second side (upsd)."),knc::errorLevel,true);
+
+ m_mainUpsInfo.reconnecting = true;
+ m_mainUpsInfo.reconnectCount = 1;
+ m_reconnectTimer->start( nextConnDelay[0]*1000, TRUE ); // start timer for reconnect delay
+ }
+
+void KNutClient::showStatusEvent(void) {
+
+
+//qDebug ("KNutClient::showStatusEvent");
+ int myState = m_mainUpsInfo.upsNet->readStatus();
+ if (myState != m_mainUpsInfo.oldState) {
+
+ if ((myState & KNutNet::OFF) != (m_mainUpsInfo.oldState & KNutNet::OFF)) {
+ if (myState & KNutNet::OFF) {
+ addEventString(i18n("UPS is off."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("UPS is off."),knc::criticalLevel);
+ }
+ else {
+ addEventString(i18n("UPS is back on."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("UPS is back on."),knc::criticalLevel,true);
+ }
+ }
+ if ((myState & KNutNet::OL) != (m_mainUpsInfo.oldState & KNutNet::OL)){
+ if (myState & KNutNet::OL) {
+ addEventString(i18n("Power is back online."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("Power is back online."),knc::warningLevel,true);
+ }
+ }
+ if ((myState & KNutNet::OB) != (m_mainUpsInfo.oldState & KNutNet::OB)) {
+ if (myState & KNutNet::OB) {
+ addEventString(i18n("UPS is on battery."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("UPS is on battery."),knc::warningLevel);
+ }
+ }
+ if ((myState & KNutNet::LB) != (m_mainUpsInfo.oldState & KNutNet::LB)) {
+ if (myState & KNutNet::LB) {
+ addEventString(i18n("UPS battery is low."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("UPS battery is low."),knc::criticalLevel);
+ }
+ else {
+ addEventString(i18n("UPS battery is OK."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("UPS battery is OK."),knc::criticalLevel,true);
+ }
+ }
+ if ((myState & KNutNet::RB) != (m_mainUpsInfo.oldState & KNutNet::RB)) {
+ if (myState & KNutNet::RB) {
+ addEventString(i18n("UPS battery is bad and needs be replaced."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("UPS battery is bad and needs be replaced."),knc::infoLevel);
+ }
+ }
+ if ((myState & KNutNet::OVER) != (m_mainUpsInfo.oldState & KNutNet::OVER)) {
+ if (myState & KNutNet::OVER) {
+ addEventString(i18n("UPS is overloaded."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("UPS is overloaded."),knc::lowWarningLevel);
+ }
+ else {
+ addEventString(i18n("UPS isn't overloaded."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("UPS isn't overloaded."),knc::lowWarningLevel,true);
+ }
+ }
+ if ((myState & KNutNet::CAL) != (m_mainUpsInfo.oldState & KNutNet::CAL)) {
+ if (myState & KNutNet::CAL) {
+ addEventString(i18n("UPS is performing calibration")+".",m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("UPS is performing calibration")+".",knc::infoLevel);
+ }
+ else {
+ addEventString(i18n("Calibration of UPS is ended."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("Calibration of UPS is ended."),knc::infoLevel,true);
+ }
+ }
+ if ((myState & KNutNet::BOOST) != (m_mainUpsInfo.oldState & KNutNet::BOOST)) {
+ if (myState & KNutNet::BOOST) {
+ addEventString(i18n("UPS is boosting incoming voltage."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("UPS is boosting incoming voltage."),knc::infoLevel);
+ }
+ else {
+ addEventString(i18n("Boosting of UPS is ended."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("Boosting of UPS is ended."),knc::infoLevel,true);
+ }
+ }
+ if ((myState & KNutNet::TRIM) != (m_mainUpsInfo.oldState & KNutNet::TRIM)) {
+ if (myState & KNutNet::TRIM) {
+ addEventString(i18n("UPS is trimming incoming voltage."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("UPS is trimming incoming voltage."),knc::infoLevel);
+ }
+ else {
+ addEventString(i18n("Trimming of UPS is ended."),m_mainUpsInfo.record.name);
+ if ((m_myMessMan) and (settingData.useMessageWindow)) m_myMessMan->addMessage(i18n("Trimming of UPS is ended."),knc::infoLevel,true);
+ }
+ }
+ m_mainUpsInfo.oldState=myState;
+ }
+ }
+
+void KNutClient::slotSetNewUPS (QString name) {
+
+ m_mainUpsInfo.reconnecting =false;
+ m_reconnectTimer->stop();
+
+ if (name != m_mainUpsInfo.record.name) {
+ m_upsTimer->stop();
+ upsDeactivate();
+
+ addEventString(i18n("Switched"),name);
+ if (m_myMessMan) m_myMessMan->deleteMessage();
+
+ m_mainUpsInfo.record.name=name;
+ m_mainUpsInfo.errorUpsData=false;
+ setActiveUpsInfo(m_mainUpsInfo.record.name);
+
+ //new connection name and password are cleaned
+ m_mainUpsInfo.name = "";
+ m_mainUpsInfo.password = "";
+
+ if (mainWindow) {
+ mainWindow->setCombo(name);
+// mainWindow->showUpsData();
+ mainWindow->cleanPanels();
+ }
+
+ if (m_myDock) {
+ // clears values of dock and set standard icon of dock
+ m_myDock->clearDockValues();
+ m_myDock->setNewUPS(); // sets miniIcon in list of UPSes for selected UPS
+ }
+
+ m_panelsAreZeroing=false;
+ m_lastError=0; // zadna chyba
+ m_mainUpsInfo.oldState=KNutNet::initState; // init variable of last UPS state
+
+ // nova cast
+
+ m_mainUpsInfo.upsNet->newUPS(m_mainUpsInfo.record.upsAddress,m_mainUpsInfo.record.upsName, m_mainUpsInfo.record.port);
+ // state of connection to usbd, this isn't state of knutnet
+ m_mainUpsInfo.upsDriverState=knc::connecting;
+ m_mainUpsInfo.upsNet->open();
+ }
+ }
+
+
+void KNutClient::slotPreferenceUps (void) {
+
+ KNutPrefDlg* prefDlg = new KNutPrefDlg ( upsRecords, analogRecords, &settingData, m_mainUpsInfo.record.name ); // aktivujeme dialog pro preference
+ connect (prefDlg,SIGNAL(signalChangeConfig(unsigned int)),this,SLOT(slotSetConfig(unsigned int)));
+ prefDlg->exec();
+ delete prefDlg;
+ }
+
+
+void KNutClient::slotSetConfig (unsigned int changeSetting) {
+
+ if (changeSetting) {
+ // cely blok konfiguraci ukladame jen zde // all block of configurations is saved only here
+ saveConfiguration(true);
+ if (changeSetting & KNutPrefDlg::ChangeXFer) {
+ if (settingData.lowHighXfer)
+ setActiveXFerVars(false);
+ else
+ setActiveXFerVars(true);
+ }
+
+ if (changeSetting & KNutPrefDlg::ChangeUpsSetting) {
+ //we have changed active UPS
+//********** same code like code into slotSetNewUPS -- stejny kod jako v slotSetNewUPS
+ m_upsTimer->stop();
+ upsDeactivate();
+
+ if (m_mainUpsInfo.record.name == "") {
+ // the first record was added, because the first UPS is active UPS always
+ QString name = upsRecords->getName(0);
+ addEventString(i18n("Switched"),name);
+ m_mainUpsInfo.record.name=name;
+ m_mainUpsInfo.errorUpsData=false;
+ m_myMessMan->deleteMessage();
+ saveConfiguration(false); // saves information of new/first active UPS
+ }
+ else {
+ if (upsRecords->getCount() == 0) {
+ // the last record was deleted, because the last UPS is active UPS
+ addEventString(i18n("Switched"),"");
+ m_mainUpsInfo.record.name="";
+ m_mainUpsInfo.errorUpsData=false;
+ m_mainUpsInfo.record.upsName = "";
+ m_mainUpsInfo.record.upsAddress = "";
+ m_myMessMan->deleteMessage();
+ saveConfiguration(false); // saves information of no UPS, list of UPS is empty
+ }
+ }
+ setActiveUpsInfo(m_mainUpsInfo.record.name);
+// upsActivate();
+// getUpsData(); // provedeme hned natazeni zbytku promenych oby se nastavili meraky
+ // protoze UPS byla odpojena a znovu pripojena
+ // zde je nutno hned provest prekresleni
+ // showUpsData je nutno udelat take proto ze se mohl zmenit vyber meraku
+// if (mainWindow) mainWindow->showUpsData();
+ if (mainWindow) mainWindow->cleanPanels();
+// if (myDock) myDock->repaintDock(mainUpsInfo.netError);
+ if (m_myDock) m_myDock->clearDockValues();
+
+ m_mainUpsInfo.upsNet->newUPS(m_mainUpsInfo.record.upsAddress,m_mainUpsInfo.record.upsName, m_mainUpsInfo.record.port);
+ // state of connection to usbd, this isn't state of knutnet
+ m_mainUpsInfo.upsDriverState=knc::connecting;
+ m_mainUpsInfo.upsNet->open();
+// if ((mainUpsInfo.upsNet->getState() == KNutNet::Connected) && (!mainUpsInfo.errorUpsData)) {
+// showStatusEvent();
+// upsTimer->start( mainUpsInfo.record.delay, TRUE ); // nastartujeme casovac
+// }
+ }
+
+ if (changeSetting & KNutPrefDlg::ChangeUpsCount) {
+ if (m_myDock) m_myDock->changeUps();
+ }
+
+ if (changeSetting & KNutPrefDlg::ChangeTypeOfKIcon) {
+ if (m_myDock) m_myDock->changeKIcon();
+ }
+
+ if (changeSetting & KNutPrefDlg::ChangeCustomKIconColor) {
+ if (m_myDock) m_myDock->changeKIBColor();
+ }
+
+ if (changeSetting & KNutPrefDlg::ChangeKIconBColor) {
+ if (m_myDock) m_myDock->changeKIBColor();
+ }
+
+ if (changeSetting & KNutPrefDlg::ChangeToolTip) {
+ if (m_myDock) m_myDock->changeToolTip();
+ }
+
+ //for other settings will call functions from mainWindow class
+ if (mainWindow) mainWindow->setConfig (changeSetting);
+ }
+ }
+
+
+void KNutClient::slotPrintUPSVars(void) {
+
+ if (m_mainUpsInfo.upsDriverState == knc::connected) {
+ if (!m_mainUpsInfo.errorUpsData) {
+ if ((m_mainUpsInfo.upsNet->readNumberVars (KNutNet::AllVars)) || (m_mainUpsInfo.upsNet->readNumberComms ())) {
+ KNutPrintUpsVar *windowUpsVars = new KNutPrintUpsVar(m_mainUpsInfo.upsNet,settingData.useDescription);
+ if (windowUpsVars->upsOk()) windowUpsVars->exec();
+ delete windowUpsVars;
+ }
+ } else {
+ // KNutVarData::showError (mainUpsInfo.netError);
+ if ((m_myMessMan)) m_myMessMan->addMessage(KNutVarData::errorToText(m_mainUpsInfo.netError),knc::errorLevel,true);
+ }
+ } else {
+ // KNutVarData::showError (KNutNet::NotConnection);
+ if ((m_myMessMan)) m_myMessMan->addMessage(KNutVarData::errorToText(KNutNet::NotConnection),knc::errorLevel,true);
+
+ }
+ }
+
+
+void KNutClient::slotInstComms(void) {
+
+ if (m_mainUpsInfo.upsDriverState == knc::connected) {
+ if (!m_mainUpsInfo.errorUpsData) {
+ if (m_mainUpsInfo.upsNet->readNumberComms ()) {
+ KNutInstComms *windowInstComms = new KNutInstComms(&m_mainUpsInfo.name,&m_mainUpsInfo.password,m_mainUpsInfo.record.userName,m_mainUpsInfo.record.password,m_mainUpsInfo.upsNet);
+ if (windowInstComms->upsOk()) windowInstComms->exec();
+ delete windowInstComms;
+ }
+ }
+ else {
+// KNutVarData::showError (mainUpsInfo.netError);
+ if ((m_myMessMan)) m_myMessMan->addMessage(KNutVarData::errorToText(m_mainUpsInfo.netError),knc::errorLevel,true);
+ }
+ }
+ else {
+// KNutVarData::showError (KNutNet::NotConnection);
+ if ((m_myMessMan)) m_myMessMan->addMessage(KNutVarData::errorToText(KNutNet::NotConnection),knc::errorLevel,true);
+ }
+ }
+
+void KNutClient::slotRWVars(void) {
+
+ if (m_mainUpsInfo.upsDriverState == knc::connected) {
+ if (!m_mainUpsInfo.errorUpsData) {
+ if (m_mainUpsInfo.upsNet->readNumberVars (KNutNet::RWVars)) {
+ KNutRWVar *windowRWVars = new KNutRWVar(&m_mainUpsInfo.name,&m_mainUpsInfo.password,m_mainUpsInfo.record.userName,m_mainUpsInfo.record.password,m_mainUpsInfo.upsNet);
+ connect (windowRWVars,SIGNAL(signalChangeRWVars(QString)),this,SLOT(slotChangeRWVars(QString)));
+ if (windowRWVars->upsOk()) windowRWVars->exec();
+ delete windowRWVars;
+ }
+ }
+ else {
+ // KNutVarData::showError (mainUpsInfo.netError);
+ if ((m_myMessMan)) m_myMessMan->addMessage(KNutVarData::errorToText(m_mainUpsInfo.netError),knc::errorLevel,true);
+ }
+ }
+ else {
+ // KNutVarData::showError (mainUpsInfo.netError);
+ if ((m_myMessMan)) m_myMessMan->addMessage(KNutVarData::errorToText(KNutNet::NotConnection),knc::errorLevel,true);
+ }
+ }
+
+
+void KNutClient::slotRefreshConnection(void) {
+
+ m_reconnectMutex.lock();
+
+ m_mainUpsInfo.reconnecting =false;
+ m_reconnectTimer->stop();
+ m_upsTimer->stop();
+ upsDeactivate(); // closes connections
+
+ // nastavime na docku iconu
+ // sets icon for dock
+ if (m_myDock) {
+ m_myDock->clearDockValues();
+ // myDock->initImage();
+ // myDock->repaint();
+ }
+ if (mainWindow) {
+ mainWindow->cleanPanels();
+ }
+ addEventString(i18n("Reconnect"),m_mainUpsInfo.record.name);
+ if (m_myMessMan) m_myMessMan->deleteMessage();
+
+// mainUpsInfo.record.name=name;
+ m_mainUpsInfo.errorUpsData=false;
+ setActiveUpsInfo(m_mainUpsInfo.record.name);
+
+ //new connection name and password are cleaned
+ m_mainUpsInfo.name = "";
+ m_mainUpsInfo.password = "";
+
+
+ m_panelsAreZeroing=false;
+ m_lastError=0; // zadna chyba
+ m_mainUpsInfo.oldState=KNutNet::initState;
+
+ m_mainUpsInfo.upsNet->newUPS(m_mainUpsInfo.record.upsAddress,m_mainUpsInfo.record.upsName, m_mainUpsInfo.record.port);
+ // state of connection to usbd, this isn't state of knutnet
+ m_mainUpsInfo.upsDriverState=knc::connecting;
+ m_mainUpsInfo.upsNet->open();
+ m_reconnectMutex.unlock();
+ }
+
+
+void KNutClient::slotChangeRWVars( QString ) {
+ // informace ze doslo k uspesne zmene promene
+ // vzhledem k asynchronimu zpracovani muze upsd vratit tuto hodnotu az za nejakou dobu
+ // nevim zda bude potreba
+ }
+
+
+void KNutClient::exitMainWindow (void) {
+
+ mainWindow=0;
+ if (m_mainUpsInfo.upsNet) setActiveUpsVars(false);
+ // Pokud neni aktivovan dock musime ukoncit aplikaci..
+ // When dock isn't activated we must close application.
+ if (m_myDock == 0) {
+ saveConfiguration(false);
+ if (m_mainUpsInfo.upsNet) {
+ delete m_mainUpsInfo.upsNet;
+ m_mainUpsInfo.upsNet = 0;
+ }
+ kapp->quit();
+ }
+ }
+
+
+void KNutClient::makeMainWindow (void) {
+
+ mainWindow = new KNutMainWindow(m_listKNutEvent ,&m_mainUpsInfo, &settingData, upsRecords, analogRecords);
+ connect(mainWindow, SIGNAL(UPSChanged (QString)), this, SLOT(slotSetNewUPS (QString)));
+ connect(mainWindow, SIGNAL(preferenceUps()),this, SLOT(slotPreferenceUps()));
+ connect(mainWindow, SIGNAL(showUPSVars()),this, SLOT(slotPrintUPSVars()));
+ connect(mainWindow, SIGNAL(makeInstComms()),this, SLOT(slotInstComms()));
+ connect(mainWindow, SIGNAL(makeRWVars()),this, SLOT(slotRWVars()));
+ connect(mainWindow, SIGNAL(makeRefreshConnection()),this, SLOT(slotRefreshConnection()));
+ connect(mainWindow, SIGNAL(saveConf()),this, SLOT(slotSaveConf()));
+
+
+
+
+ connect(mainWindow, SIGNAL(endApplication()), this, SLOT(slotExitApplication()));
+ connect(mainWindow, SIGNAL(destroyed()), this, SLOT(exitMainWindow()));
+ }
+
+
+
+void KNutClient::slotActiveMainWindow (void) {
+
+ if (!mainWindow) {
+ // pred activaci nastaveme promenne znovu precteme data
+ // state of connection to usbd, this isn't state of knutnet
+ if (m_mainUpsInfo.upsDriverState==knc::connected) {
+ m_upsTimer->stop();
+ setActiveUpsVars(true);
+ getUpsData();
+ makeMainWindow();
+ if (m_myDock) m_myDock->repaintDock(m_mainUpsInfo.netError);
+ m_upsTimer->start( 1, TRUE ); // nastartujem znovu
+ // 1 proto aby se zpracovali pripadne udalosti o zruseni spojeni
+ }
+ else {
+ setActiveUpsVars(true);
+ //getUpsData(); zrusene protoze kdyz nebylo spojeni navazeno vratil by prikaz
+ // getValues error=0 a doslo by vypsani data ok.
+ makeMainWindow();
+ if (!m_mainUpsInfo.errorUpsData) {
+ if (m_myDock) m_myDock->repaintDock(m_mainUpsInfo.netError);
+ }
+ }
+ }
+ else { // end if mainWindow
+ //activates main window
+ mainWindow->raise();
+ KWin::activateWindow(mainWindow->winId());
+ }
+ }
+
+void KNutClient::slotSaveConf (void) {
+ saveConfiguration(true); // saves all configuration
+}
+
+void KNutClient::closeMainWindow (void) {
+ if (mainWindow) {
+ if (m_myDock) m_myDock->repaintDock(m_mainUpsInfo.netError);
+ m_upsTimer->stop();
+ mainWindow->close();
+ mainWindow=0;
+ m_upsTimer->start( 1, TRUE ); // starts timer // nastartujeme casovac
+ }
+ }
+
+
+void KNutClient::slotExitApplication(void) {
+
+ m_upsTimer->stop();
+ if (mainWindow) {
+ // odpojime protoze exitMainWindow by byl vykonan az po zkonceni procedury;
+ disconnect(mainWindow, SIGNAL(destroyed()), this, SLOT(exitMainWindow()));
+ delete mainWindow;
+ mainWindow = 0;
+ }
+ saveConfiguration(false);
+ if (m_mainUpsInfo.upsNet) {
+ delete m_mainUpsInfo.upsNet;
+ m_mainUpsInfo.upsNet = 0;
+ }
+ if (m_myDock) { m_myDock->close(); m_myDock = 0;}
+ kapp->quit();
+ }
+
+#include "knutclient.moc"
+
diff --git a/src/knutclient.desktop b/src/knutclient.desktop
new file mode 100644
index 0000000..8a2568e
--- /dev/null
+++ b/src/knutclient.desktop
@@ -0,0 +1,20 @@
+# KDE Config File
+[Desktop Entry]
+Encoding=UTF-8
+Type=Application
+Version=0.9.4
+Exec=knutclient -caption "%c" %i %m
+Icon=knutclient.png
+MiniIcon=knutclient.png
+DocPath=knutclient/index.html
+Name=KNutClient
+Name[de]=KNutClient
+Name[cs]=KNutClient
+Comment=Client for NUT
+Comment[de]=
+Comment[cs]=Klient pro UPS syst� NUT
+Comment[es]=Cliente KDE para NUT
+Terminal=0
+X-KDE-StartupNotify=true
+OnlyShowIn=KDE;
+Categories=Qt;KDE;System;Monitor;
diff --git a/src/knutclient.h b/src/knutclient.h
new file mode 100755
index 0000000..fab2295
--- /dev/null
+++ b/src/knutclient.h
@@ -0,0 +1,210 @@
+/***************************************************************************
+ knutclient.h - description
+ -------------------
+ begin : Út srp 21 19:12:20 CEST 2001
+ copyright : (C) 2001 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTCLIENT_H
+#define KNUTCLIENT_H
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include "knutmainwindow.h"
+#include "knutvardata.h"
+#include "knutupsdata.h"
+#include "knutnet.h"
+#include "knutdock.h"
+#include "knutprefdlg.h"
+#include "knutmessagemanager.h"
+
+#include <kapplication.h>
+
+
+#include <qwidget.h>
+#include <qtimer.h>
+#include <qstringlist.h>
+#include <qmutex.h>
+
+ const int countNextConnDelay = 10;
+ const int nextConnDelay[] = {
+ 5, 5, 20, 30, 60, 60, 120, 300, 600, 900 };
+
+
+class KNutClient : public QObject, public KSessionManaged {
+ Q_OBJECT
+ public:
+ KNutClient(bool noDock = false, QObject* parent=0,const char* name=0);
+ ~KNutClient();
+
+ private slots:
+ void slotTimeout (void);
+
+ void slotReconnectTimeout (void);
+
+ void slotSetNewUPS (QString name);
+
+ void slotPreferenceUps(void);
+
+ void slotSetConfig (unsigned int changeSetting);
+
+ void slotPrintUPSVars(void);
+ void slotInstComms(void);
+ void slotRWVars(void);
+ void slotChangeRWVars( QString );
+
+ void slotSaveConf (void);
+
+
+ void slotExitApplication(void);
+
+
+/**
+ *
+ * Calls function for repainting of icon in dock.
+ * Vola funkci pro prekresleni icony v doku.
+ *
+ * @since 0.1
+ **/
+ void slotTryFirstConnection (int maxCount);
+
+
+
+/**
+ * This function is called when program repeats other connection;
+ * Calls function for repainting of icon in dock.
+ * Tata funkce je volana, kdyz program opakuje pokus o pripojeni.
+ * Vola funkci pro prekresleni icony v doku.
+ *
+ * @since 0.1
+ **/
+ void slotTryReepatFirstConnection (int number );
+
+
+/**
+ * Nastavi hodnoty po prvem pripojeni na UPS, zavola prekresleni docku a nastartuje timer
+ * Sets values after the first conection to UPS ,calls to repaint of dock and starts timer
+ *
+ * @since 0.2
+ **/
+ void slotFirstConnection (void);
+
+
+
+/**
+ * Zpracuje chybu spojeni
+ * Executes error of connection
+ *
+ * @since 0.1
+ **/
+ void slotErrorConnection (int error);
+
+
+/**
+ * Zpracuje ukonceni spojeni, pokud spojeni bylo ukonceno druhou stranou.
+ * Executes end of connection, when connection was closed by the second side.
+ *
+ * @since 0.1
+ **/
+ void slotConnectionClosed(void);
+
+
+/**
+ *
+ *
+ * @since 0.1
+ **/
+ void slotRefreshConnection(void);
+
+
+ void closeMainWindow (void);
+ void exitMainWindow (void);
+ void slotActiveMainWindow (void);
+
+ virtual bool commitData (QSessionManager&);
+ virtual bool saveState (QSessionManager&);
+
+ private:
+
+/**
+ * Prepares and show main window.
+ * Pripravi a zobrazi hlavni okno.
+ *
+ * @since 0.1
+ **/
+ void makeMainWindow (void);
+
+/**
+ * Sets all variables to initial values.
+ * Nastavi vsechny vsechny promenne na pocatecni hodnoty.
+ *
+ * @since 0.1
+ **/
+ void initVars (void);
+
+ void loadConfiguration ( void );
+ void saveConfiguration ( bool all = true );
+
+ void upsActivate (void);
+ void upsDeactivate (void);
+
+ void setActiveUpsVars (bool mWindow = true);
+ void setActiveXFerVars (bool activate);
+
+ void getUpsData (void);
+
+ void setActiveUpsInfo (QString name);
+
+ void addEventString (const QString text, const QString UPSAddress = QString::null);
+
+ void showStatusEvent(void);
+
+
+
+
+/********* PRIVATE VARS****************/
+ // hlavni informace o upsce
+ // main informacion about UPS
+ KNutVarData::upsInfoDef m_mainUpsInfo;
+
+ // v teto strukture jsou ulozeny promene ktere nastavuji konfiguraci
+ // in this structure are saveing values, which setting configuration
+ KNutVarData::SettingDataDef settingData;
+
+ KNutDock* m_myDock;
+
+ KNutMainWindow* mainWindow;
+
+ KNutUpsData* upsRecords;
+ KNutVarData* analogRecords;
+
+ QTimer* m_upsTimer;
+ QTimer* m_reconnectTimer;
+
+ QStringList* m_listKNutEvent;
+
+ bool m_panelsAreZeroing; // indikuje zda je panel nulovany // use if analog panels is setting to zero
+ // kod posledni chyby spojeni zjistene v timeoutu
+ // nebere ohled zda byla chyba pri inicializaci
+ int m_lastError;
+
+ KNutMessageManager* m_myMessMan;
+
+ // mutex for reconnect, only one reconnect at a time
+ QMutex m_reconnectMutex;
+ QMutex m_upsDeactivateMutex;
+
+ };
+#endif
diff --git a/src/knutclientui.rc b/src/knutclientui.rc
new file mode 100644
index 0000000..8854298
--- /dev/null
+++ b/src/knutclientui.rc
@@ -0,0 +1,24 @@
+<!DOCTYPE kpartgui SYSTEM "kpartgui.dtd">
+<kpartgui name="KNutClient" version="0.9.3">
+<MenuBar>
+ <Menu name="file"><text>&amp;File</text>
+ <Action name="printupsvars" />
+ <Action name="instcomms" />
+ <Action name="rwvars" />
+ </Menu>
+ <Menu name="settings"><text>&amp;Settings</text>
+ <Separator/>
+ <Action name="use_description" />
+ </Menu>
+ <Menu name="connection"><text>&amp;Connection</text>
+ <Action name="reconnect" />
+ </Menu>
+</MenuBar>
+<ToolBar name="mainToolBar">
+ <Action name ="file_quit"/>
+ <Action name ="options_configure"/>
+ <Action name ="reconnect"/>
+ <Separator lineSeparator="true"/>
+</ToolBar>
+<StatusBar/>
+</kpartgui>
diff --git a/src/knutconst.h b/src/knutconst.h
new file mode 100755
index 0000000..866fe5d
--- /dev/null
+++ b/src/knutconst.h
@@ -0,0 +1,58 @@
+/***************************************************************************
+ knutconst.h - description
+ -------------------
+ begin : Tue Sep 24 2001
+ copyright : (C) 2003 by Daniel Prynych
+ email : Daniel@prynych.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTCONST_H
+#define KNUTCONST_H
+
+
+namespace knc {
+
+ const int StartPort =1024;
+ const int StopPort= 65535;
+ const int MinDelay = 2000;
+
+ const int MinCols = 1;
+ const int MaxCols = 5;
+
+ const int DefaultCountCols = 3; // prednastaveny pocet sloupcu analogovych meraku
+ const int DefaultPort = 3493; // default ports - prednastaveny port
+
+ const int DefaultDelay = 2000; //2000 msec
+
+ const int DefaultInputVoltage = 230;
+ const int DefaultInputFrequency = 50;
+
+ const int NumberOfTypes = 14; // count types of variables // pocet typu promenych (none,utility ....)
+ const int NumberOfVars = NumberOfTypes -1; // how many variables we can measure // kolik promenych muzeme merit
+
+ enum {VarNone,VarUtility,VarBattPct,VarUpsTemp,VarAcfreq,VarLoadPct,VarAmbTemp,VarAmbHumid,VarBattVolt,VarOutVolt,VarCurrent,VarOutFreq,VarBattTemp,VarBattCurrent};
+
+ const unsigned int maxCountKNutEvent = 100;
+
+ const int numberVarError = -1000;
+
+ enum upsDriverConnection { // state of connection to usbd, this isn't state of knutnet
+ connecting,
+ connected,
+ stale,
+ notConnected,
+ error
+ };
+ }
+
+
+#endif
diff --git a/src/knutdock.cpp b/src/knutdock.cpp
new file mode 100755
index 0000000..13d0d87
--- /dev/null
+++ b/src/knutdock.cpp
@@ -0,0 +1,976 @@
+/***************************************************************************
+ knutdock.cpp - description
+ -------------------
+ begin : Út zari 23 2003
+ copyright : (C) 2003 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#include "knutdock.h"
+#include "knutnet.h"
+
+//#include <kglobal.h>
+#include <kiconloader.h>
+#include <klocale.h>
+#include <kapp.h>
+#include <kaboutapplication.h>
+#include <kmessagebox.h>
+
+#include <qpainter.h>
+#include <qtooltip.h>
+#include <qpixmap.h>
+#include <qbitmap.h>
+#include <qstring.h>
+
+
+#include <math.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+//#include <iostream>
+
+KNutDock::KNutDock(KNutVarData::upsInfoDef* activeUpsInfo, KNutVarData::SettingDataDef* settingData, KNutUpsData* upsRecords){
+ QString valueName;
+
+ m_settingData = settingData;
+ m_upsRecords = upsRecords;
+ m_activeUpsInfo = activeUpsInfo;
+
+//saves backgroundcolor of kicker
+ backgroundColor = paletteBackgroundColor();
+
+ m_typeOfIcon = m_settingData->typeOfKIcon;
+
+ if (!m_settingData->customKIconColor) m_myBGColor = backgroundColor;
+ else m_myBGColor = m_settingData->kIconBackgroundColor;
+
+ m_toolTipFlags=m_settingData->toolTipFlags;
+
+ clearValues();
+
+
+ KIconLoader *loader = KGlobal::iconLoader();
+ m_mainPix = loader->loadIcon ("knutclient",KIcon::Small,16);
+
+ // aplications's own icons
+ m_errorPix = UserIcon ("knc_error");
+ m_connectPix = UserIcon ("knc_conn");
+ m_upsPix = UserIcon ("knc_ups");
+ m_battPix = UserIcon ("knc_batt");
+
+ createMainMenu();
+
+ m_statusLayer = 0;
+ m_runtimeLayer = 0;
+
+ m_loadLayer = new QPixmap(24,24);
+ m_chargeLayer = new QPixmap(24,24);
+ m_mainLayer = new QPixmap(24,24);
+
+
+ initImage();
+ changeKIcon(); // this function calls function repaintIcon
+
+ }
+
+
+KNutDock::~KNutDock(){
+
+ if (m_statusLayer) delete m_statusLayer;
+ if (m_runtimeLayer) delete m_runtimeLayer;
+
+ delete m_loadLayer;
+ delete m_chargeLayer;
+ delete m_mainLayer;
+
+ delete m_upsServerMenu;
+ delete m_menu;
+ }
+
+void KNutDock::changeUps (void) {
+
+ m_upsServerMenu->clear();
+ createUpsMenu();
+ }
+
+
+void KNutDock::clearDockValues(void){
+
+ initImage(); // paints standart icon
+
+ clearValues();
+ repaintDock(true);
+ }
+
+
+void KNutDock::changeToolTip(void){
+
+ m_toolTipFlags=m_settingData->toolTipFlags;
+ toolTip(m_runtimeValue, m_statusValue, m_batteryChargeValue, m_upsLoadValue);
+ }
+
+
+void KNutDock::changeKIBColor(void) {
+
+ if (!m_settingData->customKIconColor) m_myBGColor = backgroundColor;
+ else m_myBGColor = m_settingData->kIconBackgroundColor; // uses defined color
+
+ repaintDock(true);
+ }
+
+void KNutDock::changeKIcon (void) {
+
+ m_typeOfIcon = m_settingData->typeOfKIcon;
+ if ( m_typeOfIcon == generalKI) {
+
+ if (m_mainLayer) {
+ delete m_mainLayer;
+ m_mainLayer=new QPixmap(24,24);
+ }
+
+ if (!m_statusLayer) {
+ m_statusLayer = new QPixmap(24,24);
+ }
+ if (!m_runtimeLayer) {
+ m_runtimeLayer = new QPixmap(24,24);
+ }
+ paintStatus(m_statusValue);
+ paintRuntime(m_runtimeValue, m_statusValue);
+ }
+ else { // picture Icon
+ delete m_statusLayer;
+ m_statusLayer = 0;
+ delete m_runtimeLayer;
+ m_runtimeLayer=0;
+ }
+ paintLoad(m_upsLoadValue);
+ paintCharge(m_batteryChargeValue);
+
+ m_statusWarningValue = m_statusValue & (KNutNet::CAL | KNutNet::TRIM | KNutNet::BOOST
+ | KNutNet::OVER | KNutNet::RB);
+ repaintDock(true);
+ }
+
+void KNutDock::initImage(void) {
+ setPixmap(m_mainPix);
+ m_dataOk = idle;
+ m_dataOkOld = m_dataOk;
+ }
+
+void KNutDock::setNewUPS(void) {
+ m_upsServerMenu->clear();
+ createUpsMenu();
+ }
+
+
+void KNutDock::repaintDock (const bool always) {
+ QString nutStringVar;
+ int myRuntimeValue;
+ int myUpsLoadValue;
+ int myStatusValue;
+ int myStatusBatValue;
+ int myBatteryChargeValue;
+ bool repaintNow = false;
+ // value repaintNow is seted when some ups values are changed
+ bool okFloat;
+ QString valueName;
+ QPainter paint;
+
+
+ if (m_activeUpsInfo->upsNet == 0) { repaint(); return;}
+
+ m_dataOkOld=m_dataOk;
+
+ if ((m_activeUpsInfo->upsNet->getState() == KNutNet::Connected) // paints icons with information values
+ && (!m_activeUpsInfo->netError)) {
+ // ups is connected dataOK is ok (program shows icon of connecting UPS)
+ m_dataOk = ok; // pro paint event udava ze mam pouzit nase ikony
+
+ if (!m_activeUpsInfo->upsNet->existName(m_activeUpsInfo->runtimeVar)) {
+ nutStringVar = m_activeUpsInfo->upsNet->readStringVar(m_activeUpsInfo->runtimeVar);
+//std::cout << "KNutDock::repaintDock RUNTIME " << nutStringVar << std::endl;
+ if (nutStringVar.isEmpty()) myRuntimeValue=knc::numberVarError;
+ else {
+ myRuntimeValue = (int)nutStringVar.toFloat(&okFloat);
+ if (!okFloat) myRuntimeValue = knc::numberVarError;
+ }
+ }
+ else myRuntimeValue = knc::numberVarError;
+
+ myStatusValue = m_activeUpsInfo->upsNet->readStatus();
+
+
+ switch (m_typeOfIcon) {
+ case generalKI:
+// *********STATUS****************
+ if (myStatusValue !=m_statusValue ) {
+ m_statusValue = myStatusValue;
+ paintStatus(m_statusValue);
+ repaintNow = true;
+ }
+
+// **********RUNTIME***********
+ myStatusBatValue = myStatusValue & KNutNet::OB; // OB = UPS runs on battery
+ if ((myRuntimeValue != m_runtimeValue) || (myStatusBatValue != m_statusBatValue)) {
+ // when runtime is changed or flags OB is changed we must repaint icons
+ // when OB is changed same items in icon will change color
+ m_runtimeValue = myRuntimeValue; // runtime is old value of runtime, one is defined like global value of class
+ m_statusBatValue = myStatusBatValue;
+ paintRuntime(m_runtimeValue, m_statusValue);
+ repaintNow = true;
+ }
+ break;
+
+ case pictureKI:
+// *********STATUS****************
+ if (myStatusValue !=m_statusValue ) {
+ m_statusValue = myStatusValue;
+ m_statusWarningValue = myStatusValue & (KNutNet::CAL | KNutNet::TRIM | KNutNet::BOOST
+ | KNutNet::OVER | KNutNet::RB);
+ repaintNow = true;
+ }
+
+// **********RUNTIME***********
+ if (myRuntimeValue != m_runtimeValue) {
+ m_runtimeValue = myRuntimeValue;
+ repaintNow = true;
+ }
+ break;
+ } ///////////////////// end of models
+
+ // Other values are for all modes
+
+// **********UPS LOAD***************
+ if (m_activeUpsInfo->nutVariables == 1) valueName = "LOADPCT";
+ else valueName = "ups.load";
+ if (!m_activeUpsInfo->upsNet->existName(valueName)) {
+ nutStringVar = m_activeUpsInfo->upsNet->readStringVar(valueName);
+ if (nutStringVar.isEmpty()) myUpsLoadValue=knc::numberVarError;
+ else {
+ myUpsLoadValue = (int)nutStringVar.toFloat(&okFloat);
+ if (!okFloat) myUpsLoadValue=knc::numberVarError;
+ }
+ }
+ else myUpsLoadValue=knc::numberVarError;
+
+ if (myUpsLoadValue != m_upsLoadValue) {
+ m_upsLoadValue = myUpsLoadValue;
+ if (m_typeOfIcon == generalKI) paintLoad(m_upsLoadValue);
+ repaintNow = true;
+ }
+
+// *********BATTERY CHARGE****************
+ if (m_activeUpsInfo->nutVariables == 1) valueName="BATTPCT";
+ else valueName="battery.charge";
+ if (!m_activeUpsInfo->upsNet->existName(valueName)) {
+ nutStringVar = m_activeUpsInfo->upsNet->readStringVar(valueName);
+ if (nutStringVar.isEmpty()) myBatteryChargeValue=knc::numberVarError;
+ else {
+ myBatteryChargeValue = (int)nutStringVar.toFloat(&okFloat);
+ if (!okFloat) myBatteryChargeValue = knc::numberVarError;
+ }
+ }
+ else myBatteryChargeValue=knc::numberVarError;
+
+ if (myBatteryChargeValue != m_batteryChargeValue) {
+ m_batteryChargeValue = myBatteryChargeValue;
+ if (m_typeOfIcon == generalKI)paintCharge(m_batteryChargeValue);
+ repaintNow = true;
+ }
+// ************* End of values********************
+
+ if (repaintNow || always || (m_dataOk != m_dataOkOld)) {
+
+
+ switch (m_typeOfIcon) {
+ case generalKI:
+ m_mainLayer->fill(m_myBGColor);
+// copyBlt (m_mainLayer,0,0,m_runtimeLayer,0,0,24,24);
+ bitBlt (m_mainLayer,0,0,m_runtimeLayer,0,0,24,24,AndROP);
+ bitBlt (m_mainLayer,0,0,m_loadLayer,0,0,24,24,AndROP);
+ bitBlt (m_mainLayer,0,0,m_chargeLayer,0,0,24,24,AndROP);
+ bitBlt (m_mainLayer,0,0,m_statusLayer,0,0,24,24,AndROP);
+ break;
+ case pictureKI:
+// if (m_statusValue & KNutNet::OL) bitBlt (m_mainLayer,0,0,m_loadLayer,0,0,24,24,AndROP); // icon of UPS
+ if (m_statusValue & KNutNet::OL) { // ONLINE - icon of UPS
+ int myLoad;
+ QPainter paint;
+ copyBlt (m_mainLayer,0,0,&m_upsPix,0,0,24,24); // icon of UPS
+
+ paint.begin(m_mainLayer);
+ if (m_upsLoadValue == knc::numberVarError) myLoad=0;
+ else myLoad = abs(m_upsLoadValue/10);
+
+ if (m_upsLoadValue != knc::numberVarError) {
+ if (myLoad > 12) myLoad=12;
+ if (myLoad > 10) myLoad++; // preskocime rysku pro 100 %
+ if (myLoad < 9) paint.setPen(QColor(0,192,0)); //green
+ else {
+ if (myLoad < 11) paint.setPen(QColor(255,255,0)); //yellow
+ else paint.setPen(QColor(255,0,0));//red
+ }
+ for (int i = 19; i < 22; i++) paint.drawLine(i,13,i,13-myLoad +1);
+
+ if (myLoad < 13) {
+ paint.setPen(QColor(168,220,255));
+ for (int i = 20; i < 23; i++ ) paint.drawLine(i,1,i,13-myLoad);
+ }
+ }
+ paint.setPen(QColor(Qt::black)); // line for 100 % load
+ paint.drawLine(19,3,22,3);
+ if (!m_statusWarningValue) paintOKPoint(paint);
+ else paintErrorPoint(paint);
+ paint.end();
+ }
+ else {
+ QPainter paint;
+ copyBlt (m_mainLayer,0,0,&m_battPix,0,0,24,24); // icon of Battery
+ paint.begin(m_mainLayer);
+ if (m_batteryChargeValue != knc::numberVarError) {
+ if (m_batteryChargeValue < 40) paint.setPen(Qt::red);
+ else paint.setPen(Qt::black);
+ if (m_batteryChargeValue < 40) paint.setPen(Qt::red);
+ else {
+ if (m_batteryChargeValue < 50) paint.setPen(Qt::yellow);
+ else paint.setPen(Qt::green);
+ }
+ int delka = abs((16*m_batteryChargeValue)/100);
+ delka += abs((delka-1)/4) -1;
+ paint.drawLine (2,7,2+delka,7);
+ paint.drawLine (2,8,2+delka,8);
+ paint.drawLine (2,9,2+delka,9);
+ }
+ paint.end();
+ }
+ break;
+ }
+ toolTip(m_runtimeValue, m_statusValue, m_batteryChargeValue, m_upsLoadValue);
+
+ setPixmap(*m_mainLayer);
+ }
+ }
+ else { // KNutNet->state isn't connected
+ // we must test activeUpsInfo->netError because error can rise higher level
+ if (m_activeUpsInfo->netError)
+ m_dataOk = error; // error is value not variable
+ else {
+ if ((m_activeUpsInfo->upsNet->getState() == KNutNet::Connecting) ||
+ (m_activeUpsInfo->upsNet->getState() == KNutNet::HostLookup))
+ m_dataOk = connecting;
+ else m_dataOk = idle;
+ }
+ if ((m_dataOk != m_dataOkOld) or always) {
+ toolTip(0, -1, 0, 0);
+ m_dataOkOld=m_dataOk;
+ if (m_dataOk == connecting) setPixmap(m_connectPix);
+ else {
+ if (m_dataOk == error) setPixmap(m_errorPix);
+ else {
+ setPixmap(m_mainPix);
+ }
+ }
+ }
+ }
+ repaint();
+ }
+
+
+
+void KNutDock::toolTip (int runtime, int status, int batteryCharge, int upsLoad ) {
+
+ QString text;
+ QString manufacturer = "";
+ QString upsModel = "";
+ QString serial = "";
+ QString firmware = "";
+ int myNetErr = 0;
+
+ int min = abs(runtime/60);
+ int sec = runtime - (min*60);
+
+ if (m_activeUpsInfo->upsNet != 0) {
+ myNetErr= m_activeUpsInfo->upsNet->getError();
+ switch (m_activeUpsInfo->nutVariables) {
+ case 1:
+ manufacturer = m_activeUpsInfo->upsNet->readStringVar("MFR");
+ upsModel = m_activeUpsInfo->upsNet->readStringVar("MODEL");
+ serial = m_activeUpsInfo->upsNet->readStringVar("SERIAL");
+ firmware = m_activeUpsInfo->upsNet->readStringVar("FIRMREV");
+ break;
+ case 2:
+ manufacturer = m_activeUpsInfo->upsNet->readStringVar("ups.mfr");
+ upsModel = m_activeUpsInfo->upsNet->readStringVar("ups.model");
+ serial = m_activeUpsInfo->upsNet->readStringVar("ups.serial");
+ firmware = m_activeUpsInfo->upsNet->readStringVar("ups.firmware");
+ break;
+ }
+ }
+
+ text = i18n("Name")+" : "+m_activeUpsInfo->record.name + "\n"
+ +i18n("UPS name")+" : "+m_activeUpsInfo->record.upsName + "\n"
+ +i18n("UPS address")+" : "+m_activeUpsInfo->record.upsAddress +"\n"
+ +i18n("Status : ");
+
+ if (status == -1) {
+ text += i18n("Connection doesn't exist.");
+ }
+ else {
+ if (status & KNutNet::OL) {
+ text += i18n("UPS On line");
+ }
+ else {
+ if (status & KNutNet::OB) {
+ text += i18n("UPS On battery");
+ }
+ else {
+ if (status & KNutNet::OFF) {
+ text += i18n("UPS Of line");
+ }
+ }
+ }
+
+ if (status & KNutNet::LB) {
+ text += "\n" + i18n("Status : ") + i18n("UPS Battery is low");
+ }
+ if (status & KNutNet::RB) {
+ text += "\n" + i18n("Status : ") + i18n("Replace battery");
+ }
+ if (status & KNutNet::CAL) {
+ text += "\n" + i18n("Status : ") + i18n("UPS is performing calibration");
+ }
+ if (status & KNutNet::OVER) {
+ text += "\n" + i18n("Status : ") + i18n("UPS is Overload");
+ }
+ if (status & KNutNet::TRIM) {
+ text += "\n" + i18n("Status : ") + i18n("UPS is trimming voltage");
+ }
+ if (status & KNutNet::BOOST) {
+ text += "\n" + i18n("Status : ")+ i18n("UPS is boosting voltage");
+ }
+
+
+ }
+ if ((status == -1) && (myNetErr != KNutNet::NoError)) {
+ text += "\n" + i18n("Error : ")+ KNutVarData::errorToText(myNetErr);
+ }
+
+ if (m_toolTipFlags & TTMFR) text += "\n" + i18n("Manufac. : ")+ manufacturer;
+
+ if (m_toolTipFlags & TTModel) text += "\n" + i18n("Name")+" : "+ upsModel;
+
+ if (m_toolTipFlags & TTSerial) text += "\n" + i18n("Serial")+" : "+ serial;
+
+ if (m_toolTipFlags & TTFirm) text += "\n" + i18n("Firmware")+" : "+ firmware;
+
+ if (m_toolTipFlags & TTRun) {
+ if (runtime != knc::numberVarError)
+ text += "\n" + i18n("Runtime") + i18n(" : %1:%2 min").arg(min).arg(sec);
+ }
+
+ if (m_toolTipFlags & TTCharge) {
+ if (batteryCharge != knc::numberVarError)
+ text += "\n" + i18n("Battery Charge") + QString(" : %1 %").arg(batteryCharge);
+ }
+
+ if (m_toolTipFlags & TTLoad) {
+ if (upsLoad != knc::numberVarError)
+ text += "\n" + i18n("UPS Load") + QString(" : %1 %").arg(upsLoad);
+ }
+
+ QToolTip::remove(this);
+ QToolTip::add(this,text);
+ }
+
+
+
+/*********************************************************************************************/
+/* */
+/* PRIVATE SLOTS */
+/* */
+/*********************************************************************************************/
+
+ void KNutDock::slotShowMyAbout() {
+ KAboutApplication *dialog;
+
+ dialog= new KAboutApplication;
+ dialog->exec();
+ delete dialog;
+}
+
+void KNutDock::slotExitApplication (void) {
+
+ if (m_settingData->areYouSure) {
+ if (KMessageBox::warningYesNo (0,i18n("Are you sure ?")) == 3)
+ emit endApplication();
+ }
+ else emit endApplication();
+ }
+
+void KNutDock::slotUpsName(int i) {
+
+ emit UPSChanged(m_upsRecords->getName(i-101));
+ }
+
+
+void KNutDock::slotMinimize(void) {
+
+ emit minimize ();
+ }
+
+void KNutDock::slotPreferences(void) {
+
+ emit preferences();
+ }
+
+void KNutDock::slotPrintUPSVars(void) {
+
+ emit printUPSVars();
+ }
+
+void KNutDock::slotInstComms(void) {
+
+ emit instComms();
+ }
+
+void KNutDock::slotRWVars(void) {
+
+ emit RWVars();
+ }
+
+void KNutDock::slotRefreshConnection(void) {
+
+ emit makeRefreshConnection();
+ }
+
+
+//------------------------------------------
+
+void KNutDock::mousePressEvent(QMouseEvent *e) {
+
+//qDebug("KNutDock::mousePressEvent");
+ if( e->button()==LeftButton ) emit activeMainWindow();
+ if( e->button()==RightButton ) m_menu->popup(e->globalPos());
+ }
+
+
+
+
+void KNutDock::paintEvent (QPaintEvent *e) {
+
+ KSystemTray::paintEvent(e);
+ if ((m_activeUpsInfo->upsNet->getState() == KNutNet::Connected) and
+ (m_statusValue != KNutNet::NS)) { // When driver isn't connected, getState is connected and m_statusValue is NS // NONE STATUS
+ if (m_typeOfIcon == pictureKI) {
+ QPainter painter(this);
+// painter.begin();
+ if (m_statusValue & KNutNet::OL) { // ONLINE - icon of UPS
+ painter.setPen(Qt::black);
+ paintNumbers (m_upsLoadValue, -2, 15, &painter );
+ }
+ else { // OFFLINE icon of battery
+ if (m_batteryChargeValue != knc::numberVarError) {
+ if (m_batteryChargeValue < 40) painter.setPen(Qt::red);
+ else painter.setPen(Qt::black);
+ paintNumbers(m_batteryChargeValue,-2,16,&painter);
+ }
+ else {
+ painter.setPen(Qt::black);
+ paintDash (3,16,&painter);
+ paintDash (8,16,&painter);
+ }
+ }
+ // painter.end();
+ }
+ }
+ }
+
+
+
+
+/*********************************************************************************************/
+/* */
+/* PRIVATE FUNCTIONS */
+/* */
+/*********************************************************************************************/
+
+void KNutDock::clearValues(void) {
+
+ m_batteryChargeValue = 0;
+ m_runtimeValue = 0;
+ m_upsLoadValue = 0;
+ m_statusValue = 0;
+ }
+
+
+void KNutDock::createUpsMenu(void) {
+
+ int n = m_upsRecords->getCount();
+ for (int i =0; i < n; i++) {
+ if (m_activeUpsInfo->record.name == m_upsRecords->getName(i))
+ m_upsServerMenu->insertItem(kapp->miniIcon(),m_upsRecords->getName(i), this, SLOT(slotUpsName(int)),0,101+i);
+ else
+ m_upsServerMenu->insertItem(m_upsRecords->getName(i), this, SLOT(slotUpsName(int)),0,101+i);
+ }
+ }
+
+void KNutDock::createMainMenu(void) {
+
+ m_menu = new KPopupMenu;
+ m_upsServerMenu = new KPopupMenu;
+ createUpsMenu();
+
+ m_menu->insertTitle (kapp->miniIcon(),"knutclient");
+ m_menu->insertSeparator();
+ m_menu->insertItem("UPS",m_upsServerMenu);
+ m_menu->insertSeparator();
+ m_menu->insertItem(i18n("&Showing UPS variables and commands"), this, SLOT(slotPrintUPSVars()));
+ m_menu->insertItem(i18n("&Running instant commands"), this, SLOT(slotInstComms()));
+ m_menu->insertItem(i18n("Setting R&W variables"), this, SLOT(slotRWVars()));
+ m_menu->insertSeparator();
+ m_menu->insertItem(SmallIcon("reload"),i18n("Reconnect"), this, SLOT(slotRefreshConnection()));
+ m_menu->insertSeparator();
+ m_menu->insertItem(SmallIcon("configure"),i18n("&Preferences"), this, SLOT(slotPreferences()));
+ m_menu->insertSeparator();
+ m_menu->insertItem(kapp->miniIcon(),i18n("&About KNutClient"), this, SLOT(slotShowMyAbout()));
+ m_menu->insertSeparator();
+ m_menu->insertItem(i18n("&Minimize"), this, SLOT(slotMinimize()));
+ m_menu->insertSeparator();
+ m_menu->insertItem (SmallIcon("exit"),i18n("&Exit"),this ,SLOT(slotExitApplication()));
+ }
+
+
+void KNutDock::paintCharge (int charge ) {
+ QPainter paint;
+
+ m_chargeLayer->fill(Qt::white);
+ paint.begin(m_chargeLayer);
+ if (charge > 199) charge = 199;
+
+ if (m_typeOfIcon == generalKI) {
+ if (charge != knc::numberVarError) {
+ if (charge < 40) paint.setPen(Qt::red);
+ else paint.setPen(Qt::black);
+ paintNumbers(charge,8,2,&paint);
+ }
+ else {
+ paint.setPen(Qt::black);
+ paintDash (13,2,&paint);
+ paintDash (18,2,&paint);
+ }
+ }
+ else {
+ // picture version
+ if (charge != knc::numberVarError) {
+ if (charge < 40) paint.setPen(Qt::red);
+ else paint.setPen(Qt::black);
+ paintNumbers(charge,-2,16,&paint);
+
+ if (charge < 40) paint.setPen(Qt::red);
+ else {
+ if (charge < 50) paint.setPen(Qt::yellow);
+ else paint.setPen(Qt::green);
+ }
+ int delka = abs((16*charge)/100);
+ delka += abs((delka-1)/4) -1;
+ paint.drawLine (2,7,2+delka,7);
+ paint.drawLine (2,8,2+delka,8);
+ paint.drawLine (2,9,2+delka,9);
+ }
+ else {
+ paint.setPen(Qt::black);
+ paintDash (3,16,&paint);
+ paintDash (8,16,&paint);
+ }
+
+ }
+ paint.end();
+ }
+
+
+void KNutDock::paintErrorPoint ( QPainter& paint ) {
+
+ paint.setPen(QColor(0,0,255));
+ paint.setPen(QColor(255,0,0));
+
+ paint.drawLine(19,18,21,18);
+ paint.drawLine(19,19,21,19);
+ paint.drawLine(19,20,21,20);
+ }
+
+
+void KNutDock::paintOKPoint (QPainter& paint ) {
+
+ paint.setPen(QColor(0,255,0));
+ paint.drawLine(19,18,21,18);
+ paint.drawLine(19,19,21,19);
+ paint.drawLine(19,20,21,20);
+ }
+
+
+void KNutDock::paintStatus (int status ) {
+ QPainter paint;
+ int lastPos = 0;
+
+ m_statusLayer->fill(Qt::white);
+ paint.begin(m_statusLayer);
+
+ if (status & KNutNet::OL) {
+ paint.setPen(Qt::black);
+ paintChar (1,2,'P',&paint);
+ }
+ else {
+ if (status & KNutNet::OB) {
+ paint.setPen(Qt::red);
+ paintChar (1,2,'B',&paint);
+ }
+ }
+
+ if (status & KNutNet::LB) {
+ paint.setPen(Qt::red);
+ paintChar (6,2,'L',&paint);
+ }
+ if ((lastPos <2) && (status & KNutNet::RB)) {
+ paint.setPen(Qt::red);
+ paintChar (6,2,'R',&paint);
+ lastPos++;
+ }
+ if ((lastPos <2) && (status & KNutNet::BOOST)) {
+ paint.setPen(Qt::red);
+ paintChar (6,2,'B',&paint);
+ lastPos++;
+ }
+ if ((lastPos <2) && (status & KNutNet::TRIM)) {
+ paint.setPen(Qt::red);
+ paintChar (6,2,'T',&paint);
+ lastPos++;
+ }
+ if ((lastPos <2) && (status & KNutNet::CAL)) {
+ paint.setPen(Qt::red);
+ paintChar (6,2,'C',&paint);
+ lastPos++;
+ }
+ paint.end();
+ }
+
+void KNutDock::paintRuntime (int runtime, int status ) {
+ QPainter paint;
+
+ m_runtimeLayer->fill(Qt::white);
+ paint.begin(m_runtimeLayer);
+
+ if (status & KNutNet::OB)
+ paint.setPen(Qt::red);
+ else
+ paint.setPen(Qt::black);
+ if (runtime != knc::numberVarError) {
+
+ int min = abs(runtime/60);
+ int sec = runtime - (min*60);
+
+ paintNumber(1,11, abs(min/10) ,&paint);
+ paintNumber(6,11,min-((abs(min/10))*10) ,&paint);
+ paintNumber(13,11, abs(sec/10) ,&paint);
+ paintNumber(18,11,sec-((abs(sec/10))*10) ,&paint);
+ }
+ else {
+ paintDash (1,11,&paint);
+ paintDash (6,11,&paint);
+ paintDash (13,11,&paint);
+ paintDash (18,11,&paint);
+ }
+ paint.drawLine (11,12,11,13);
+ paint.drawLine (11,15,11,16);
+ paint.end();
+ }
+
+void KNutDock::paintLoad (int load ) {
+ QPainter paint;
+ int myLoad;
+
+// if (m_typeOfIcon != generalKI) bitBlt (m_loadLayer,0,0,m_upsLayer,0,0,24,24,AndROP);
+ m_loadLayer->fill(Qt::white);
+ paint.begin(m_loadLayer);
+ if (load == knc::numberVarError) myLoad=0;
+ else myLoad = abs(load/10);
+
+ if (m_typeOfIcon == generalKI) {
+ if (load != knc::numberVarError) {
+ if (myLoad > 11) myLoad=11;
+ if (myLoad < 9) paint.setPen(Qt::green);
+ else {
+ if (myLoad < 11) paint.setPen(Qt::yellow);
+ else paint.setPen(Qt::red);
+ }
+ paint.setPen(Qt::green.light(60));
+ for (int i = 0; i < myLoad; i++) {
+ paint.drawLine((i*2)+1,19,(i*2)+1,21);
+ }
+ paint.setPen(Qt::cyan.light(150));
+ for (int i = myLoad; i < 11; i++) {
+ paint.drawLine((i*2)+1,19,(i*2)+1,21);
+ }
+ }
+ }
+ paint.end();
+
+ }
+
+
+
+
+void KNutDock::paintNumbers (int numbers, int x, int y, QPainter* p ) {
+ bool first = false;
+
+ if (numbers > 199) numbers = 199;
+
+ if (numbers != knc::numberVarError) {
+
+ if (numbers > 99) {
+ paintNumber (x,y,1,p);
+ numbers -= 100;
+ first=true;
+ }
+ int second = abs (numbers/10);
+ int third = numbers - (second * 10);
+
+ if ((second != 0) || (first)) paintNumber (x+5,y,second,p);
+ paintNumber (x+10,y,third,p);
+
+ }
+ else {
+ p->setPen(Qt::black);
+ paintDash (x+5,y,p);
+ paintDash (x+10,y,p);
+ }
+ }
+
+
+void KNutDock::paintDash (int x, int y, QPainter *p) {
+
+ p->drawLine(x,y+3,x+3,y+3);
+ }
+
+void KNutDock::paintNumber (int x, int y, int number, QPainter *p) {
+ // x and y are left top corner
+
+ if ((number > -1) && (number < 10)) {
+ // painting - kreslim
+ switch (number) {
+ case 0:
+ p->drawRect(x,y,4,7);
+ break;
+ case 1:
+ p->drawLine (x+3,y,x+3,y+6);
+ break;
+ case 2:
+ p->drawLine(x,y,x+3,y);
+ p->lineTo(x+3,y+3);
+ p->lineTo(x,y+3);
+ p->lineTo(x,y+6);
+ p->lineTo(x+3,y+6);
+ break;
+ case 3:
+ p->drawLine(x,y,x+3,y);
+ p->lineTo(x+3,y+6);
+ p->lineTo(x,y+6);
+ p->drawLine(x,y+3,x+3,y+3);
+ break;
+ case 4:
+ p->drawLine(x,y,x,y+3);
+ p->lineTo(x+3,y+3);
+ p->drawLine (x+3,y,x+3,y+6);
+ break;
+ case 5:
+ p->drawLine(x+3,y,x,y);
+ p->lineTo(x,y+3);
+ p->lineTo(x+3,y+3);
+ p->lineTo(x+3,y+6);
+ p->lineTo(x,y+6);
+ break;
+ case 6:
+ p->drawRect(x,y+3,4,4);
+ p->drawLine(x,y+3,x,y);
+ p->lineTo(x+3,y);
+ break;
+ case 7:
+ p->drawLine(x,y,x+3,y);
+ p->lineTo(x+3,y+6);
+ break;
+ case 8:
+ p->drawRect(x,y,4,7);
+ p->drawLine(x,y+3,x+3,y+3);
+ break;
+ case 9:
+ p->drawRect(x,y,4,4);
+ p->drawLine(x+3,y+3,x+3,y+6);
+ p->lineTo(x,y+6);
+ break;
+ }
+ }
+ }
+
+
+void KNutDock::paintChar (int x, int y, char LCDChar, QPainter *p) {
+ // x and y are left up corner
+ switch (LCDChar) {
+ case 'L':
+ p->drawLine(x,y,x,y+6);
+ p->lineTo(x+3,y+6);
+ break;
+ case 'O':
+ p->drawRect(x,y,4,7);
+ break;
+ case 'B':
+ p->drawLine(x,y,x,y+6);
+ p->lineTo(x+2,y+6);
+ p->drawLine(x,y,x+2,y);
+ p->drawLine(x,y+3,x+2,y+3);
+ p->drawLine(x+3,y+1,x+3,y+2);
+ p->drawLine(x+3,y+4,x+3,y+5);
+ break;
+ case 'U':
+ p->drawLine(x,y,x,y+6);
+ p->lineTo(x+3,y+6);
+ p->lineTo(x+3,y);
+ break;
+ case 'C':
+ p->drawLine(x+3,y+1,x+3,y);
+ p->lineTo(x,y);
+ p->lineTo(x,y+6);
+ p->lineTo(x+3,y+6);
+ p->lineTo(x+3,y+5);
+ break;
+ case 'R':
+ p->drawLine(x,y,x,y+6);
+ p->drawLine(x,y,x+2,y);
+ p->drawLine(x,y+3,x+2,y+3);
+ p->drawLine(x+3,y+1,x+3,y+2);
+ p->drawLine(x+3,y+4,x+3,y+6);
+ break;
+ case 'P':
+ p->drawLine(x,y,x,y+6);
+ p->drawLine(x,y,x+2,y);
+ p->drawLine(x,y+3,x+2,y+3);
+ p->drawLine(x+3,y+1,x+3,y+2);
+ break;
+ case 'T':
+ p->drawLine(x+2,y,x+2,y+6);
+ p->drawLine(x,y,x+4,y);
+ break;
+ }
+ }
+
+
+
+
+#include "knutdock.moc"
diff --git a/src/knutdock.h b/src/knutdock.h
new file mode 100755
index 0000000..15fa69c
--- /dev/null
+++ b/src/knutdock.h
@@ -0,0 +1,525 @@
+/***************************************************************************
+ knutdock.h - description
+ -------------------
+ begin : Út zari 23 2003
+ copyright : (C) 2003 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTDOCK_H
+#define KNUTDOCK_H
+
+#include "knutupsdata.h"
+#include "knutvardata.h"
+#include "knutconst.h"
+
+
+#include <ksystemtray.h>
+#include <kpopupmenu.h>
+
+#include <qobject.h>
+
+
+class QString;
+class QPixmap;
+class QColor;
+
+/**
+ * This class makes icons in dock.
+ * Tato trida zajistuje vytvoreni icony v docku.
+ *
+ * @author Daniel Prynych
+ * @short Dock's icons
+ * @version 0.3
+ */
+class KNutDock : public KSystemTray {
+ Q_OBJECT
+ public:
+
+ enum KNTDconst { DefaultToolTipFlags = 0x398};
+
+
+ enum upsConnection {
+ idle, // ups isn't connected
+ connecting, // ups is connecting
+ ok, // ups is connected
+ error // error of connecting
+ };
+
+ enum eTypeOfIcons { pictureKI = 0, generalKI};
+
+
+ enum toolTipItems {
+ TTMFR = 0x8, // 8, // FRM
+ TTModel = 0x10, // 16, // Model
+ TTSerial = 0x20, // 32, // Serial
+ TTFirm = 0x40, //64, // Firmware Revision
+ TTRun = 0x80,// 128, // Runtime
+ TTCharge = 0x100, // 256, // Charge
+ TTLoad = 0x200 // 512 // Load
+ };
+
+
+
+
+/**
+ * Constructor - makes icon in dockbar.
+ * Konstruktor - vytvori iconu v docku.
+ *
+ * @param activeUpsInfo odkaz na structuru upsInfo
+ * @param activeUpsInfo pointer to structure upsInfo
+ * @param settingData odkaz na strukturu typu SettingDataDef
+ * @param settingData pointer to structure type of SettingDataDef
+ * @param upsRecord odkaz na instanci tridy tActiveUpsInfo
+ * @param upsRecord pointer to class tActiveUpsInfo
+ * @since 0.3
+ */
+ KNutDock(KNutVarData::upsInfoDef* activeUpsInfo, KNutVarData::SettingDataDef* settingData, KNutUpsData* upsRecords);
+
+/**
+ * Destruktor.
+ *
+ * @since 0.1.2
+ **/
+ ~KNutDock();
+
+
+/**
+ * Nastavi zakladni nastaveni pro dock.
+ * Sets basic setting for dock.
+ *
+ * @since 0.1
+ **/
+ void clearDockValues(void);
+
+
+/**
+ * Vytvori menu (seznam) UPS.
+ * Makes menu (list) of UPS.
+ *
+ * @since 0.1
+ **/
+ void changeUps(void);
+
+
+/**
+ * Zmeni styl/typ icon
+ * Changes style/type of icon
+ *
+ * @since 0.1
+ **/
+ void changeKIcon (void);
+
+/**
+ * Zmeni pozadi icony v kickeru
+ * Changes background of icon in kicker
+ *
+ * @since 0.2
+ **/
+ void changeKIBColor(void);
+
+
+/**
+ * Zmeni prvky v tooltip-u
+ * Changes items in toolTip
+ *
+ * @since 0.1
+ **/
+ void changeToolTip(void);
+
+/**
+ * Provede nove zpracovani dat a jejich nakresli iconu docku, interni repaint je volan vzdy.
+ * Tato funkce take vola funkci ToolTip.
+ * Makes new processing of data and paints icons of dock, internal repaint is colled always.
+ * This function calls function ToolTips too.
+ * @param always Kdyz je true prorovede vykresleni vzdy, kde je false provede vykresleni jen kdyz je zmenena nejaka hodnota UPS.
+ * @param always When param is true, icon is made always, is one is false icon is makeing when same UPS's value is changed.
+ *
+ * @since 0.4
+ **/
+ void repaintDock ( const bool always = false);
+
+
+
+/**
+ * Nastavi v Menu oznaceni pro aktivni UPS.
+ * Sets mark for active UPS in menu.
+ *
+ * @since 0.1
+ **/
+ void setNewUPS(void);
+
+
+
+
+ signals:
+/**This signal is emited when end of application was selected in menu.
+ * Tento signal je vyslan pokud bylo vybrano v menu ukonceni aplikace.
+ *
+ *
+ * @since 0.1
+ **/
+ void endApplication(void);
+
+/**
+ * Tento signal je vyslan pokud bylo vybrano v menu minimalizace aplikace.
+ * Tento signal is emited when minimize application was selected in menu.
+ *
+ *
+ * @since 0.1
+ **/
+ void minimize(void);
+
+/**
+ * Tento signal je vyslan pokud bylo vybrano v menu polozka preferences.
+ * This signal is emited when item preferences was selected in menu.
+ *
+ * @since 0.1
+ **/
+ void preferences(void);
+
+
+
+/**
+ * Tento signal je vyslan pokud byla vybrana activace hlavniho okna (Main Window).
+ *
+ * @since 0.1
+ **/
+ void activeMainWindow(void);
+
+
+/**
+ * Tento signal je vyslan pokud bylo vybrano zobrazeni promennych;
+ * This signal is emited when showing values was selected.
+ *
+ * @since 0.1
+ **/
+ void printUPSVars(void);
+
+/**
+ * Tento signal je vyslan pokud bylo vybrano provedeni okamziteho prikazu;
+ * This signal is emited when running instant command was selected.
+ *
+ * @since 0.1
+ **/
+ void instComms(void);
+
+/**
+ * Tento signal je vyslan pokud bylo vybrana zmena RW promennych.
+ * This signal is emited when change of RW values was selected.
+ *
+ * @since 0.1
+ **/
+ void RWVars(void);
+
+/**
+ * Tento signal je vyslan pokud bylo vybrana zmena RW promennych.
+ * This signal is emited when refresh connection was selected
+ *
+ * @since 0.1
+ **/
+ void makeRefreshConnection(void);
+
+
+/**
+ * Tento signal je vyslan pokud je vybrana nova UPS;
+ * This signal is emited when new UPS is selected
+ *
+ * @since 0.1
+ **/
+ void UPSChanged(QString name);
+
+
+ protected slots:
+
+ virtual void mousePressEvent(QMouseEvent *e);
+
+/**
+ * @internal
+ * Vola proceduru KAboutApplication, zobrazi informace o teto aplikaci a KDE.
+ * Calls procedure KAboutApplication, shows informations about this application and KDE.
+ *
+ * @since 0.1
+ **/
+ void slotShowMyAbout();
+ void slotExitApplication (void);
+
+/**
+ * @internal
+ * Vysle signal minimize.
+ * Sends signal minimize.
+ *
+ * @since 0.1
+ **/
+ void slotMinimize (void);
+
+
+/**
+ * @internal
+ * Vysle signal peferences.
+ * Sends signal preferences.
+ *
+ * @since 0.1
+ **/
+ void slotPreferences (void);
+
+/**
+ * @internal
+ * Vysle signal printUPSVars.
+ * Sends signal printUPSVars.
+ *
+ * @since 0.1
+ **/
+ void slotPrintUPSVars(void);
+
+/**
+ * @internal
+ * Vysle signal instComms.
+ * Sends signal instComms.
+ *
+ * @since 0.1
+ **/
+ void slotInstComms(void);
+
+
+/**
+ * @internal
+ * Vysle signal RWVars.
+ * Sends signal RWVars.
+ *
+ * @since 0.1
+ **/
+ void slotRWVars(void);
+
+/**
+ * @internal
+ * Vysle signal upsName
+ * Sends signal upsName.
+ *
+ * @since 0.1
+ **/
+ void slotUpsName(int i);
+
+/**
+ * @internal
+ * Vysle signal makeRefreshConnection
+ * Sends signal makeRefreshConnection.
+ *
+ * @since 0.1
+ **/
+ void slotRefreshConnection(void);
+
+
+ protected:
+/**
+ * @internal
+ * Nastavi vse pro vykresleni zakladni ikony.
+ * Tato ikona je kreslena dokud neni navazano spojeni
+ * Sets all for painting of basic icon.
+ * This icon is painted
+ *
+ * @since 0.2
+ **/
+ void initImage(void);
+
+
+
+/**
+ * @internal
+ * Sets tooltip.
+ * Nastavi ToolTip.
+ *
+ * @since 0.1
+ **/
+ void toolTip (int runtime, int status, int batteryCharge, int upsLoad );
+
+
+/**
+ * @internal
+ * Vytvori a hlavni menu panelu.
+ * Makes a main menu of panel
+ *
+ * @since 0.1
+ **/
+ void createMainMenu(void);
+
+/**
+ * @internal
+ * Vytvori a podmenu pro seznam UPS-ek.
+ * Makes a submenu for list ig UPSes.
+ *
+ * @since 0.1
+ **/
+ void createUpsMenu(void);
+
+/**
+ * @internal
+ * Paints a numbers.
+ * Vykresli cisla.
+ * @param number je hodnota cisla.
+ * @param x je leva souradnice cisla
+ * @param y je horni souradnice cisla
+ * @param p je ukazatel na painter
+ *
+ * @since 0.2
+ **/
+ void paintNumbers (int numbers, int x, int y, QPainter* p ); //x,y levy horni roh cisla 1
+
+/**
+ * @internal
+ * Paints a number
+ * Vykresli cislici.
+ * @param number je hodnota cislice.
+ * @param x je leva souradnice cislice
+ * @param y je horni souradnice cislice
+ * @param p je ukazatel na painter
+ *
+ * @since 0.1
+ **/
+ void paintNumber (int x, int y, int number, QPainter *p);
+
+/**
+ * @internal
+ * Paints a char.
+ * Vykresli znak.
+ * @param x je leva souradnice cislice
+ * @param y je horni souradnice cislice
+ * @param p je ukazatel na painter
+ * @param char je vykreslovany znak.
+ *
+ * @since 0.1
+ **/
+ void paintChar (int x, int y, char LCDChar, QPainter *p);
+
+
+/**
+ * @internal
+ * Vykresli pomlcku.
+ * @param x je leva souradnice pomlcky
+ * @param y je horni souradnice pomlcky
+ * @param p je ukazatel na painter
+ *
+ * @since 0.1
+ **/
+ void paintDash (int x, int y, QPainter *p);
+
+
+/**
+ * @internal
+ * Paints runtime layer.
+ * Vykresli vrstvu runtime.
+ *
+ * @since 0.1
+ **/
+ void paintRuntime (int runtime, int status);
+
+/**
+ * @internal
+ * Paints layer for UPS Load
+ * Vykresli vrstvu pro UPS Load.
+ *
+ * @since 0.2
+ **/
+ void paintLoad (int load );
+
+/**
+ * @internal
+ * Paints layer for Battery Charge, only for type general.
+ * Vykresli vrstvu pro Battery Charge.
+ *
+ * @since 0.2
+ **/
+ void paintCharge (int charge );
+
+/**
+ * @internal
+ * Paints layer for UPS Status, only for type general
+ * Vykresli vrstvu pro UPS Status.
+ *
+ * @since 0.2
+ **/
+ void paintStatus (int status );
+
+
+ void paintEvent (QPaintEvent *);
+
+/**
+ * @internal
+ * Paints green point into main layer, only for type picture.
+ * Vykresli do hlavni vrstvy zeleny bod.
+ * Ma vyznam jen pro typ picture.
+ *
+ * @since 0.3
+ **/
+ void paintErrorPoint ( QPainter& paint );
+
+/**
+ * @internal
+ * Paints red point into main layer, only for type picture.
+ * Vykresli do hlavni vrstvy cerveny bod.
+ * Ma vyznam jen pro typ picture.
+ *
+ * @since 0.3
+ **/
+ void paintOKPoint ( QPainter& paint );
+
+/**
+ * @internal
+ * Clean internal variables this class.
+ * Vycisti interni promene teto tridy.
+ *
+ * @since 0.1
+ **/
+ void clearValues(void);
+
+
+ KNutUpsData* m_upsRecords;
+ KNutVarData::SettingDataDef* m_settingData; // v teto strukture jsou ulozeny promene ktere nastavuji konfiguraci
+ KNutVarData::upsInfoDef* m_activeUpsInfo; // values for selected ups
+
+ QPixmap m_mainPix;
+ QPixmap m_errorPix;
+ QPixmap m_connectPix;
+ QPixmap m_upsPix;
+ QPixmap m_battPix;
+
+ QPixmap m_mainLayer1;
+
+ QColor backgroundColor;
+
+ KPopupMenu* m_menu;
+ KPopupMenu* m_upsServerMenu;
+
+ QPixmap *m_statusLayer;
+ QPixmap *m_runtimeLayer;
+ QPixmap *m_loadLayer;
+ QPixmap *m_chargeLayer;
+ QPixmap *m_mainLayer;
+
+ int m_runtimeValue;
+ int m_upsLoadValue;
+ int m_batteryChargeValue;
+ int m_statusValue;
+ int m_statusBatValue;
+ int m_statusWarningValue;
+
+
+ upsConnection m_dataOk; // selects one from four type of icons's view //idle, connecting, connected, error
+ upsConnection m_dataOkOld;
+
+ int m_typeOfIcon;
+ QColor m_myBGColor;
+ unsigned int m_toolTipFlags;
+
+};
+
+#endif
diff --git a/src/knutfrontpanel.cpp b/src/knutfrontpanel.cpp
new file mode 100755
index 0000000..caa5b6e
--- /dev/null
+++ b/src/knutfrontpanel.cpp
@@ -0,0 +1,676 @@
+/***************************************************************************
+ knutfrontpanel.cpp - description
+ -------------------
+ begin : Tue Aug 21 2001
+ copyright : (C) 2001 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+
+#include "knutfrontpanel.h"
+#include "knutvardata.h"
+#include "knutnet.h"
+
+#include <klocale.h>
+#include <kapp.h>
+
+#include <qtooltip.h>
+#include <qstring.h>
+#include <qpaintdevice.h>
+#include <qlayout.h>
+#include <qlcdnumber.h>
+//#include <qframe.h>
+#include <qlabel.h>
+#include <qcolor.h>
+#include <qfont.h>
+#include <qpalette.h>
+#include <qgroupbox.h>
+
+#include <math.h>
+
+KNutFrontPanel::KNutFrontPanel( QPalette* const paletteIn, QWidget *parent, const unsigned int flags, QFont* const panelFonts, const char *name) : QFrame( parent, name ), m_panelFlags(flags) {
+
+ m_myPalette = paletteIn->copy(); // makes deep copy of palette
+ m_upsOkColor = Qt::green;
+ m_upsErrorColor = Qt::red;
+ m_upsBackColor = Qt::white; //backgroundColor();
+ m_helpColor = Qt::black;
+ m_typeOfLCDColor=true;
+ m_LCDNumber1 = 0;
+
+
+ setFrameStyle( QFrame::Box | QFrame::Raised );
+ setLineWidth( 2 );
+
+ if (panelFonts == 0) {
+ m_panelFont =kapp->font(); // sets font - system font
+ m_panelBoldFont = kapp->font();
+ }
+ else {
+ m_panelFont = *panelFonts; // sets font / our selected font
+ m_panelBoldFont = *panelFonts; // change later
+ }
+ m_panelBoldFont.setBold (TRUE);
+ m_panelFont.setBold (FALSE); // sets no bold
+
+ m_mainLayout = new QVBoxLayout(this);
+ m_mainLayout->setMargin ( 10 );
+ m_mainLayout->setSpacing ( 10 );
+
+ // layer for bulbs
+
+ m_bulbsGroupBox = new QGroupBox(this);
+ m_mainLayout->addWidget(m_bulbsGroupBox);
+ m_bulbsGroupBox->setFrameStyle( QFrame::Panel + QFrame::Raised);
+// m_bulbsGroupBox->setFrameStyle( QFrame::Panel + QFrame::Sunken);
+ m_bulbsGroupBox->setLineWidth(2);
+ QVBoxLayout* bulbsLayout = new QVBoxLayout(m_bulbsGroupBox);
+ bulbsLayout->setMargin( 5 );
+
+
+ m_textLabel1 = new QLabel( i18n("UPS On line"),m_bulbsGroupBox);
+ m_frameOL = new KLed (m_upsBackColor,KLed::Off,KLed::Sunken,KLed::Circular,m_bulbsGroupBox);
+ m_frameOL->setMaximumSize(30,30);
+ m_frameOL->setMinimumSize(25,25);
+ QToolTip::add(m_textLabel1,m_textLabel1->text());
+
+ QHBoxLayout* OLLayout = new QHBoxLayout(bulbsLayout);
+ OLLayout->addWidget(m_textLabel1);
+ OLLayout->addSpacing(10);
+ OLLayout->addWidget(m_frameOL);
+ OLLayout->setMargin (3);
+ OLLayout->setStretchFactor(m_textLabel1,20);
+ OLLayout->setStretchFactor(m_frameOL,5);
+
+
+ m_textLabel2 = new QLabel( i18n("UPS On battery"), m_bulbsGroupBox);
+ m_frameOB = new KLed (m_upsBackColor,KLed::Off,KLed::Sunken,KLed::Circular,m_bulbsGroupBox);
+ m_frameOB->setMaximumSize(30,30);
+ m_frameOB->setMinimumSize(25,25);
+ QToolTip::add(m_textLabel2,m_textLabel2->text());
+
+ QHBoxLayout* OBLayout = new QHBoxLayout(bulbsLayout);
+ OBLayout->addWidget(m_textLabel2);
+ OBLayout->addSpacing(10);
+ OBLayout->addWidget(m_frameOB);
+ OBLayout->setMargin (3);
+ OBLayout->setStretchFactor(m_textLabel2,20);
+ OBLayout->setStretchFactor(m_frameOB,5);
+
+
+ m_textLabel3 = new QLabel( i18n("UPS Overload"), m_bulbsGroupBox);
+ m_frameOVER = new KLed (m_upsBackColor,KLed::Off,KLed::Sunken,KLed::Circular,m_bulbsGroupBox);
+ m_frameOVER->setMaximumSize(30,30);
+ m_frameOVER->setMinimumSize(25,25);
+ QToolTip::add(m_textLabel3,m_textLabel3->text());
+
+ m_OLayout = new QHBoxLayout(bulbsLayout);
+ m_OLayout->addWidget(m_textLabel3);
+ m_OLayout->addSpacing(10);
+ m_OLayout->addWidget(m_frameOVER);
+ m_OLayout->setMargin (3);
+ m_OLayout->setStretchFactor(m_textLabel3,20);
+ m_OLayout->setStretchFactor(m_frameOVER,5);
+
+ m_textLabel4 = new QLabel( i18n("UPS Battery low"), m_bulbsGroupBox);
+ m_frameLB = new KLed (m_upsBackColor,KLed::Off,KLed::Sunken,KLed::Circular,m_bulbsGroupBox);
+ m_frameLB->setMaximumSize(30,30);
+ m_frameLB->setMinimumSize(25,25);
+ QToolTip::add(m_textLabel4,m_textLabel4->text());
+
+ m_LBLayout = new QHBoxLayout(bulbsLayout);
+ m_LBLayout->addWidget(m_textLabel4);
+ m_LBLayout->addSpacing(10);
+ m_LBLayout->addWidget(m_frameLB);
+ m_LBLayout->setMargin (3);
+ m_LBLayout->setStretchFactor(m_textLabel4,20);
+ m_LBLayout->setStretchFactor(m_frameLB,5);
+
+ m_textLabel5 = new QLabel( i18n("Replace battery"), m_bulbsGroupBox);
+ m_frameRB = new KLed (m_upsBackColor,KLed::Off,KLed::Sunken,KLed::Circular,m_bulbsGroupBox);
+ m_frameRB->setMaximumSize(30,30);
+ m_frameRB->setMinimumSize(25,25);
+ QToolTip::add(m_textLabel5,m_textLabel5->text());
+
+ m_RBLayout = new QHBoxLayout(bulbsLayout);
+ m_RBLayout->addWidget(m_textLabel5);
+ m_RBLayout->addSpacing(10);
+ m_RBLayout->addWidget(m_frameRB);
+ m_RBLayout->setMargin (3);
+ m_RBLayout->setStretchFactor(m_textLabel5,20);
+ m_RBLayout->setStretchFactor(m_frameRB,5);
+
+ m_textLabel6 = new QLabel( i18n("UPS calibration"), m_bulbsGroupBox);
+ m_frameCAL = new KLed (m_upsBackColor,KLed::Off,KLed::Sunken,KLed::Circular,m_bulbsGroupBox);
+ m_frameCAL->setMaximumSize(30,30);
+ m_frameCAL->setMinimumSize(25,25);
+ QToolTip::add(m_textLabel6,m_textLabel6->text());
+
+ m_CALLayout = new QHBoxLayout(bulbsLayout);
+ m_CALLayout->addWidget(m_textLabel6);
+ m_CALLayout->addSpacing(10);
+ m_CALLayout->addWidget(m_frameCAL);
+ m_CALLayout->setMargin (3);
+ m_CALLayout->setStretchFactor(m_textLabel6,20);
+ m_CALLayout->setStretchFactor(m_frameCAL,5);
+
+
+ m_messGroupBox = new QGroupBox(this);
+ m_mainLayout->addWidget(m_messGroupBox);
+ m_messGroupBox->setFrameStyle( QFrame::Panel + QFrame::Raised);
+// m_messGroupBox->setFrameStyle( QFrame::Panel + QFrame::Sunken);
+ m_messGroupBox->setLineWidth(2);
+ QVBoxLayout* messLayout = new QVBoxLayout(m_messGroupBox);
+ messLayout->setMargin( 3 );
+
+
+ m_textLabel7 = new QLabel( "", m_messGroupBox);
+ QToolTip::add(m_textLabel7,m_textLabel7->text());
+ m_manufacModelLayout = new QHBoxLayout(messLayout);
+ m_manufacModelLayout->addWidget(m_textLabel7);
+ m_manufacModelLayout->setMargin ( 3 );
+
+ m_textLabelManufac = new QLabel( i18n("Manufac. : "), m_messGroupBox);
+ m_textLabel8 = new QLabel( "", m_messGroupBox);
+ QToolTip::add(m_textLabelManufac,m_textLabelManufac->text());
+
+ m_manufacLayout = new QHBoxLayout(messLayout);
+ m_manufacLayout->addWidget(m_textLabelManufac);
+ m_manufacLayout->addWidget(m_textLabel8);
+ m_manufacLayout->addStretch(20);
+ m_manufacLayout->setMargin ( 3 );
+
+ m_textLabelName = new QLabel( i18n("Name")+" : ", m_messGroupBox);
+ m_textLabel9 = new QLabel( "", m_messGroupBox);
+ QToolTip::add(m_textLabelName,m_textLabelName->text());
+
+ m_nameLayout = new QHBoxLayout(messLayout);
+ m_nameLayout->addWidget(m_textLabelName);
+ m_nameLayout->addWidget(m_textLabel9);
+ m_nameLayout->addStretch(20);
+ m_nameLayout->setMargin ( 3 );
+
+ m_textLabelSerial = new QLabel( i18n("Serial : "), m_messGroupBox);
+ m_textLabel10 = new QLabel( "", m_messGroupBox);
+ QToolTip::add(m_textLabelSerial,m_textLabelSerial->text());
+
+ m_serialLayout = new QHBoxLayout(messLayout);
+ m_serialLayout->addWidget(m_textLabelSerial);
+ m_serialLayout->addWidget(m_textLabel10);
+ m_serialLayout->addStretch(20);
+ m_serialLayout->setMargin ( 3 );
+
+ m_textLabelFirm = new QLabel( i18n("Firm. rev. : "), m_messGroupBox);
+ m_textLabel11 = new QLabel( "", m_messGroupBox);
+ QToolTip::add(m_textLabelFirm,m_textLabelFirm->text());
+
+ m_firmLayout = new QHBoxLayout(messLayout);
+ m_firmLayout->addWidget(m_textLabelFirm);
+ m_firmLayout->addWidget(m_textLabel11);
+ m_firmLayout->addStretch(20);
+ m_firmLayout->setMargin ( 3 );
+
+
+ m_valGroupBox = new QGroupBox(this);
+ m_mainLayout->addWidget(m_valGroupBox);
+ m_valGroupBox->setFrameStyle( QFrame::Panel + QFrame::Raised);
+// m_bulbsGroupBox->setFrameStyle( QFrame::Panel + QFrame::Sunken);
+ m_valGroupBox->setLineWidth(2);
+ QVBoxLayout* valLayout = new QVBoxLayout(m_valGroupBox);
+ valLayout->setMargin( 3 );
+
+
+
+ m_textLabelRun = new QLabel( i18n("Runtime")+" : ", m_valGroupBox);
+ QToolTip::add(m_textLabelRun,m_textLabelRun->text());
+
+ m_LCDNumber1 = new QLCDNumber (5,m_valGroupBox);
+ m_LCDNumber1->setSegmentStyle (QLCDNumber::Flat);
+ m_LCDNumber1->setFrameStyle( QFrame::NoFrame );
+ m_LCDNumber1->setMinimumSize(50,20);
+
+ m_runLayout = new QHBoxLayout(valLayout);
+ m_runLayout->addWidget(m_textLabelRun);
+ m_runLayout->addStretch(20);
+ m_runLayout->addWidget(m_LCDNumber1);
+ m_runLayout->setMargin ( 5 );
+
+ m_mainLayout->addStretch(20);
+ m_mainLayout->addSpacing(5);
+
+ setAllPalettes();
+
+ changePanelFont();
+ paintPanel ();
+
+ }
+
+KNutFrontPanel::~KNutFrontPanel(){
+ }
+
+
+//************************************************************
+
+void KNutFrontPanel::paintPanel( void ) {
+
+ if (m_panelFlags & PBOnLine) {
+ m_textLabel1->show();
+ m_frameOL->show();
+ }
+ else {
+ m_textLabel1->hide();
+ m_frameOL->hide();
+ }
+
+ if (m_panelFlags & PBOnBatt) {
+ m_textLabel2->show();
+ m_frameOB->show();
+ }
+ else {
+ m_textLabel2->hide();
+ m_frameOB->hide();
+ }
+
+ if (m_panelFlags & PBOver) {
+ m_OLayout->setMargin ( 3 );
+ m_textLabel3->show();
+ m_frameOVER->show();
+ }
+ else {
+ m_textLabel3->hide();
+ m_frameOVER->hide();
+ m_OLayout->setMargin ( 0 );
+ }
+
+ if (m_panelFlags & PBBattLow) {
+ m_textLabel4->show();
+ m_frameLB->show();
+ m_LBLayout->setMargin ( 3 );
+ }
+ else {
+ m_textLabel4->hide();
+ m_frameLB->hide();
+ m_LBLayout->setMargin ( 0 );
+ }
+
+ if (m_panelFlags & PBRepBatt) {
+ m_textLabel5->show();
+ m_frameRB->show();
+ m_RBLayout->setMargin ( 3 );
+ }
+ else {
+ m_textLabel5->hide();
+ m_frameRB->hide();
+ m_RBLayout->setMargin ( 0 );
+ }
+
+ if (m_panelFlags & PBCal) {
+ m_textLabel6->show();
+ m_frameCAL->show();
+ m_CALLayout->setMargin ( 3 );
+ }
+ else {
+ m_textLabel6->hide();
+ m_frameCAL->hide();
+ m_CALLayout->setMargin ( 0 );
+ }
+
+ if (m_panelFlags & PBMFRMod) {
+ m_textLabel7->show();
+ m_manufacModelLayout->setMargin ( 5 );
+ }
+ else {
+ m_textLabel7->hide();
+ m_manufacModelLayout->setMargin ( 0 );
+ }
+
+
+ if (m_panelFlags & PBMFR) {
+ m_textLabel8->show();
+ m_textLabelManufac->show();
+ m_manufacLayout->setMargin ( 5 );
+ }
+ else {
+ m_textLabel8->hide();
+ m_textLabelManufac->hide();
+ m_manufacLayout->setMargin ( 0 );
+ }
+
+ if (m_panelFlags & PBModel) {
+ m_textLabel9->show();
+ m_textLabelName->show();
+ m_nameLayout->setMargin ( 5 );
+ }
+ else {
+ m_textLabel9->hide();
+ m_textLabelName->hide();
+ m_nameLayout->setMargin ( 0 );
+ }
+
+ if (m_panelFlags & PBSerial) {
+ m_textLabel10->show();
+ m_textLabelSerial->show();
+ m_serialLayout->setMargin ( 5 );
+ }
+ else {
+ m_textLabel10->hide();
+ m_textLabelSerial->hide();
+ m_serialLayout->setMargin ( 0 );
+ }
+
+ if (m_panelFlags & PBFirm) {
+ m_textLabel11->show();
+ m_textLabelFirm->show();
+ m_firmLayout->setMargin ( 5 );
+ }
+ else {
+ m_textLabel11->hide();
+ m_textLabelFirm->hide();
+ m_firmLayout->setMargin ( 0 );
+ }
+
+if ( (m_panelFlags & PBMFRMod) || (m_panelFlags & PBMFR) || (m_panelFlags & PBModel) || (m_panelFlags & PBSerial) ||(m_panelFlags & PBFirm))
+ m_messGroupBox->show();
+else
+ m_messGroupBox->hide();
+
+ if (m_panelFlags & PBRun) {
+// LCDNumber1->show();
+// textLabelRun->show();
+// runLayout->setMargin ( 5 );
+ m_valGroupBox->show();
+ }
+ else {
+// LCDNumber1->hide();
+// textLabelRun->hide();
+// runLayout->setMargin ( 0 );
+ m_valGroupBox->hide();
+ }
+ }
+
+
+int KNutFrontPanel::getPanelHeight( void) { return 0; } ///// correct !!!!!!!!
+
+unsigned int KNutFrontPanel::getPanelFlags( void) { return m_panelFlags; }
+
+void KNutFrontPanel::setPanelFlags(const int upsPanelFlags) { m_panelFlags = upsPanelFlags; }
+
+void KNutFrontPanel::setAllNameUps(const QString panelUpsAllName ){
+ m_textLabel7->setText(panelUpsAllName);
+ QToolTip::remove(m_textLabel7);
+ QToolTip::add(m_textLabel7,panelUpsAllName);
+ }
+
+void KNutFrontPanel::setMFRUps(const QString panelUpsFRM ){
+ m_textLabel8->setText(panelUpsFRM);
+ QToolTip::remove(m_textLabelManufac);
+ QToolTip::add(m_textLabelManufac,m_textLabelManufac->text()+panelUpsFRM);
+ }
+
+void KNutFrontPanel::setNameUps(const QString panelUpsName ){
+ m_textLabel9->setText(panelUpsName);
+ QToolTip::remove(m_textLabelName);
+ QToolTip::add(m_textLabelName,m_textLabelName->text()+panelUpsName);
+ }
+
+void KNutFrontPanel::setSerialUps(const QString panelUpsSerial ){
+ m_textLabel10->setText(panelUpsSerial);
+ QToolTip::remove(m_textLabelSerial);
+ QToolTip::add(m_textLabelSerial,m_textLabelSerial->text()+panelUpsSerial);
+ }
+
+void KNutFrontPanel::setFirmRevUps(const QString upsPanelFormRev ){
+ m_textLabel11->setText(upsPanelFormRev);
+ QToolTip::remove(m_textLabelFirm);
+ QToolTip::add(m_textLabelFirm,m_textLabelFirm->text()+upsPanelFormRev);
+ }
+
+
+void KNutFrontPanel::cleanPanel(void) {
+ m_textLabel7->setText("");
+ m_textLabel8->setText("");
+ m_textLabel9->setText("");
+ m_textLabel10->setText("");
+ m_textLabel11->setText("");
+
+ m_frameOL->setColor(m_upsBackColor);
+ m_frameOL->off();
+ m_frameOB->setColor(m_upsBackColor);
+ m_frameOB->off();
+ m_frameOVER->setColor(m_upsBackColor);
+ m_frameOVER->off();
+ m_frameLB->setColor(m_upsBackColor);
+ m_frameLB->off();
+ m_frameRB->setColor(m_upsBackColor);
+ m_frameRB->off();
+ m_frameCAL->setColor(m_upsBackColor);
+ m_frameCAL->off();
+
+ m_LCDNumber1->display("-:--");
+ m_LCDNumber1->setPalette (palette());
+ }
+
+void KNutFrontPanel::setRuntime(const int runtime) {
+ QString runtimeString;
+
+ if (runtime != knc::numberVarError) {
+ int min = (int)floor(runtime/60);
+ int sec = runtime - (min*60);
+ runtimeString=QString("%1:%2").arg(min,2).arg(sec,2);
+ if (runtimeString[3] == ' ') runtimeString[3]='0';
+ }
+ else runtimeString="-:--";
+
+ m_LCDNumber1->display(runtimeString);
+ }
+
+
+
+void KNutFrontPanel::setPanel(const int panelBulbs) {
+// OFF - 1 ups je vypnuta
+// OL - 2 ups je bezi na sit
+// OB - 4 ups bezi na baterie
+// LB - 8 baterie je vybyta (pokud je zaroven OB dojde k shutdownu)
+// CAL - 16 je spustena calibrace
+// OVER - 128 ups je pretizena
+// RB - 256 ups pozaduje vymenu baterie
+
+
+ if (!(panelBulbs < 0)) {
+ // ups online /na sit
+ if (panelBulbs & KNutNet::OL) {
+ m_frameOL->setColor(m_upsOkColor);
+ m_frameOL->on();
+ m_LCDNumber1->setPalette (m_LCDPaletteOk);
+ m_typeOfLCDColor=true;
+ }
+ else {
+ m_frameOL->setColor(m_upsBackColor);
+ m_frameOL->off();
+ }
+
+ // ups ofline /na baterie
+ if (panelBulbs & KNutNet::OB) {
+ m_frameOB->setColor(m_upsErrorColor);
+ m_frameOB->on();
+ m_LCDNumber1->setPalette (m_LCDPaletteErr);
+ m_typeOfLCDColor=false;
+ }
+ else {
+ m_frameOB->setColor(m_upsBackColor);
+ m_frameOB->off();
+ }
+
+ if (panelBulbs & KNutNet::LB) {
+ m_frameLB->setColor(m_upsErrorColor);
+ m_frameLB->on();
+ }
+ else {
+ m_frameLB->setColor(m_upsBackColor);
+ m_frameLB->off();
+ }
+
+ if (panelBulbs & KNutNet::OVER) {
+ m_frameOVER->setColor(m_upsErrorColor);
+ m_frameOVER->on();
+ }
+ else {
+ m_frameOVER->setColor(m_upsBackColor);
+ m_frameOVER->off();
+ }
+
+ if (panelBulbs & KNutNet::RB) {
+ m_frameRB->setColor(m_upsErrorColor);
+ m_frameRB->on();
+ }
+ else {
+ m_frameRB->setColor(m_upsBackColor);
+ m_frameRB->off();
+ }
+
+ if (panelBulbs & KNutNet::CAL) {
+ m_frameCAL->setColor(m_upsErrorColor);
+ m_frameCAL->on();
+ }
+ else {
+ m_frameCAL->setColor(m_upsBackColor);
+ m_frameCAL->off();
+ }
+ }
+ }
+
+
+/*********************************************************************************************/
+/* */
+/* PUBLIC SLOTS */
+/* */
+/*********************************************************************************************/
+
+
+void KNutFrontPanel::slotSetPanelFont(QFont newPanelFont) {
+
+ m_panelFont = newPanelFont; // nastavime font
+ m_panelBoldFont = newPanelFont; // pozdeji zmenime
+
+ m_panelBoldFont.setBold (TRUE);
+ m_panelFont.setBold (FALSE); // Zrusime bold u panelu
+
+ changePanelFont(); // zmeni pismo
+ paintPanel();
+ }
+
+
+/*********************************************************************************************/
+/* */
+/* PRIVATE FUNCTIONS */
+/* */
+/*********************************************************************************************/
+
+
+void KNutFrontPanel::setLCDPalette (void) {
+ m_LCDPaletteOk = m_myPalette;
+ m_LCDPaletteErr = m_myPalette;
+ //Nastavime barvu pro OK system je online
+ QColorGroup activeColorGroup = m_LCDPaletteOk.active();
+ activeColorGroup.setColor( QColorGroup::Foreground, green);
+
+ m_LCDPaletteOk.setActive(activeColorGroup);
+ m_LCDPaletteOk.setInactive(activeColorGroup);
+
+ //Nastavime Barvu pro Error - System neni online
+ activeColorGroup = m_LCDPaletteErr.active();
+ activeColorGroup.setColor( QColorGroup::Foreground, red);
+ m_LCDPaletteErr.setActive(activeColorGroup);
+ m_LCDPaletteErr.setInactive(activeColorGroup);
+ }
+
+void KNutFrontPanel::setPalette (const QPalette & p){
+
+ m_myPalette = p;
+ setAllPalettes();
+ }
+
+
+void KNutFrontPanel::setAllPalettes (void){
+ QColor myColor;
+
+ QFrame::setPalette (m_myPalette);
+ //QColorGroup myColorGroup = myPalette.active();
+
+// LCDPaletteOk = myPalette;
+// LCDPaletteErr = myPalette;
+
+ setLCDPalette();
+
+ m_bulbsPalette = m_myPalette;
+
+ m_frameOL->setPalette(m_bulbsPalette);
+
+ // we must correct feature of KLed, KLed repaint background when color of item (function KLed::setColor()) is changed only
+ // when we change palette backround only, KLed ignore this change
+
+ myColor = m_frameOL->color();
+ m_frameOL->setColor(m_helpColor); // black is neutral (unprofitable) color for us
+ m_frameOL->setColor(myColor);
+
+ myColor = m_frameOB->color();
+ m_frameOB->setColor(m_helpColor);
+ m_frameOB->setColor(myColor);
+
+ myColor = m_frameLB->color();
+ m_frameLB->setColor(m_helpColor);
+ m_frameLB->setColor(myColor);
+
+ myColor = m_frameOVER->color();
+ m_frameOVER->setColor(m_helpColor);
+ m_frameOVER->setColor(myColor);
+
+ myColor = m_frameRB->color();
+ m_frameRB->setColor(m_helpColor);
+ m_frameRB->setColor(myColor);
+
+ myColor = m_frameCAL->color();
+ m_frameCAL->setColor(m_helpColor);
+ m_frameCAL->setColor(myColor);
+
+
+ if (m_LCDNumber1) {
+ if (m_typeOfLCDColor)
+ m_LCDNumber1->setPalette (m_LCDPaletteOk);
+ else
+ m_LCDNumber1->setPalette (m_LCDPaletteErr);
+ }
+ }
+
+void KNutFrontPanel::changePanelFont (void) {
+ m_textLabel1->setFont(m_panelFont);
+ m_textLabel2->setFont(m_panelFont);
+ m_textLabel3->setFont(m_panelFont);
+ m_textLabel4->setFont(m_panelFont);
+ m_textLabel5->setFont(m_panelFont);
+ m_textLabel6->setFont(m_panelFont);
+
+ m_textLabelManufac->setFont(m_panelFont);
+ m_textLabelName->setFont (m_panelFont);
+ m_textLabelSerial->setFont (m_panelFont);
+ m_textLabelFirm->setFont (m_panelFont);
+ m_textLabelRun->setFont (m_panelFont);
+ m_textLabel7->setFont (m_panelBoldFont);
+ m_textLabel8->setFont (m_panelBoldFont);
+ m_textLabel9->setFont (m_panelBoldFont);
+ m_textLabel10->setFont (m_panelBoldFont);
+ m_textLabel11->setFont (m_panelBoldFont);
+ m_textLabelRun->setFont (m_panelFont);
+ }
+
+
+#include "knutfrontpanel.moc"
diff --git a/src/knutfrontpanel.h b/src/knutfrontpanel.h
new file mode 100755
index 0000000..42242ed
--- /dev/null
+++ b/src/knutfrontpanel.h
@@ -0,0 +1,333 @@
+/***************************************************************************
+ knutfrontpanel.h - description
+ -------------------
+ begin : Tue Aug 21 2001
+ copyright : (C) 2001 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTFRONTPANEL_H
+#define KNUTFRONTPANEL_H
+
+#include <kled.h>
+
+#include <qframe.h>
+
+
+/**
+ *@author Daniel Prynych
+ */
+
+
+class QFont;
+class QPalette;
+class QColor;
+class QLCDNumber;
+class QLabel;
+class QVBoxLayout;
+class QHBoxLayout;
+class QGroupBox;
+
+
+/**
+ * Class is used for feature of panel, which shows informations about UPS.
+ * Trida slouzi pro zobrazeni panelu, ktery zobrazuje informace o UPS.
+ *
+ *
+ * @author Daniel Prynych
+ * @short Main panel
+ * @version 0.7.0
+ */
+class KNutFrontPanel : public QFrame {
+ Q_OBJECT
+ public:
+
+
+enum KNFPConst { DefaultPanelFlags = 1615}; //1+2+4+8+64+512+1024
+
+
+enum panelBulb {
+ PBOnLine = 1, // Panel Bulb On Line
+ PBOnBatt = 2, // Panel Bulb On Battery
+ PBOver = 4, // Panel Bulb Overloading
+ PBBattLow = 8, // Panel Bulb Battery Low
+ PBRepBatt = 16, // Panel Bulb Replace Battery
+ PBCal = 32, // Panel Bulb Calibration
+ PBMFRMod = 64, // FRM + Model
+ PBMFR = 128, // FRM
+ PBModel = 256, // Model
+ PBSerial = 512, // Serial
+ PBFirm = 1024, // Firmware Revision
+ PBRun=2048 // Panel LCD Number Runtime
+ };
+
+
+
+
+
+
+
+/**
+ * Constructor - makes panel, which shows status of UPS
+ * Konstruktor - vytvori panel, ktery zobrazuje stav UPS-ky.
+ *
+ * @param flags Determine which parts will be shown.
+ * @param panelFonts Pointer to font, which is used for painnting, when one is 0 (zero) systems font is used.
+ * @param flags Udava ktere casti se maji na panelu zobrazit.
+ * @param panelFonts Odkaz na fonts ktery se ma pouzit pro vykreslovani, pokud je = 0 (nula) pouzije se systemovy font pri aplikaci.
+ * @since 0.8
+ */
+ KNutFrontPanel( QPalette* const paletteIn, QWidget *parent = 0, const unsigned int flags = DefaultPanelFlags, QFont* const panelFonts = 0L ,const char *name = 0);
+
+/**
+ * Destruktor
+ *
+ * @since 0.3
+ */
+ ~KNutFrontPanel();
+
+
+/**
+ * Vykresli na panelu udaje.
+ * Paints values on panel.
+ *
+ * @since 0.4
+ */
+ void paintPanel( void);
+
+/**
+ * Gets height of panel.
+ * Vrati vysku panelu.
+ * Od verzi 0.4 je vracena vzdy 0. !!!!!!
+ * From version 0.4 always gets 0 !!!!!!!!!!!
+ *
+ * @since 0.4
+ */
+ int getPanelHeight( void);
+
+/**
+ * Vrati nastaveni panelu.
+ * Gets setting of panel (flags of panel).
+ *
+ * @since 0.2
+ */
+ unsigned int getPanelFlags( void);
+
+/**
+ * Nastavi priznaky(nastaveni) panelu. Tyto priznaky nastavuji ktere prvky budou na panelu zobrazeny.
+ * Sets flags of panel. This flags sets what items will be shown on panel.
+ *
+ * @param upsPanelFlags flags od panel.
+ * @param upsPanelFlags priznaky panelu.
+ *
+ * @since 0.2
+ */
+ void setPanelFlags(const int upsPanelFlags);
+
+/**
+ * Shows complete name (name of UPS and manufacturer) of UPS on panel.
+ * Zobrazi na panelu cele jmeno (jmeno UPS a vyrobce ) UPS-ky.
+ *
+ * @param upsPanelName Text which is showed on panel (address of UPS and manufacturer).
+ * @param upsPanelName Text ktery se zobrazi na panelu (adresa UPS-ky a vyrobce).
+ *
+ * @since 0.2
+ */
+void setAllNameUps(const QString panelUpsAllName);
+
+/**
+ * Shows name of UPS on panel.
+ * Zobrazi na panelu jmeno UPS-ky.
+ *
+ * @param upsPanelName Text which is shown on panel (name of UPS).
+ * @param upsPanelName Text ktery se zobrazi na panelu (jmeno UPS-ky).
+ *
+ * @since 0.3
+ */
+ void setNameUps(const QString panelUpsName );
+
+/**
+ * Zobrazi na panelu jmeno vyrobce UPS-ky.
+ * Shows name of UPS's manufacturer on panel.
+ *
+ * @param panelUpsFRM Text ktery se zobrazi na panelu (vyrobce UPS).
+ * @param panelUpsFRM Text which is showed on panel (UPS's manufacturer).
+ *
+ * @since 0.2
+ */
+ void setMFRUps(const QString panelUpsFRM );
+
+/**
+ * Shows serial number of UPS on panel.
+ * Zobrazi na panelu seriove cislo UPS-ky.
+ *
+ * @param panelUpsSerial Text ktery se zobrazi na panelu (seriove cislo UPS-ky).
+ * @param panelUpsSerial Text which is showed on panel (serial number of UPS).
+ *
+ * @since 0.2
+ */
+ void setSerialUps(const QString panelUpsSerial );
+
+/**
+ * Zobrazi na panelu verzi firmwaru cislo UPS-ky.
+ *
+ * @param upsPanelFormRev Text ktery se zobrazi na panelu (verze firmwaru UPS-ky).
+ *
+ * @since 0.2
+ */
+ void setFirmRevUps(const QString upsPanelFormRev );
+
+/**
+ * Offs bulbs on panel. / Cleans panel.
+ * Zhasne indikacni prvky na panelu.
+ *
+ * @since 0.5
+ */
+ void cleanPanel(void);
+
+/**
+ * Shows bulbs on panel.
+ * Rozsviti indikacni prvky na panelu.
+ *
+ * @param panelBulbs Code for select lighted bulbs.
+ * @param panelBulbs Kod pro urceni rozsvicenych indikacnich prvku.
+ *
+ * @since 0.4
+ */
+ void setPanel(const int panelBulbs);
+
+
+/**
+ * Sets value of runtime.
+ * Nastavi hodnotu runtime.
+ *
+ * @param Runtime hodnota ktera se zobrazi jako runtime.
+ *
+ * @since 0.4
+ */
+ void setRuntime(const int runtime);
+
+/**
+ * Sets palette.
+ * Nastavi paletu (palette). Predefinovana funkce from QWidget.
+ *
+ * @param Palette which mail panel is painted.
+ * @param Paleta kterou ma byt vykreslen hlavni panel
+ *
+ * @since 0.1
+ */
+ void setPalette (const QPalette & );
+
+ public slots:
+
+/**
+ * Changes font for painting.
+ * Zmeni font pro vykresleni.
+ *
+ * @param panelFonts Novy font.
+ *
+ * @since 0.2
+ */
+ void slotSetPanelFont(QFont newPanelFont);
+
+ private:
+
+/**
+ * @internal
+ * Sets palettes for LCDLabel.
+ * Nastavi palety pro LCDLabel.
+ *
+ * @since 0.1
+ */
+ void setLCDPalette (void);
+
+/**
+ * @internal
+ * Makes change of palette of all items on based values m_myPalette
+ * Provede zmenu palety vsech prvku na zaklade promenne m_myPalette
+ *
+ * @since 0.1
+ */
+ void setAllPalettes (void);
+
+/**
+ * @internal
+ * Makes font's change of all items, based on values m_panelFont and m_panelBoldFont
+ * Provede zmenu fontu vsech prvku, na zaklade promennych m_panelFont and mpanelBoldFont
+ *
+ * @since 0.1
+ */
+ void changePanelFont (void);
+
+
+ QLabel* m_textLabel1;
+ QLabel* m_textLabel2;
+ QLabel* m_textLabel3;
+ QLabel* m_textLabel4;
+ QLabel* m_textLabel5;
+ QLabel* m_textLabel6;
+ QLabel* m_textLabel7;
+ QLabel* m_textLabel8;
+ QLabel* m_textLabel9;
+ QLabel* m_textLabel10;
+ QLabel* m_textLabel11;
+
+ QLabel* m_textLabelManufac;
+ QLabel* m_textLabelName;
+ QLabel* m_textLabelSerial;
+ QLabel* m_textLabelFirm;
+ QLabel* m_textLabelRun;
+
+
+ KLed* m_frameOL;
+ KLed* m_frameOB;
+ KLed* m_frameOVER;
+ KLed* m_frameLB;
+ KLed* m_frameRB;
+ KLed* m_frameCAL;
+
+ QLCDNumber* m_LCDNumber1;
+ QPalette m_LCDPaletteOk, m_LCDPaletteErr;
+ QPalette m_bulbsPalette;
+
+ QColor m_upsOkColor, m_upsErrorColor, m_upsBackColor, m_helpColor;
+
+ QFont m_panelFont; // font pro header
+ QFont m_panelBoldFont; // font for date
+
+ unsigned int m_panelFlags; // selects which of rows will be shown/ urcuji ktera radka bude rozsvicena 1 OL, 2 OB, 3 OVER, 4 RB, CAL 5 ...
+
+ QPalette m_myPalette;
+
+
+ QGroupBox* m_bulbsGroupBox;
+ QGroupBox* m_messGroupBox;
+ QGroupBox* m_valGroupBox;
+
+ bool m_typeOfLCDColor;
+
+ QVBoxLayout* m_mainLayout;
+
+ QHBoxLayout* m_OLayout;
+ QHBoxLayout* m_LBLayout;
+ QHBoxLayout* m_RBLayout;
+ QHBoxLayout* m_CALLayout;
+ QHBoxLayout* m_manufacModelLayout;
+ QHBoxLayout* m_manufacLayout;
+ QHBoxLayout* m_nameLayout;
+ QHBoxLayout* m_serialLayout;
+ QHBoxLayout* m_firmLayout;
+ QHBoxLayout* m_runLayout;
+};
+
+#endif
+
diff --git a/src/knutinstcomms.cpp b/src/knutinstcomms.cpp
new file mode 100755
index 0000000..e21ebfc
--- /dev/null
+++ b/src/knutinstcomms.cpp
@@ -0,0 +1,137 @@
+/***************************************************************************
+ knutinstcomms.cpp - description
+ -------------------
+ begin : ct ríj 24 2002
+ copyright : (C) 2002 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#include "knutinstcomms.h"
+#include "knutprintupsvar.h"
+#include "knutvardata.h"
+
+#include <kcombobox.h>
+#include <kmessagebox.h>
+
+
+#include <qlayout.h>
+#include <qframe.h>
+#include <qlabel.h>
+#include <qstring.h>
+
+
+KNutInstComms::KNutInstComms(QString* userName, QString* userPassword, const QString uName, const QString password, KNutNet* const upsNet, QWidget* parent, const char* name, const bool modal)
+: KDialogBase(Plain, i18n("Instant commands"),Ok|Cancel,Ok, parent, name, modal, true), m_upsNet(upsNet),m_oldUserName(userName), m_oldUserPassword(userPassword) {
+ upsICommDef upsIComm;
+
+
+ if (m_upsNet->getState() != KNutNet::Connected) { // no connection - no instant commnads
+ KNutVarData::showError (KNutNet::NotConnection);
+ m_upsConnectOk=false;
+ }
+ else {
+ m_upsConnectOk=true;
+ QFrame *page = plainPage();
+ QVBoxLayout *topLayout = new QVBoxLayout( page, 0, spacingHint() );
+ QLabel *label1 = new QLabel (i18n("RUN INSTANT COMMAND"),page,"label1");
+ label1->setAlignment(Qt::AlignHCenter);
+ topLayout->addWidget(label1);
+
+ QLabel *label2 = new QLabel (i18n("Command:"),page,"label2");
+ m_instCommBox = new KComboBox(page,"instcommbox");
+
+ QGridLayout *passLayout = new QGridLayout (3,2,5,"passLayout");
+ QLabel *labelName = new QLabel (i18n("User name:"),page,"labelName");
+ QLabel *labelPassword = new QLabel (i18n("Password:"),page,"labelPassword");
+ m_lineEditName = new KLineEdit( page, "LineEditName" );
+ m_lineEditPassword = new KLineEdit( page, "LineEditName" );
+ if (((*m_oldUserName) == "") && ((*m_oldUserPassword) == "")) {
+ m_lineEditName->setText(uName);
+ m_lineEditPassword->setText(password);
+ }
+ else {
+ m_lineEditName->setText(*m_oldUserName);
+ m_lineEditPassword->setText(*m_oldUserPassword);
+ m_lineEditName->setDisabled(true);
+ m_lineEditPassword->setDisabled(true);
+ }
+
+ // if (!((*oldUserName) == "") || !((*oldUserPassword) == "")) {
+ // if (!((*oldUserName) == "") && ((*oldUserPassword) == "")) {
+ // lineEditName->setDisabled(true);
+ // lineEditPassword->setDisabled(true);
+ // }
+
+ m_lineEditPassword->setEchoMode(QLineEdit::Password);
+
+ topLayout->addLayout(passLayout);
+
+ passLayout->addWidget(label2,0,0);
+ passLayout->addWidget(m_instCommBox,0,1);
+
+ passLayout->addWidget(labelName,1,0);
+ passLayout->addWidget(labelPassword,2,0);
+ passLayout->addWidget(m_lineEditName,1,1);
+ passLayout->addWidget(m_lineEditPassword,2,1);
+
+ topLayout->addStretch(10);
+
+ //loads ComboBox
+ int n = m_upsNet->readNumberComms()+1;
+ for (int i =1; i < n ; i++) { // for se testuje na zacatku pokud je n < 1 neprovede se ani jednou
+ if (!m_upsNet->readIComm(i, upsIComm))
+ m_instCommBox->insertItem(upsIComm.upsCommName);
+ }
+ }
+ }
+
+KNutInstComms::~KNutInstComms(){
+}
+
+
+void KNutInstComms::slotOk() {
+ int error =0;
+
+
+ if (((*m_oldUserName) == "") && ((*m_oldUserPassword) == "")) {
+ // prvni propojeni nastavime jmeno a heslo
+ //for the first connection we have to set name and password
+ if (!( error = m_upsNet->instantCommand(m_instCommBox->currentText(),m_lineEditName->text(),m_lineEditPassword->text(),false))) {
+ (*m_oldUserName) = m_lineEditName->text();
+ (*m_oldUserPassword) = m_lineEditPassword->text();
+ accept();
+ }
+ }
+ else {
+ // for other connection name and password are not setted
+ if (((*m_oldUserName) == m_lineEditName->text()) && ((*m_oldUserPassword) == m_lineEditPassword->text())) {
+ // jen posleme prikaz // sends command only
+ if (!( error = m_upsNet->instantCommand(m_instCommBox->currentText(),m_lineEditName->text(),m_lineEditPassword->text(),true))) accept();
+ }
+// az v pristi verzi
+// else
+// {
+// // odpojime a pripojime
+// // nastavime jmeno a heslo
+// if (!( error = myUpsNet->instantCommand(instCommBox->currentText(),lineEditName->text(),lineEditPassword->text(),false))) {
+// (*oldUserName) = lineEditName->text();
+// (*oldUserPassword) = lineEditPassword->text();
+// accept();
+// }
+// }
+ }
+ if (error) KNutVarData::showError (error);
+ }
+
+//bool KNutInstComms::upsOk (void) { return m_upsConnectOk; }
+
+
diff --git a/src/knutinstcomms.h b/src/knutinstcomms.h
new file mode 100755
index 0000000..55e02b1
--- /dev/null
+++ b/src/knutinstcomms.h
@@ -0,0 +1,97 @@
+/***************************************************************************
+ knutinstcomms.h - description
+ -------------------
+ begin : ct ríj 24 2002
+ copyright : (C) 2002 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTINSTCOMMS_H
+#define KNUTINSTCOMMS_H
+
+#include "knutnet.h"
+
+#include <kdialogbase.h>
+#include <klineedit.h>
+#include <kcombobox.h>
+#include <klocale.h>
+
+
+class QString;
+
+
+/**
+ * This class is graphic interface for runinng of instant commands.
+ * Tato trida je graficke rozhrani pro spusteni okamzitych prikazu.
+ *
+ * @author Daniel Prynych
+ * @short Okamzite prikazy
+ * @version 0.4
+*/
+class KNutInstComms : public KDialogBase {
+public:
+
+
+/**
+ * Construktor - Creates window for select of instant command.
+ * Konstruktor - vytvori okno pro vyber okamziteho prikazu.
+ *
+ * @param uName Determines user name.
+ * @param password Determines passwprd.
+ * @param uName Urcuje uzivatelske jmeno.
+ * @param password Urcuje heslo.
+ * @param upsNet Je odkaz na instanci tridy KNutNet.
+ *
+ * @since 0.4
+ **/
+ KNutInstComms(QString* userName, QString* userPassword, const QString uName, const QString password, KNutNet* const upsNet, QWidget* parent = 0, const char* name = 0, bool const modal = TRUE);
+
+/**
+ * Destruktor
+ *
+ * @since 0.3
+ **/
+ ~KNutInstComms();
+
+
+/**
+ * Vraci true pokud existuje pripojeni na server a vytvorilo se
+ * ovladaci okno pro odeslani prikazu.
+ *
+ * @since 0.3
+ **/
+ bool upsOk (void) { return m_upsConnectOk; };
+
+
+private slots:
+/**
+ * @internal
+ *
+ * Provede akci, da prikaz k provedeni okamziteho prikazu.
+ */
+ virtual void slotOk();
+
+
+private:
+ KLineEdit *m_lineEditName;
+ KLineEdit *m_lineEditPassword;
+ KComboBox *m_instCommBox;
+
+ KNutNet* m_upsNet;
+ bool m_upsConnectOk;
+
+ QString* m_oldUserName;
+ QString* m_oldUserPassword;
+
+};
+
+#endif
diff --git a/src/knutmainwindow.cpp b/src/knutmainwindow.cpp
new file mode 100644
index 0000000..c5aaf16
--- /dev/null
+++ b/src/knutmainwindow.cpp
@@ -0,0 +1,813 @@
+/***************************************************************************
+ knutmainwindow.cpp - description
+ -------------------
+ begin : Po cen 16 2003
+ copyright : (C) 2003 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+
+#include "knutmainwindow.h"
+#include "knutvardata.h"
+
+#include <kmessagebox.h>
+#include <kstdaction.h>
+#include <kconfig.h>
+#include <ksimpleconfig.h>
+#include <kstatusbar.h>
+#include <kkeydialog.h>
+#include <kprogress.h>
+
+
+#include <qfont.h>
+#include <qpalette.h>
+#include <qbrush.h>
+#include <qcolor.h>
+#include <qstring.h>
+#include <qscrollview.h>
+#include <qlayout.h>
+#include <qiconset.h>
+#include <qstring.h>
+#include <qstringlist.h>
+#include <qlabel.h>
+#include <qsplitter.h>
+//#include <qprogressbar.h>
+
+
+
+
+#include <math.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include <iostream>
+
+
+
+extern const char *nameUpsVars1[];
+extern const char *nameUpsVars2[];
+
+const char *descrOfConnection = I18N_NOOP("test of conection from 5");
+
+
+
+KNutMainWindow::KNutMainWindow(QStringList *tListKNutEvent, KNutVarData::upsInfoDef* tActiveUpsInfo, KNutVarData::SettingDataDef* tSettingData, KNutUpsData* tUpsRecords, KNutVarData* tAnalogRecords, QWidget* parent, const char *name) : KMainWindow(parent, name),
+ m_listKNutEvent(tListKNutEvent), m_activeUpsInfo(tActiveUpsInfo),m_settingData (tSettingData),
+ m_upsRecords(tUpsRecords), m_analogRecords (tAnalogRecords) {
+
+
+
+ m_settingData->activatedMainWindow=true; //information about state of mainWindow
+
+ initVars();
+ initStatusBar();
+ initAction();
+// createGUI ("/home/dan/Projekty/knutclient/src/knutclientui.rc"); // pred distribuci nezapomenout odstranit retezec
+ // createGUI vytvori zakladni strukturu podle souboru knutclientui.rc
+ createGUI ();
+ initToolBar ();
+
+
+ m_descriptionAction->setChecked(m_settingData->useDescription);
+
+ //sets input frequency and input voltage
+ //nastavime vstupni frekvenci a vstupni napeti
+ m_analogRecords->setFrequency(m_settingData->inputFrequency);
+ m_analogRecords->setVoltage(m_settingData->inputVoltage);
+
+ //sets palette for analog panels
+ // nastavime paletu pro analogove panely
+ if (m_settingData->customBAnalogColor) {
+ m_aPanelPalette.setColor(QPalette::Active,QColorGroup::Background,m_settingData->aPanelBackgroundColor);
+ m_aPanelPalette.setColor(QPalette::Inactive,QColorGroup::Background,m_settingData->aPanelBackgroundColor);
+ }
+
+ if (m_settingData->customBColor) {
+ m_areaPalette.setColor(QPalette::Active,QColorGroup::Background,m_settingData->mainBackgroundColor);
+ m_areaPalette.setColor(QPalette::Inactive,QColorGroup::Background,m_settingData->mainBackgroundColor);
+ }
+
+
+ // makes main area // Vytvorime hlavni plochu
+ m_area = new QLabel (this);
+ setCentralWidget (m_area);
+
+ QHBoxLayout* mainLayout = new QHBoxLayout(m_area);
+ m_mainSplit = new QSplitter(Qt::Horizontal,m_area);
+ m_mainSplit->setOpaqueResize(true);
+
+ mainLayout->addWidget(m_mainSplit);
+ if (m_settingData->customBPanelColor) {
+ m_mPanelPalette.setColor(QPalette::Active,QColorGroup::Background,m_settingData->mPanelBackgroundColor);
+ m_mPanelPalette.setColor(QPalette::Inactive,QColorGroup::Background,m_settingData->mPanelBackgroundColor);
+ }
+
+ QScrollView* panelSV = new QScrollView(m_mainSplit,"panelSV");
+ if (m_settingData->customFont)
+ m_frontPanel = new KNutFrontPanel (&m_mPanelPalette,m_mainSplit,m_settingData->panelFlags,&(m_settingData->mPanelFont),"FrontPanel");
+ else
+ m_frontPanel = new KNutFrontPanel (&m_mPanelPalette,m_mainSplit,m_settingData->panelFlags,&(m_settingData->systemFont),"FrontPanel");
+ panelSV->addChild(m_frontPanel);
+ panelSV->setResizePolicy ( QScrollView::AutoOneFit ) ;
+ m_mainSplit->setResizeMode (panelSV,QSplitter::FollowSizeHint);
+
+ m_panelMeter = new KNutPanelMeter(m_aPanelPalette,m_activeUpsInfo,m_settingData,m_analogRecords,m_mainSplit);
+ m_mainSplit->setResizeMode (m_panelMeter,QSplitter::Stretch );
+
+ m_area->setPalette(m_areaPalette);
+ m_panelMeter->setPalette(m_areaPalette);
+
+ // sets Combo a actives connections to meter panels
+ // Nastavime COMBO a pripadne aktivujeme spojeni na merici panely
+ int activeUpsNameIndex = activeMainCombo ();
+ if (activeUpsNameIndex != -1) toolBar(0)->getCombo(1)->setCurrentItem( activeUpsNameIndex );
+
+ showUpsData();
+ setGeometry (m_settingData->x,m_settingData->y,m_settingData->width,m_settingData->height);
+ show();
+
+
+ //message has to include into status bar after showing window,
+ // only for KDE relase < 3.0.0
+
+ // jinak se nastavi minimalni velikost ne mensi nez delka aktivni zpravy.
+
+ initStatusBarMessage();
+ }
+
+
+
+void KNutMainWindow::addComboStatusItem (const QString text, const QString name) {
+ if (m_infoCombo->count() >= (int)knc::maxCountKNutEvent) m_infoCombo->removeItem(0);
+ if (m_listKNutEvent->count() > knc::maxCountKNutEvent) m_listKNutEvent->remove(m_listKNutEvent->begin());
+
+ QString dateTime(QDate::currentDate().toString());
+ dateTime +=" " + QTime::currentTime().toString();
+ if (name.isEmpty()) {
+ m_infoCombo->insertItem(dateTime+" "+text);
+ m_listKNutEvent->append(dateTime+" "+text);
+ }
+ else {
+ m_infoCombo->insertItem(dateTime+" "+name+" : "+text);
+ m_listKNutEvent->append(dateTime+" "+name+" : "+text);
+ }
+ m_infoCombo->setCurrentItem(m_infoCombo->count()-1);
+ if (m_listKNutEvent->count() > knc::maxCountKNutEvent) m_listKNutEvent->remove(m_listKNutEvent->begin());
+ }
+
+
+KNutMainWindow::~KNutMainWindow(void) {
+
+ m_settingData->height = height();
+ m_settingData->width = width();
+ m_settingData->y = y();
+ m_settingData->x = x();
+
+ delete m_frontPanel;
+ delete m_panelMeter;
+ }
+
+
+void KNutMainWindow::setConfig (unsigned int changeSetting) {
+
+
+//qDebug ("KNutMainWindow::setConfig");
+ KNutVarData::VarStrucDef analogMemberData;
+ bool repaintVoltagePanels = false;
+ bool repaintFrequencyPanels = false;
+ bool repaintAllPanels = false;
+ bool repaintOAPanels = false;
+
+ // Main Setting
+
+ // Nastavime zmenu barvy pozadi
+ // sets background color
+ if (changeSetting & KNutPrefDlg::ChangeCustomBColor) {
+ if (!m_settingData->customBColor) { // nastavime barvu pozadi podle systemu
+ m_area->setPalette (m_mainPalette); // we set background color based on system
+ m_panelMeter->setPalette (m_mainPalette);
+ repaint();
+ }
+ else {
+ m_areaPalette.setColor(QPalette::Active,QColorGroup::Background,m_settingData->mainBackgroundColor);
+ m_areaPalette.setColor(QPalette::Inactive,QColorGroup::Background,m_settingData->mainBackgroundColor);
+ m_area->setPalette (m_areaPalette);
+ m_panelMeter->setPalette (m_areaPalette);
+ repaint();
+ }
+ }
+ else {
+ if (changeSetting & KNutPrefDlg::ChangeMBColor ) {
+ m_areaPalette.setColor(QPalette::Active,QColorGroup::Background,m_settingData->mainBackgroundColor);
+ m_areaPalette.setColor(QPalette::Inactive,QColorGroup::Background,m_settingData->mainBackgroundColor);
+ m_area->setPalette (m_areaPalette);
+ m_panelMeter->setPalette (m_areaPalette);
+ repaint();
+ }
+ }
+
+ // Sets background for panels
+ // sets frequence
+ // sets voltage
+ // XFer is switch-on and one exist for this UPS
+
+
+ if ((changeSetting & KNutPrefDlg::ChangeXFer) || // je provedena nejaka zmena na napeti nebo frekvence
+ (changeSetting & KNutPrefDlg::ChangeVoltage) || (changeSetting & KNutPrefDlg::ChangeFrequency)) {
+
+ if ((changeSetting & KNutPrefDlg::ChangeXFer) && (m_settingData->lowHighXfer) && (m_existLowHighXfer)) {
+ // xfer was activated
+ if (changeSetting & KNutPrefDlg::ChangeXFer) {
+ if (abs((int)(230 - (m_lowXfer + (m_highXfer - m_lowXfer) /2))) > abs((int)(120 - (m_lowXfer + (m_highXfer - m_lowXfer) /2)))) {
+ m_analogRecords->setVoltage(120);
+ m_analogRecords->setFrequency(60);
+ }
+ else {
+ m_analogRecords->setVoltage(230);
+ m_analogRecords->setFrequency(50);
+ }
+ m_analogRecords->setXfer(m_lowXfer,m_highXfer);
+ repaintVoltagePanels = true;
+ repaintFrequencyPanels = true;
+ }
+ }
+ else {
+ // XFER neni aktivovano nebo je nepodporuje UPS
+ // XFER isn;t activated or XFER isn't supported by UPS
+ if ((changeSetting & KNutPrefDlg::ChangeVoltage) || ((changeSetting & KNutPrefDlg::ChangeXFer))) {
+ // byla aktivovana zmena napeti nebo zmena xfer a zaroven ho ups podporuje
+ m_analogRecords->setVoltage(m_settingData->inputVoltage);
+ repaintVoltagePanels=true;
+ }
+ if ((changeSetting & KNutPrefDlg::ChangeFrequency) || ((changeSetting & KNutPrefDlg::ChangeXFer))) {
+ // byla aktivovana zmena napeti nebo zmena xfer a zaroven ho ups podporuje
+ m_analogRecords->setFrequency(m_settingData->inputFrequency);
+ repaintFrequencyPanels=true;
+ }
+ }
+ }
+
+ // Analog setting
+ // now DigitalProcesing of pointer
+ if (changeSetting & KNutPrefDlg::ChangeTypeOfDigProcessing) { //type of digital processing was changed
+ m_panelMeter->changeAnalogPanelsDigProcessing(); //paint pointers with new digotal processing
+ }
+
+ if ((changeSetting & KNutPrefDlg::ChangeCustomAPanelBColor) || // barva panelu je zmenena, panel color is changed
+ (changeSetting & KNutPrefDlg::ChangeAPBColor)) {
+ if (m_settingData->customBAnalogColor) {
+ m_aPanelPalette.setColor(QPalette::Active,QColorGroup::Background,m_settingData->aPanelBackgroundColor);
+ m_aPanelPalette.setColor(QPalette::Inactive,QColorGroup::Background,m_settingData->aPanelBackgroundColor);
+ repaintAllPanels=true;
+ m_panelMeter->setAnalogBG(m_aPanelPalette);
+ }
+ else {
+ m_aPanelPalette = m_mainPalette;
+ repaintAllPanels=true;
+ m_panelMeter->setAnalogBG(m_aPanelPalette);
+ }
+ }
+
+ if ((changeSetting & KNutPrefDlg::ChangeCustomAPanelOColor) || // je provedena zmena barvy panelu
+ (changeSetting & KNutPrefDlg::ChangeAPOColor)) {
+ if (m_settingData->customOAnalogColor) {
+ repaintAllPanels=true;
+ repaintOAPanels=true;
+ }
+ else {
+ repaintAllPanels=true;
+ repaintOAPanels=true;
+ }
+ }
+ // regeneration of panel uses for setting Main and setting Analog
+ // pregenerovani panelu slozi pro setting Main a setting Analog
+ m_panelMeter->repaintAnalogPanels (repaintFrequencyPanels, repaintVoltagePanels, repaintAllPanels);
+
+ if (m_activeUpsInfo->record.name != "") {
+ m_panelMeter->setSize();
+ m_mainSplit->refresh();
+ }
+
+ // UPS Setting
+ if (changeSetting & KNutPrefDlg::ChangeUpsSetting ) activeMainCombo();
+ else {
+ if (changeSetting & KNutPrefDlg::ChangeUpsCount) activeMainCombo();
+ }
+
+ // Main Panel Setting
+ // change of background color
+ // zmena barvy pozadi;
+ if (changeSetting & KNutPrefDlg::ChangeCustomMPanelBColor) {
+ if (!m_settingData->customBPanelColor) { // nastavime barvu pozadi podle systemu
+ m_frontPanel->setPalette (m_mainPalette);
+ }
+ else {
+ m_mPanelPalette.setColor(QPalette::Active,QColorGroup::Background,m_settingData->mPanelBackgroundColor);
+ m_mPanelPalette.setColor(QPalette::Inactive,QColorGroup::Background,m_settingData->mPanelBackgroundColor);
+ m_frontPanel->setPalette (m_mPanelPalette);
+ }
+ }
+ else {
+ if (changeSetting & KNutPrefDlg::ChangeMPBColor ) {
+ m_mPanelPalette.setColor(QPalette::Active,QColorGroup::Background,m_settingData->mPanelBackgroundColor);
+ m_mPanelPalette.setColor(QPalette::Inactive,QColorGroup::Background,m_settingData->mPanelBackgroundColor);
+ m_frontPanel->setPalette (m_mPanelPalette);
+ }
+ }
+
+ if (changeSetting & KNutPrefDlg::ChangeMainPanelSetting ) {
+ if (m_settingData->panelFlags != m_frontPanel->getPanelFlags()) {
+ m_frontPanel->setPanelFlags(m_settingData->panelFlags);
+ //aktivujema a presuneme prvky panelu
+ // activates and moves items of panel
+ m_frontPanel->paintPanel();
+ }
+ }
+
+ // Font panel setting
+ if (changeSetting & KNutPrefDlg::ChangeAnalogFont ) {
+ QFont newAnalogFont;
+ if (m_settingData->customFont) {
+ newAnalogFont=m_settingData->aPanelFont;
+ }
+ else {
+ newAnalogFont=m_settingData->systemFont;
+ }
+
+ m_panelMeter->slotSetPanelsFont(newAnalogFont);
+ }
+ if (changeSetting & KNutPrefDlg::ChangePanelFont ) {
+ QFont newPanelFont;
+ if (m_settingData->customFont) {
+ m_frontPanel->slotSetPanelFont(m_settingData->mPanelFont);
+ }
+ else {
+ m_frontPanel->slotSetPanelFont(m_settingData->systemFont);
+ }
+ }
+ }
+
+
+
+
+void KNutMainWindow::showUpsData (void) {
+
+//qDebug ("KNutMainWindow::showUpsData start");
+
+
+ if ((m_activeUpsInfo->upsNet != 0L) && (!m_activeUpsInfo->netError) &&
+ (m_activeUpsInfo->upsDriverState == knc::connected)) {
+ int runtimeVal;
+ QString nutStringVar;
+ bool okFloat;
+// activeUpsInfo->oldStatus=KNutNet::initStatus;
+
+ // Nastaveni nemenych dat jsou precteny pouze jednou, predpoklada se jejich nemenost
+ // setting of unchange data, ones are reading only one.
+ nutStringVar = m_activeUpsInfo->upsNet->readStringVar(m_activeUpsInfo->lowxferVar);
+ switch (m_activeUpsInfo->nutVariables) {
+ case 1:
+ m_manufacturer = m_activeUpsInfo->upsNet->readStringVar("MFR");
+ m_upsModel = m_activeUpsInfo->upsNet->readStringVar("MODEL");
+ m_serial = m_activeUpsInfo->upsNet->readStringVar("SERIAL");
+ m_firmrev = m_activeUpsInfo->upsNet->readStringVar("FIRMREV");
+ break;
+ case 2:
+ m_manufacturer = m_activeUpsInfo->upsNet->readStringVar("ups.mfr");
+ m_upsModel = m_activeUpsInfo->upsNet->readStringVar("ups.model");
+ m_serial = m_activeUpsInfo->upsNet->readStringVar("ups.serial");
+ m_firmrev = m_activeUpsInfo->upsNet->readStringVar("ups.firmware");
+ break;
+ }
+ QString allUpsName = m_manufacturer + " " + m_upsModel;
+ m_frontPanel->setAllNameUps (allUpsName);
+ m_frontPanel->setMFRUps (m_manufacturer);
+ m_frontPanel->setNameUps (m_upsModel);
+ m_frontPanel->setSerialUps (m_serial);
+ m_frontPanel->setFirmRevUps (m_firmrev);
+ // try if LOWXFER and HIGHXFER or our values are existed
+ //Zjistime zda existuji LOWXFER a HIGHXFER pripadne jeji hodnoty
+
+ if (nutStringVar.isNull()) {
+ m_lowXfer =-1;
+ m_highXfer=-1;
+ m_existLowHighXfer = false;
+ }
+ else {
+ m_lowXfer = atof(nutStringVar);
+ nutStringVar = m_activeUpsInfo->upsNet->readStringVar(m_activeUpsInfo->highxferVar);
+ if (nutStringVar.isEmpty()) {
+ m_highXfer = -1;
+ m_existLowHighXfer = false;
+ }
+ else {
+ m_highXfer = atof(nutStringVar);
+ m_existLowHighXfer = true;
+ }
+ }
+ int upsStatus=0;
+ if ((upsStatus = m_activeUpsInfo->upsNet->readStatus ()) != -1)
+ m_frontPanel->setPanel(upsStatus);
+
+ if ( !m_activeUpsInfo->upsNet->existName(m_activeUpsInfo->runtimeVar)) {
+ nutStringVar = m_activeUpsInfo->upsNet->readStringVar(m_activeUpsInfo->runtimeVar);
+ if (nutStringVar.isEmpty()) runtimeVal=knc::numberVarError;
+ else {
+ runtimeVal=(int)nutStringVar.toFloat(&okFloat);
+ if (!okFloat) runtimeVal = knc::numberVarError;
+ }
+ }
+ else runtimeVal=knc::numberVarError;
+ m_frontPanel->setRuntime(runtimeVal);
+
+ m_panelMeter->deActivateAnalogs();
+
+ // pokud je pouzito XFER nastavime hodnoty
+ // when XFER is used we set values
+ if (m_settingData->lowHighXfer) {
+ // xfer je nastaveno
+ // xfer is seted
+ if (m_existLowHighXfer) {
+ if (abs((int)(230 - (m_lowXfer + (m_highXfer - m_lowXfer) /2))) > abs((int)(120 - (m_lowXfer + (m_highXfer - m_lowXfer) /2)))) {
+ m_analogRecords->setVoltage(120);
+ m_analogRecords->setFrequency(60);
+ }
+ else {
+ m_analogRecords->setVoltage(230);
+ m_analogRecords->setFrequency(50);
+ }
+ m_analogRecords->setXfer(m_lowXfer,m_highXfer);
+ }
+ }
+
+//qDebug ("KNutMainWindow::showUpsData 1");
+ m_panelMeter->activateAnalogs(); // makes panel and makes background of panel
+ repaintAnalogs(false);
+//qDebug ("KNutMainWindow::showUpsData 2");
+ m_panelMeter->setSize(true);
+//qDebug ("KNutMainWindow::showUpsData 3");
+ m_mainSplit->refresh();
+ // doesn't repaint analog pointers, because pointers will be repainted twice
+//qDebug ("KNutMainWindow::showUpsData 4");
+// repaintAnalogs(false); // don't make this
+//qDebug ("KNutMainWindow::showUpsData 5");
+ }
+ else {
+ cleanPanels();
+ }
+ }
+
+
+void KNutMainWindow::zeroingPanels (void) {
+
+ m_panelMeter->zeroingPanels();
+ m_frontPanel->setRuntime(knc::numberVarError);
+ m_frontPanel->setPanel(0);
+ }
+
+
+void KNutMainWindow::hideUpsData (void) {
+ m_frontPanel->cleanPanel();
+ }
+
+void KNutMainWindow::setCombo (QString name) {
+ if (toolBar(0)->getCombo(1)->currentText() != name) toolBar(0)->getCombo(1)->setCurrentText(name);
+ }
+
+void KNutMainWindow::repaintPanel (void) {
+ QString nutStringVar;
+
+ if (m_activeUpsInfo->upsNet == 0) return;
+ if (!m_activeUpsInfo->upsNet->existName(m_activeUpsInfo->runtimeVar)) {
+ nutStringVar = m_activeUpsInfo->upsNet->readStringVar(m_activeUpsInfo->runtimeVar);
+ if (nutStringVar.isEmpty()) m_frontPanel->setRuntime(0);
+ else m_frontPanel->setRuntime( nutStringVar.toInt());
+ }
+ else m_frontPanel->setRuntime(knc::numberVarError);
+ // precteme status a nastavime zarovky panelu
+ int status = m_activeUpsInfo->upsNet->readStatus();
+ m_frontPanel->setPanel(status);
+ }
+
+
+/// je volan vzdy po timeoutu
+/// this function is called after timeout always
+void KNutMainWindow::repaintAnalogs ( bool run ) {
+//qDebug ("KNutMainWindow::repaintAnalogs");
+
+
+ QString nutStringVar;
+ float numVar;
+ bool newRange = false;
+
+ if ((m_settingData->lowHighXfer) && (m_existLowHighXfer)) {
+ QString nutStringVar;
+
+ nutStringVar = m_activeUpsInfo->upsNet->readStringVar(m_activeUpsInfo->lowxferVar);
+ if (! nutStringVar.isEmpty()) {
+ float helpLowXfer = nutStringVar.toFloat();
+ nutStringVar = m_activeUpsInfo->upsNet->readStringVar(m_activeUpsInfo->highxferVar);
+ if (! nutStringVar.isEmpty()) {
+ float helpHighXfer = nutStringVar.toFloat();
+ if ((helpLowXfer != m_lowXfer) || (helpHighXfer != m_highXfer)) {
+ m_lowXfer=helpLowXfer;
+ m_highXfer=helpHighXfer;
+ m_analogRecords->setXfer(m_lowXfer,m_highXfer);
+ newRange = true;
+ }
+ }
+ }
+ }
+
+//qDebug ("KNutMainWindow::repaintAnalogs 1");
+
+ for (int i=0; i< knc::NumberOfVars; i++) {
+ if (m_activeUpsInfo->record.upsVarCode[i] != 0) { // jistota pokud by nam to nekde propadlo
+ switch (m_activeUpsInfo->nutVariables) {
+ case 1:
+ nutStringVar = m_activeUpsInfo->upsNet->readStringVar ((char *)nameUpsVars1[m_activeUpsInfo->record.upsVarCode[i]]);
+ break;
+ case 2:
+ nutStringVar = m_activeUpsInfo->upsNet->readStringVar ((char *)nameUpsVars2[m_activeUpsInfo->record.upsVarCode[i]]);
+ break;
+ }
+//qDebug ("KNutMainWindow::repaintAnalogs 2 ");
+
+ if (nutStringVar.isEmpty()) numVar=0;
+ else numVar = nutStringVar.toFloat();
+
+ m_panelMeter->repaintScaleAnalogPanel (i, numVar);
+ if (newRange) m_panelMeter->repaintAnalogPanels (true, true, false); //freq volt
+ m_panelMeter->repaintAnalogPointer(i,numVar,run);
+ }
+ } // end for
+//qDebug ("KNutMainWindow::repaintAnalogs 3 ");
+ }
+
+
+
+void KNutMainWindow::cleanPanels (void) {
+
+ m_frontPanel->cleanPanel();
+ m_panelMeter->deActivateAnalogs();
+ m_panelMeter->setSize(false);
+ m_mainSplit->refresh();
+ }
+
+void KNutMainWindow::startConnectPB ( const int count ) {
+ m_connectProggresBar->setTotalSteps(count);
+ m_connectProggresBar->setProgress(1);
+ m_connectProggresBar->show();
+ }
+
+
+void KNutMainWindow::setProgressConnectPB ( const int progress ) {
+ m_connectProggresBar->setProgress(progress);
+ }
+
+
+void KNutMainWindow::hideConnectPB ( void ) {
+ m_connectProggresBar->setProgress(0);
+ m_connectProggresBar->hide();
+ }
+
+
+/*********************************************************************************************/
+/* */
+/* PRIVATE SLOTS */
+/* */
+/*********************************************************************************************/
+
+
+//this SLOT is for older KDE only
+void KNutMainWindow::slotShowToolBar(void) {
+
+ if(toolBar("mainToolBar")->isVisible()) toolBar("mainToolBar")->hide();
+ else toolBar("mainToolBar")->show();
+ }
+
+
+void KNutMainWindow::slotShowStatusBar(void) {
+
+ if(statusBar()->isVisible()) {
+ statusBar()->hide();
+ }
+ else {
+ statusBar()->show();
+ }
+ }
+
+void KNutMainWindow::slotDescription(void) {
+
+ if (m_descriptionAction->isChecked()) {
+ if (!m_activeUpsInfo->upsNet->isDescription()) m_activeUpsInfo->upsNet->getDescription();
+ m_settingData->useDescription=true;
+ }
+ else m_settingData->useDescription=false;
+ emit saveConf();
+ }
+
+
+void KNutMainWindow::slotPrintUPSVars(void) {
+
+ emit showUPSVars();
+}
+
+
+void KNutMainWindow::slotInstComms(void) {
+
+ emit makeInstComms();
+ }
+
+void KNutMainWindow::slotRWVars(void) {
+
+ emit makeRWVars();
+ }
+
+void KNutMainWindow::slotRefreshConnection(void) {
+
+ emit makeRefreshConnection();
+ }
+
+
+void KNutMainWindow::slotChangeRWVars ( QString ) {
+ }
+
+
+
+void KNutMainWindow::closeEvent( QCloseEvent *e ){
+
+ m_settingData->activatedMainWindow=false; //information about state of mainWindow
+ e->accept();
+ }
+
+
+
+void KNutMainWindow::slotConfigureKeys() {
+
+ KKeyDialog::configure( actionCollection(), this );
+ }
+
+
+void KNutMainWindow::slotCloseKnutClient (void) {
+ if (m_settingData->areYouSure) {
+ if (KMessageBox::warningYesNo (0,i18n("Are you sure ?")) == 3)
+ emit endApplication();
+ }
+ else emit endApplication();
+ }
+
+
+
+
+ void KNutMainWindow::slotChangeUPS (const QString &name) {
+ emit UPSChanged (name);
+ }
+
+
+void KNutMainWindow::slotPreferencesUps() {
+ emit preferenceUps();
+ }
+
+
+/*********************************************************************************************/
+/* */
+/* PRIVATE FUNCTIONS */
+/* */
+/*********************************************************************************************/
+
+
+
+void KNutMainWindow::initStatusBar ( void ) {
+ // sets main message if statusbar
+ // nastavime hlavni hlaseni v statusbaru
+
+ // QString progressString("%v ");// += descrOfConnection;
+// progressString.append(descrOfConnection);
+
+ m_progressFormatString.append("%v ");
+ m_progressFormatString.append(descrOfConnection);
+ m_infoCombo = new KComboBox (statusBar(),"infoCombo");
+ m_infoCombo->setMaxCount(knc::maxCountKNutEvent+1); // nastavime maximalni pocet polozek v Combu
+ // pro rezervu pridame jeste jednu
+//sets maximal if items in Combo
+ statusBar()->addWidget(m_infoCombo,10,false);
+
+ m_connectProggresBar = new KProgress(statusBar(),"connectProgressBar");
+ statusBar()->addWidget(m_connectProggresBar,5,false);
+ m_connectProggresBar->setProgress(0);
+// m_connectProggresBar->setFormat("%v test of conection from 5");
+ m_connectProggresBar->setFormat(m_progressFormatString);
+ m_connectProggresBar->hide();
+ }
+
+
+void KNutMainWindow::initStatusBarMessage ( void ) {
+ // loads data into comboBox
+ QStringList::iterator it;
+
+ for ( it = m_listKNutEvent->begin(); it != m_listKNutEvent->end(); ++it ) {
+ m_infoCombo->insertItem((*it));
+ }
+ statusBar()-> setItemAlignment(0,Qt::AlignHCenter|Qt::AlignVCenter);
+ m_infoCombo->setCurrentItem(m_infoCombo->count()-1);
+ }
+
+
+void KNutMainWindow::initToolBar ( void ) {
+
+ QLabel *upsNazev = new QLabel ("UPS : ",toolBar("mainToolBar"));
+ // upsNazev is connected on toolBaar, dosn't need to call desctructor
+ toolBar ("mainToolBar")->insertWidget (0,upsNazev->sizeHint().width(),upsNazev);
+ toolBar ("mainToolBar")->insertCombo("",1,false, SIGNAL (activated (const QString &)),this,SLOT (slotChangeUPS (const QString &)));
+ // bude se pouze vybirat-------------------^^^
+ KComboBox *combo = toolBar("mainToolBar")->getCombo(1);
+ combo->clear();
+ toolBar("mainToolBar")->setBarPos (KToolBar::Top);
+ //sets toolbarr no movable / nastavime toolBar nepresouvatelny
+ setToolBarsMovable(false);
+ }
+
+
+void KNutMainWindow::initAction ( void ) {
+
+ // KAction and KStdAction must be to make before command createGUI, function initToolBar is runed after create GUI
+ m_quit = KStdAction::quit (this, SLOT (slotCloseKnutClient()), actionCollection());
+ m_quit->setStatusText(i18n("Quits the application"));
+
+ m_preferencesUps = KStdAction::preferences (this, SLOT (slotPreferencesUps()), actionCollection(),"options_configure");
+ new KAction(i18n("&Showing UPS variables and commands"),0,this,SLOT(slotPrintUPSVars()),actionCollection(),"printupsvars");
+ new KAction(i18n("&Running instant commands"),0,this,SLOT(slotInstComms()),actionCollection(),"instcomms");
+ new KAction(i18n("Setting R&W variables"),0,this,SLOT(slotRWVars()),actionCollection(),"rwvars");
+
+///////////////////
+// KStdAction::showToolbar (this, SLOT (slotShowToolBar()), actionCollection());
+// setStandardToolBarMenuEnabled(true); since KDE version 3.1
+
+// since version 3.1
+ #if defined (KDE_VERSION_MAJOR)
+ #if KDE_VERSION_MAJOR >= 3
+ #if defined (KDE_VERSION_MINOR)
+ #if KDE_VERSION_MINOR >= 1
+ setStandardToolBarMenuEnabled(true);
+ #else
+ KStdAction::showToolbar (this, SLOT (slotShowToolBar()), actionCollection());
+ #endif
+ #else
+ KStdAction::showToolbar (this, SLOT (slotShowToolBar()), actionCollection());
+ #endif
+ #else
+ KStdAction::showToolbar (this, SLOT (slotShowToolBar()), actionCollection());
+ #endif
+ #else
+ KStdAction::showToolbar (this, SLOT (slotShowToolBar()), actionCollection());
+ #endif
+
+
+ KStdAction::showStatusbar (this, SLOT (slotShowStatusBar()), actionCollection());
+
+ m_descriptionAction = new KToggleAction(i18n("&Using descriptions"),0,this,SLOT(slotDescription()),actionCollection(),"use_description");
+
+ KStdAction::keyBindings( this, SLOT(slotConfigureKeys()),actionCollection());
+ new KAction (i18n("Reconnect"),"reload",Key_F5,this,SLOT(slotRefreshConnection()),actionCollection(),"reconnect");
+ }
+
+void KNutMainWindow::initVars ( void ) {
+
+ //m_activeUpsIndex = -1;
+
+ //nastavime fonty
+ // sets fonts
+ m_mainPalette= kapp->palette();
+ m_areaPalette=m_mainPalette;
+ m_mPanelPalette=m_mainPalette;
+ m_aPanelPalette=m_mainPalette;
+ }
+
+
+int KNutMainWindow::activeMainCombo (void) {
+ int activeUpsNameIndex = -1; // zadne upsName neni aktivni , any upsName is not active
+ KComboBox *combo = toolBar(0)->getCombo(1);
+
+ //naplnime comboBox
+ //loads comboBox
+ combo->clear();
+ for (int i=0; i < m_upsRecords->getCount (); i++) {
+ combo->insertItem (m_upsRecords->getName(i));
+ // ulozime si poradove cislo jmena aktivniho ups
+ // save serial number of active usp name
+ if ((m_upsRecords->getName(i)) == m_activeUpsInfo->record.name) activeUpsNameIndex = i;
+ }
+ return activeUpsNameIndex;
+ }
+
+#include "knutmainwindow.moc"
diff --git a/src/knutmainwindow.h b/src/knutmainwindow.h
new file mode 100644
index 0000000..01b9815
--- /dev/null
+++ b/src/knutmainwindow.h
@@ -0,0 +1,346 @@
+/***************************************************************************
+ knutmainwindow.h - description
+ -------------------
+ begin : Po cen 16 2003
+ copyright : (C) 2003 by Daniel Prynych
+ email : Daniel@prynych.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTMAINWINDOW_H
+#define KNUTMAINWINDOW_H
+
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+
+#include "knutprefdlg.h"
+#include "knutupsdata.h"
+#include "knutvardata.h"
+#include "knutfrontpanel.h"
+#include "knutnet.h"
+#include "knutanalog.h"
+#include "knutpanelmeter.h"
+
+#include <kapp.h>
+#include <kmainwindow.h>
+#include <kaction.h>
+//#include <kprogress.h>
+
+
+#include <qwidget.h>
+#include <qdatetime.h>
+//#include <qprogressbar.h>
+
+
+class QString;
+class QStringList;
+class QLabel;
+class QPalette;
+class QSplitter;
+class KProgress;
+//class QProgressBar;
+
+
+/**
+ * Trida slouzi pro zobrazeni okna s informacemi o UPS.
+ * Class is used for view window with informations about UPS
+ *
+ * @author Daniel Prynych
+ * @short Hlavni okno
+ * @version 0.2.3
+ */
+class KNutMainWindow : public KMainWindow {
+ Q_OBJECT
+ public:
+
+/**
+ * Constructor - makes main window.
+ * Konstruktor - vytvori hlavni okno.
+ *
+ * @param tListKNutEvent pointer on QStringList contain text information about events (drop connection, switch ..)
+ * @param tActiveUpsInfo pointer on data about active UPS
+ * @param tSettingData pointer on basic data of program (background color, intercircle, pointers...,fonts..)
+ * @param tAnalogRecords pointer in class which works with data about UPS
+ * @param tListKNutEvent ukazatel na QStringList obsahuje textove udaje o udalostech (ztrata spojeni, prepnuti atd.)
+ * @param tActiveUpsInfo ukazatel na data o aktivni UPS
+ * @param tSettingData ukazatel na zakladni data programu (barvy pozadi, mezikruzi, rucicky ... ,fonty atd )
+ * @param tAnalogRecords ukazatel na tridu ktera pracuje s daty o upsekach
+ *
+ * @since 0.3.1
+ **/
+ KNutMainWindow(QStringList* tListKNutEvent, KNutVarData::upsInfoDef* tActiveUpsInfo, KNutVarData::SettingDataDef* tSettingData, KNutUpsData* tUpsRecords, KNutVarData* tAnalogRecords, QWidget* parent=0,const char *name=0);
+
+/**
+ * Destructor
+ *
+ * @since 0.1.1
+ **/
+ ~KNutMainWindow();
+
+/**
+ * Repaints information of main panel.
+ * Prekresli informace hlavniho panelu.
+ *
+ * @since 0.1.2
+ **/
+ void repaintPanel(void);
+
+
+/**
+ * Repaints analog panels based on their status.
+ * Prekresli analogove panely na zaklade jejich stavu.
+ * @param run = TRUE makes immediately repaint of panel
+ *
+ * @since 0.3.1
+ **/
+ void repaintAnalogs ( bool run = true);
+
+/**
+ * Da prikaz k prekresleni analogovych panelu, hlavniho panelu a nastavi jejich hodnoty na
+ * zaklade XFer hodnot.
+ * Give command to repaint analog panels, main panel and sets their values based on XFer values
+ * @param run = TRUE makes immediately repaint of analog panels
+ *
+ * @since 0.3.1
+ **/
+ void showUpsData (void);
+
+
+/**
+ * Adds other line into list of events and shows them on bottom part of panel.
+ * Prida dalsi radku do seznamu udalosti a zobrazi je v dolni casti panelu.
+ *
+ * @param text text of event.
+ * @param name name of UPS, name which is list of UPSes.
+ * @param text udava text udalosti.
+ * @param name udava jmeno UPS-ky tak jak je vedena v seznamu UPS-ek tohoto programu
+ *
+ * @since 0.1
+ **/
+ void addComboStatusItem (const QString text, const QString name = QString::null);
+
+/**
+ * Rebuilds main panel based on value changeSetting.
+ * This value generates config windies
+ * Prestavi hlavni panel na zaklade hodnoty changeSetting.
+ * Tuto hodnotu generuje konfiguracni okno.
+ *
+ * @param changeSetting tell which setting was changed.
+ * @param changeSetting udava jake nastaveni bylo zmeneno.
+ *
+ * @since 0.1.2
+ **/
+ void setConfig (unsigned int changeSetting);
+
+/**
+ * Sets ComboBox (for name of UPS)
+ * Nastavi ComboBox (pro jmeno UPSky).
+ *
+ * &param name je jmeno UPSky ktere bude nastavena.
+ * &param name is name of ups which will be set.
+ *
+ * @since 0.1
+ **/
+ void setCombo(QString name);
+
+/**
+ * Nastavi vsechny panely na nulovo hodnotu
+ * Sets all pannels to zero value
+ *
+ * @since 0.2
+ **/
+ void zeroingPanels (void);
+
+/**
+ * Cleans front panel and panel meter (includes analog panels) .
+ *
+ * @since 0.1
+ **/
+ void cleanPanels (void);
+
+/**
+ * Sets and shows connect progress bar.
+ * Nastavi a zobrazi connect progress bar.
+ *
+ * &param is count of parts of progress bar.
+ * &param je pocet casti progres baru.
+ *
+ * @since 0.1
+ **/
+ void startConnectPB ( const int count );
+
+/**
+ * Hide connect progress bar.
+ * Schova connect progress bar.
+ *
+ * @since 0.1
+ **/
+ void hideConnectPB ( void );
+
+
+/**
+ * Sets amount of progress for connect progress bar.
+ * Nastavi delku vyplne pro connect progresbar.
+ *
+ * &param is amount of progress.
+ * &param je delka vyplne.
+ *
+ * @since 0.1
+ **/
+ void setProgressConnectPB ( const int progress );
+
+
+ signals:
+/**
+ * This signal is emited when other UPS was selected.
+ * Tento signal je vyslan pokud byla vybrana jina UPS-ka.
+ *
+ * @since 0.1
+ **/
+ void UPSChanged (QString);
+
+/**
+ * This signal is emited when request for viewing preferences window was ordered from menu.
+ * Tento signal je vyslan pokud byl z menu zadan pozadavek na zobrazeni okna
+ * pro nastaveni programu (preference).
+ *
+ * @since 0.1
+ **/
+ void preferenceUps (void);
+
+/**
+ * This signal is emited, when in menu was odered requirement for viewing list of values .
+ * Tento signal je vyslan, pokud byl z menu zadan pozadavek na zobrazeni seznamu promennych.
+ *
+ * @since 0.1
+ **/
+ void showUPSVars (void);
+
+/**
+ * Tento signal je vyslan pokud byl z menu zadan pozadavek na zmenu RW promennych.
+ * This signal is emited when request for change RW varianles was orederd from menu.
+ *
+ * @since 0.1
+ **/
+ void makeRWVars(void);
+
+
+/**
+ * Tento signal je vyslan pokud byl z menu vybran pozadavek na obnovu spojeni.
+ * This signal is emited when request for refreshing connection was selected from menu.
+ *
+ * @since 0.1
+ **/
+ void makeRefreshConnection(void);
+
+/**
+ * This signal is emited when request for making instant commands was selected from menu.
+ * Tento signal je vyslan pokud byl z menu zadan pozadavek na provedeni okamzitych prikazu.
+ *
+ * @since 0.1
+ **/
+ void makeInstComms(void);
+
+/**
+ * This signal is emited whem we need save configuration of program.
+ * Tento signal je vyslan pokud potrebujeme ulozit konfiguraci programuss.
+ *
+ * @since 0.1
+ **/
+ void saveConf(void);
+
+
+
+/**
+ * This signal is emited whem request for ending all application was selected from menu.
+ * Tento signal je vyslan pokud byl z menu zadan pozadavek na ukonceni cele aplikace.
+ *
+ * @since 0.1
+ **/
+ void endApplication();
+
+ protected:
+ void closeEvent( QCloseEvent *e );
+
+
+
+ private slots:
+ void slotDescription(void);
+ void slotShowToolBar(void);
+ void slotShowStatusBar(void);
+ void slotPreferencesUps(void);
+ void slotPrintUPSVars(void);
+ void slotInstComms(void);
+ void slotRWVars(void);
+ void slotChangeRWVars ( QString );
+ void slotCloseKnutClient (void);
+ void slotChangeUPS (const QString &name);
+ void slotConfigureKeys(void);
+ void slotRefreshConnection(void);
+
+/************** private common functions ************************/
+ private:
+
+ void activeConfiguration (void);
+ int activeMainCombo (void);
+ void hideUpsData (void);
+
+
+/************ init functions ********************/
+ void initVars ( void );
+ void initAction ( void );
+ void initStatusBar ( void );
+ void initToolBar ( void );
+ void initStatusBarMessage ( void );
+
+
+/************** private vars **************************/
+// Nazvy promenych UPS cislovany jsou od 0 do 10 "NONE", "UTILITY", "BATTPCT", "UPSTEMP", "ACFREQ", "LOADPCT", "AMBTEMP", "AMBHUMID", "BATTVOLT", "OUTVOLT", "CURRENT"
+
+ QStringList* m_listKNutEvent;
+ KNutVarData::upsInfoDef* m_activeUpsInfo; // values for selected ups / hodnoty pro vybrane ups
+ KNutVarData::SettingDataDef* m_settingData; // v teto strukture jsou ulozeny promene ktere nastavuji konfiguraci
+ KNutUpsData* m_upsRecords;
+ KNutVarData* m_analogRecords;
+
+
+ KAction *m_quit;
+ KAction *m_preferencesUps;
+ KToggleAction *m_descriptionAction;
+
+
+ QLabel* m_area; // main arrea, on its will server main panel and analog panels
+ // hlavni plocha na ni umistime panel a analogove ukazatele
+
+ QSplitter* m_mainSplit;
+ KNutFrontPanel* m_frontPanel;
+
+ // nactene hodnoty promenych UPS, tyto promene se ctou jen jednou
+ // readly values of UPS's variables, these varieables is read only once
+ QString m_manufacturer, m_upsModel, m_serial, m_firmrev;
+ bool m_existLowHighXfer;
+ float m_lowXfer, m_highXfer;
+ QPalette m_mainPalette, m_areaPalette, m_mPanelPalette, m_aPanelPalette;
+
+ // Combo a pomocne struktury pro dolni radku
+ // Combo and help structures for bottom line.
+ KComboBox *m_infoCombo;
+
+ KNutPanelMeter* m_panelMeter;
+
+ KProgress* m_connectProggresBar;
+ QString m_progressFormatString;
+
+ };
+#endif
+
diff --git a/src/knutmessage.cpp b/src/knutmessage.cpp
new file mode 100644
index 0000000..f13b9e7
--- /dev/null
+++ b/src/knutmessage.cpp
@@ -0,0 +1,95 @@
+/***************************************************************************
+ knutmessage.cpp - description
+ -------------------
+ begin : So led 24 2004
+ copyright : (C) 2004 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#include "knutmessage.h"
+#include <kglobal.h>
+#include <kiconloader.h>
+
+#include <qlayout.h>
+#include <qlabel.h>
+#include <qframe.h>
+#include <qpixmap.h>
+#include <qtimer.h>
+
+
+KNutMessage::KNutMessage(const QString messageText, const typeOfMessage type, const long int timeValidity, QWidget *parent, const char *name) : KDialogBase(Plain, "Messages",Ok,Ok, parent, name, false, false) {
+
+
+ setCaption("KNutClient");
+ m_messageTimer = 0;
+ KIconLoader *loader = KGlobal::iconLoader();
+
+ switch(type) {
+ case infoMess:
+ m_ret = loader->loadIcon("messagebox_info", KIcon::NoGroup, KIcon::SizeMedium, KIcon::DefaultState, 0, true);
+ break;
+ case warningMess:
+ m_ret = loader->loadIcon("messagebox_warning", KIcon::NoGroup, KIcon::SizeMedium, KIcon::DefaultState, 0, true);
+ break;
+ case criticalMess:
+ m_ret = loader->loadIcon("messagebox_critical", KIcon::NoGroup, KIcon::SizeMedium, KIcon::DefaultState, 0, true);
+ break;
+ }
+
+ QFrame *page = plainPage();
+
+ QVBoxLayout *setTopLayout = new QVBoxLayout( page, 10, spacingHint(), "setTopLayout" );
+ QHBoxLayout *setMessageLayout = new QHBoxLayout( setTopLayout, spacingHint(), "setMessageLayout" );
+
+ QLabel* picture = new QLabel (page);
+ QLabel* text = new QLabel (messageText,page);
+ picture->setPixmap(m_ret);
+
+ setMessageLayout->addWidget(picture);
+ setMessageLayout->addWidget(text);
+
+ if (timeValidity > 0 ) {
+ m_messageTimer = new QTimer(this);
+ if (timeValidity > maxTime)
+ m_messageTimer->start(maxTime*1000);
+ else
+ m_messageTimer->start(timeValidity*1000);
+ connect (m_messageTimer,SIGNAL(timeout()),this,SLOT(timeout()));
+ disableResize();
+ }
+ }
+
+KNutMessage::~KNutMessage(){
+ }
+
+void KNutMessage::timeout(void) {
+
+ if (m_messageTimer) m_messageTimer->stop();
+
+ emit endMessage();
+ }
+
+
+void KNutMessage::slotOk (void) {
+
+ if (m_messageTimer) m_messageTimer->stop();
+ emit endMessage();
+ }
+
+void KNutMessage::moveEvent ( QMoveEvent * e) {
+
+ KDialogBase::moveEvent (e);
+ emit messageMoved(x(),y());
+}
+
+
+#include "knutmessage.moc"
diff --git a/src/knutmessage.h b/src/knutmessage.h
new file mode 100644
index 0000000..6be9f5d
--- /dev/null
+++ b/src/knutmessage.h
@@ -0,0 +1,126 @@
+/***************************************************************************
+ knutmessage.h - description
+ -------------------
+ begin : So led 24 2004
+ copyright : (C) 2004 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTMESSAGE_H
+#define KNUTMESSAGE_H
+
+#include <kdialogbase.h>
+
+//#include <qpixmap.h>
+//#include <qtimer.h>
+
+
+/**
+ *@author Daniel Prynych
+ */
+
+
+class QTimer;
+class QPixmap;
+
+/**
+ * Tato trida zobrazi okno zpravy v modeless rezimu.
+ * Okno pracuje nezavisle na ostatnich oknech a NEPOZASTAVUJE jejich cinnost.
+ *
+ * @author Daniel Prynych
+ * @short window message
+ * @version 0.1
+ */
+class KNutMessage : public KDialogBase {
+ Q_OBJECT
+public:
+
+enum typeOfMessage {
+ infoMess,
+ warningMess,
+ criticalMess
+ };
+
+
+/**
+ * Constructor - makes window of message.
+ * Konstruktor - vytvori okno zpravy.
+ * @param messageText is text of message
+ * @param type is type of message see on enum typeOfMessage
+ * @param timeValidity maximal time for showing window, if it is equal zere, time is unlimited.
+ *
+ * @param messageText je text zpravu.
+ * @param type je typ zpravy blize enum typeOfMessage
+ * @param timeValidity maximalni doba zobrazeni okna, je-li rovna nule je neomezena.
+ * @since 0.2
+ */
+ KNutMessage(const QString messageText, const typeOfMessage type=infoMess, const long int timeValidity=0, QWidget *parent=0, const char *name=0);
+
+/**
+ * Destruktor.
+ *
+ * @since 0.1.2
+ **/
+ ~KNutMessage();
+
+signals:
+/**
+ * Je emitovan kdyz dojde ke stisku tlacitka OK, nebo vyprsi doba platnosti (timeValidity).
+ * Is emited, when button OK is pressed or time of validity is stopped.
+ *
+ * @since 0.1
+ **/
+ void endMessage(void);
+
+/**
+ * Is emited when window of message is moved;
+ * Je emitovan kdyz dojde presunu okna.
+ *
+ * @since 0.1
+ **/
+
+ void messageMoved (int, int);
+
+private slots:
+
+/**
+ * @internal
+ * Je aktivivan, kdyz vyprsi doba platnosti (timeValidity).
+ *
+ * @since 0.1
+ **/
+ void timeout(void);
+
+/**
+ * @internal
+ * Is activated when button OK was pressed
+ * Je aktivovan kdyz se stiskne tlacitko OK
+ *
+ * @since 0.1
+ **/
+ virtual void slotOk (void);
+
+
+private:
+ // max rime for message window is 3600 sec or 60 min
+ static const int maxTime = 3600;
+
+ QPixmap m_ret;
+ QTimer* m_messageTimer;
+
+protected:
+ void moveEvent ( QMoveEvent * e);
+
+
+};
+
+#endif
diff --git a/src/knutmessagemanager.cpp b/src/knutmessagemanager.cpp
new file mode 100644
index 0000000..4a5aa8a
--- /dev/null
+++ b/src/knutmessagemanager.cpp
@@ -0,0 +1,121 @@
+/***************************************************************************
+ knutmessagemanager.cpp - description
+ -------------------
+ begin : So led 24 2004
+ copyright : (C) 2004 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#include "knutmessagemanager.h"
+#include <qstring.h>
+
+KNutMessageManager::KNutMessageManager( QObject *parent, const char *name) : QObject (parent, name) {
+//qDebug("KNutMessageManager::KNutMessageManager");
+
+
+ m_myMess =0;
+ m_myMessLevel = knc::infoLevel;
+ m_xPos=0;
+ m_yPos=0;
+ }
+
+
+
+KNutMessageManager::~KNutMessageManager(){
+
+ deleteMessage ();
+ }
+
+
+void KNutMessageManager::deleteMessage (void) {
+
+ if (m_myMess) {
+ disconnect (m_myMess,SIGNAL(finished()),this,SLOT(slotFinishedMessage()));
+ disconnect (m_myMess,SIGNAL(endMessage()),this,SLOT(slotEndMessage()));
+ disconnect (m_myMess,SIGNAL(messageMoved(int,int)),this,SLOT(slotMessageMoved(int,int)));
+ m_myMess->hide();
+ delete m_myMess;
+ m_myMess = 0;
+ }
+ }
+
+void KNutMessageManager::addMessage (QString text, knc::LevelOfMessage messageLevel, bool useInfoIcon, bool useShortTimeOfValidity) {
+long int timeOfMessageValidity;
+
+ if (useShortTimeOfValidity) timeOfMessageValidity = ShortTimeOfValidity;
+ else timeOfMessageValidity = TimeOfValidity;
+//qDebug("KNutMessageManager::addMessage");
+
+ deleteMessage();
+ if (useInfoIcon) m_myMess = new KNutMessage(text,KNutMessage::infoMess,timeOfMessageValidity);
+ else {
+ switch (messageLevel) {
+ case knc::infoLevel:
+ m_myMess = new KNutMessage(text,KNutMessage::infoMess,timeOfMessageValidity);
+ break;
+ case knc::lowWarningLevel:
+ m_myMess = new KNutMessage(text,KNutMessage::warningMess,timeOfMessageValidity);
+ break;
+ case knc::warningLevel:
+ m_myMess = new KNutMessage(text,KNutMessage::warningMess,timeOfMessageValidity);
+ break;
+ case knc::errorLevel:
+ m_myMess = new KNutMessage(text,KNutMessage::criticalMess,timeOfMessageValidity);
+ break;
+ case knc::criticalLevel:
+ m_myMess = new KNutMessage(text,KNutMessage::criticalMess,TimeOfValidity); //validity time of critical message has to be standard time of Validity, this time doesn't be short time
+ break;
+ }
+ }
+ m_myMessLevel=messageLevel;
+ if ((m_xPos != 0) && (m_yPos !=0)) {
+ m_myMess->move (m_xPos, m_yPos);
+ }
+
+ m_myMess->show();
+ connect (m_myMess,SIGNAL(finished()),this,SLOT(slotFinishedMessage()));
+ connect (m_myMess,SIGNAL(endMessage()),this,SLOT(slotEndMessage()));
+ connect (m_myMess,SIGNAL(messageMoved(int,int)),this,SLOT(slotMessageMoved(int,int)));
+ }
+
+
+void KNutMessageManager::slotFinishedMessage (void) {
+
+ if (m_myMess) {
+ disconnect (m_myMess,SIGNAL(finished()),this,SLOT(slotFinishedMessage()));
+ disconnect (m_myMess,SIGNAL(endMessage()),this,SLOT(slotEndMessage()));
+ disconnect (m_myMess,SIGNAL(messageMoved(int,int)),this,SLOT(slotMessageMoved(int,int)));
+ m_myMess->hide();
+ m_myMess->deleteLater();
+ m_myMess=0;
+ }
+ }
+
+void KNutMessageManager::slotEndMessage (void) {
+ //kdyz dojde ke stisku tlacitka OK, nebo vyprsi doba platnosti (timeValidity)
+
+ deleteMessage();
+ }
+
+
+void KNutMessageManager::slotMessageMoved (int x,int y) {
+
+//qDebug("KNutMessageManager::slotMessageMoved");
+ m_xPos=x;
+ m_yPos=y;
+}
+
+
+
+
+
+#include "knutmessagemanager.moc"
diff --git a/src/knutmessagemanager.h b/src/knutmessagemanager.h
new file mode 100644
index 0000000..3267c6e
--- /dev/null
+++ b/src/knutmessagemanager.h
@@ -0,0 +1,131 @@
+/***************************************************************************
+ knutmessagemanager.h - description
+ -------------------
+ begin : So led 24 2004
+ copyright : (C) 2004 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTMESSAGEMANAGER_H
+#define KNUTMESSAGEMANAGER_H
+
+#include "knutmessage.h"
+
+#include <qobject.h>
+
+/**
+ *@author Daniel Prynych
+ */
+
+namespace knc {
+
+enum LevelOfMessage {
+ infoLevel, // status RB, TRIM, CAL, TRIM
+ lowWarningLevel, // OVER,
+ warningLevel, // OB ..
+ errorLevel, // connection error
+ criticalLevel // Status BL, OFF
+ };
+
+ }
+
+class QString;
+
+/**
+ * Tato trida slouzi pro ovladani vyskakovacich oken (pop-up)
+ * Okno pracuji nezavisle na ostatnich oknech a NEPOZASTAVUJI jejich cinnost.
+ *
+ * @author Daniel Prynych
+ * @short window message manager
+ * @version 0.1
+ */
+class KNutMessageManager : public QObject {
+ Q_OBJECT
+ public:
+/**
+ * Konstruktor - vytvori instanci tridy.
+ *
+ * @since 0.1
+ */
+ KNutMessageManager( QObject *parent=0, const char *name=0);
+
+/**
+ * Destruktor.
+ *
+ * @since 0.1.1
+ **/
+ ~KNutMessageManager();
+
+/**
+ * Pozada o zobrazeni okna. Pokud je zobrazeno okne s vyssi prioritou, neni funkce provedena.
+ *
+ * @param text Text of message, which will be showed in window
+ *
+ * @param text Text zpravy ktera se zobrazi v okne.
+ * @param messageLevel urcuje prioritu zpravy.
+ * @param useInfoIcon urcuje ktera icona se zobrazi. Pokud je nastaven na true, je vzdy zobrazena icona
+ * info, pokud je false je nastavena icona v zavislosti na priorite zpravy.
+ *
+ * @since 0.2
+ **/
+ void addMessage (QString text, knc::LevelOfMessage messageLevel = knc::infoLevel, bool useInfoIcon = false, bool useShortTimeOfValidity = false);
+
+
+/**
+ * Close window, when one is existed
+ * Zrusi okno, pokud existuje;
+ *
+ * @since 0.1.1
+ **/
+ void deleteMessage (void);
+
+
+ private slots:
+
+/**
+ * @internal
+ * Je aktivovan, kdyz bylo pozadano o zruseni okna stisknutim praveho widgetu nebo vnejsimi udalostmi (KDE Logout).
+ *
+ * @since 0.1.2
+ **/
+ void slotFinishedMessage (void);
+
+/**
+ * @internal
+ * Je aktivovan, kdyz bylo pozadano o zruseni okna stsknutim OK nebo vyprsenim casoveho terminu
+ *
+ * @since 0.1.2
+ **/
+ void slotEndMessage (void);
+
+
+/**
+ * @internal
+ / Is activated when window was moved
+ * Je aktivovan, kdyz bylo okno presunuto
+ *
+ * @since 0.1.2
+ **/
+ void slotMessageMoved (int x,int y);
+
+
+ private:
+ static const long int TimeOfValidity = 600; //600 sec or 10n min
+ static const long int ShortTimeOfValidity = 60; // 60 sec or one min
+ KNutMessage* m_myMess;
+ knc::LevelOfMessage m_myMessLevel;
+ int m_xPos;
+ int m_yPos;
+
+ };
+
+#endif
diff --git a/src/knutnet.cpp b/src/knutnet.cpp
new file mode 100755
index 0000000..71bc315
--- /dev/null
+++ b/src/knutnet.cpp
@@ -0,0 +1,1941 @@
+/***************************************************************************
+ knutnet.cpp - description
+ -------------------
+ begin : Ne led 12 2003
+ copyright : (C) 2003 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#include "knutnet.h"
+
+#include <qtextstream.h>
+#include <qstring.h>
+#include <qcstring.h>
+#include <qtimer.h>
+
+
+#include <unistd.h> // for function sleep
+
+//#include <iostream>
+
+
+
+/****** CONSTS ***********/
+
+//const Q_ULONG rBufferLen = 1024;
+
+
+
+KNutNet::KNutNet (const QString upsAddress, const QString upsName, const unsigned short port, unsigned int countRepeat, const unsigned int delay)
+ : QObject(), m_upsAddress(upsAddress), m_upsName(upsName), m_countRepeat(countRepeat), m_port(port), m_delay(delay) {
+
+
+//qDebug ("KNutNet::KNutNet");
+
+ m_state = Idle; //idle is value
+ m_numberVars = 0;
+ m_numberRWVars = 0;
+ m_numberIComms = 0;
+ m_upsStatusVar = 0;
+ m_nutProtocol = 0;
+ m_nutVariables = 0;
+ m_switchToTCP = false;
+
+ m_description = false; // popis neni natazen - description is not loaded
+
+ m_unConnectTimer = new QTimer( this );
+ connect( m_unConnectTimer, SIGNAL(timeout()), this, SLOT(slotTimerReconnect()) );
+
+ m_error = NoError;
+
+ m_commandSocket = new QSocket( this );
+ connect( m_commandSocket, SIGNAL( hostFound()),this, SLOT( slotHostFound()));
+ connect( m_commandSocket, SIGNAL( connected()),this,SLOT( slotConnected()));
+ connect( m_commandSocket, SIGNAL( connectionClosed()),this, SLOT( slotConnectionClosed()));
+ connect( m_commandSocket, SIGNAL( error(int)),this, SLOT( slotConnectionError(int)));
+ }
+
+
+KNutNet::~KNutNet(){
+ QCString inBuffer;
+ QString outBuffer;
+
+ close(); // close connetion when is existed
+ while (m_state == Closing ) {
+ sleep (100);
+ }
+// deleteVars() is made in close();
+ }
+
+
+void KNutNet::close (void) {
+// std::cout << "--KNutNet::close" << std::endl;
+ QCString inBuffer;
+ QString outBuffer;
+
+ m_unConnectTimer->stop();
+ deleteVars();
+ if ((m_state == Connected) || (m_state == Connecting)) {
+ m_state = Closing;
+ if (m_state == Connected) {
+ inBuffer="LOGOUT\n";
+ getUpsData (inBuffer,outBuffer);
+ // getUpsDate makes "commandSocket->flush()"
+ }
+
+ if (m_commandSocket->bytesToWrite () > 0) sleep (1000);
+ m_commandSocket->clearPendingData (); // data in output buffer will be errased
+ m_commandSocket->close(); // closes the socket
+
+ if ( m_commandSocket->state() == QSocket::Closing ) {
+ connect( m_commandSocket, SIGNAL(delayedCloseFinished()),this,SLOT(slotClosed()) );
+ }
+ else {
+ slotClosed();
+ }
+ }
+ }
+
+void KNutNet::slotClosed (void) {
+
+ disconnect( m_commandSocket,SIGNAL(delayedCloseFinished()),this, SLOT(slotClosed()) );
+ m_state = Idle;
+ }
+
+
+void KNutNet::open (void) {
+
+ QCString inBuffer;
+ QString outBuffer;
+
+ if ((m_state == Connected) || (m_state == Connecting)) close(); // close connetion when is existed
+ else {
+ while (m_state == Closing ) {
+ sleep (100);
+ }
+ }
+ if (m_upsAddress != "") {
+ if ( m_commandSocket->state() != QSocket::Connecting ) {
+ m_firstConnect=true;
+ m_numberConnection=0;
+ m_state = HostLookup;
+ emit tryFirstConnection(m_countRepeat); // how many times we can try to connect with ups server /upsd/
+// std::cout << "--KNutNet :: Open emit - tryFirstConnection" << std::endl;
+ m_commandSocket->connectToHost(m_upsAddress,m_port);
+ }
+ }
+ }
+
+
+void KNutNet::newUPS (const QString upsAddress, const QString upsName, const unsigned short port) {
+
+ if ((m_state == Connected) || (m_state == Connecting)) {
+ close();
+ while (m_state == Closing ) {
+ sleep (100);
+ }
+ }
+
+ m_upsAddress = upsAddress;
+ m_upsName = upsName;
+ m_port = port;
+
+ m_state = Idle;
+ m_numberVars = 0;
+ m_numberRWVars = 0;
+ m_numberIComms = 0;
+ m_upsStatusVar = 0;
+ m_nutProtocol = 0;
+ m_nutVariables = 0;
+ m_switchToTCP = false;
+
+ m_error = NoError;
+ //firstConnect=true;
+ //numberConnection=0;
+ }
+
+
+
+int KNutNet::getError ( void ) { return m_error; }
+
+int KNutNet::getState ( void ){ return m_state; }
+
+bool KNutNet::isDescription ( void ){ return m_description; }
+
+int KNutNet::getNutProtocol ( void ) { return m_nutProtocol; }
+
+int KNutNet::getNutVariables ( void ) { return m_nutVariables; }
+
+bool KNutNet::switchedToTCP ( void ) { return m_switchToTCP; }
+
+
+int KNutNet::getUpsVars ( void) {
+ int returnValue;
+
+ m_error=0;
+ if (m_state == Connected) {
+
+ // init vars and lists
+ m_numberVars = 0;
+ m_numberRWVars = 0;
+ m_numberIComms = 0;
+ deleteVars();
+ int countWaitRevision = 5;
+ do {
+ switch (m_nutProtocol) {
+ case 1:
+ returnValue = getUpsVars1();
+ break;
+ case 2:
+ returnValue = getUpsVars2();
+ break;
+ default:
+ return 0;
+ }
+ if ( readStatus() != KNutNet::WAIT) return returnValue;
+ countWaitRevision--;
+ if (countWaitRevision) sleep (2);
+ }
+ while (countWaitRevision);
+ return NoListVars; //getUpsVars can't read list variables
+ }
+ else {
+ return NotConnection;
+ }
+ }
+
+
+int KNutNet::getUpsValues (const bool allVars ) {// allVars = true vse; allVars = false jen activate
+
+ m_error=0; // vynulujeme chyby
+ if (m_state == Connected) {
+ // init vars and lists
+ switch (m_nutProtocol) {
+ case 1:
+ return getUpsValues1(allVars);
+ break;
+ case 2:
+ return getUpsValues2(allVars);
+ break;
+ default:
+ return 0;
+ }
+ }
+ else {
+ return NotConnection;
+ }
+ }
+
+
+
+int KNutNet::getDescription (bool always) {
+
+ m_error=0; // vynulujeme chyby
+ if (m_state == Connected) {
+ switch (m_nutProtocol) {
+ case 1:
+ return getDescription1 (always);
+ break;
+ case 2:
+ return getDescription2 (always);
+ break;
+ default:
+ return 0;
+ }
+ }
+ else return NotConnection;
+ }
+
+
+int KNutNet::instantCommand (const QString command, const QString userName, const QString password, const bool onlyCommand) {
+ m_error=0; // vynulujeme chyby
+
+ if (m_state == Connected) {
+ QString outBuffer;
+
+ // funkce sendComm sama mastavi promenou error
+ if (onlyCommand) {
+ if (!(m_error = sendComm("INSTCMD", command, "",true))) {
+// netMutex=false;
+ return 0;
+ }
+ else {
+// netMutex=false;
+ return m_error;
+ }
+ }
+ else {
+
+
+
+
+ if (!(m_error = sendComm ("USERNAME", userName, ""))) {
+ if (!(m_error = sendComm("PASSWORD", password, ""))) {
+ if (!(m_error = sendComm("INSTCMD", command, "",true))) {
+// netMutex=false;
+ return 0;
+ }
+ else {
+ return m_error; // spatny prikaz
+ }
+ } //username
+ else {
+ return m_error; //spatne helso
+ }
+ }
+ else {
+ return m_error; // spatne jmeno
+ }
+ }
+ }
+ else return NotConnection;
+ }
+
+
+int KNutNet::setVariable (const QString variable, const QString value, const QString userName, const QString password, const bool onlyVariable) {
+ m_error=0; // vynulujeme chyby
+ if (m_state == Connected) {
+ QString outBuffer;
+ QString setCommand;
+
+ switch (m_nutProtocol) {
+ case 1: setCommand = "SET";
+ break;
+ case 2: setCommand = "SET VAR";
+ }
+ if (onlyVariable) {
+ if (!(m_error = sendComm(setCommand, variable, value, true))) {
+ return 0;
+ }
+ else {
+ return m_error;
+ }
+ }
+ else {
+ if (!(m_error = sendComm ("USERNAME", userName, ""))) {
+ if (!(m_error = sendComm("PASSWORD", password, ""))) {
+ if (!(m_error = sendComm(setCommand, variable, value, true))) {
+ //netMutex=false;
+ return 0;
+ }
+ else {
+ return m_error;
+ }
+ } //username
+ else {
+ return m_error;
+ }
+ }
+ else {
+ return m_error;
+ }
+ }
+ }
+ else return NotConnection;
+ }
+
+
+int KNutNet::readNumberVars (typeOfVar typVar) {
+// Vraci pocet promenych
+ m_error=0;
+ if (m_state == Connected) {
+ switch (typVar) {
+ case AllVars:
+ return m_numberVars;
+ break;
+ case ROVars:
+ return m_numberVars - m_numberRWVars;
+ break;
+ case RWVars:
+ return m_numberRWVars;
+ break;
+ default:
+ return -1;
+ }
+ }
+ else return -1;
+ }
+
+int KNutNet::readNumberComms (void) {
+// Vraci pocet prikazu
+ m_error=0;
+ if (m_state == Connected) return m_numberIComms;
+ else return -1;
+ }
+
+
+int KNutNet::readIComm (const int seqNumber, upsICommDef& upsIComm) {
+ m_error =0;
+ if (m_state == Connected) {
+ if ((seqNumber < 1) || ((unsigned int)seqNumber > m_listIComms.size())) {
+ m_error=CommNotFind;
+ return m_error;
+ }
+ upsIComm = m_listIComms[seqNumber-1];
+ return 0;
+ }
+ else return NotConnection;
+ }
+
+
+int KNutNet::readVars (const QString name, struct upsVarDef& allVar) {
+ m_error =0;
+ if (m_state == Connected) {
+ QValueVector<upsVarDef>::const_iterator it;
+ for (it = m_listVars.begin(); it != m_listVars.end(); it++) {
+ if ((*it).upsVarName == name) {
+ allVar = (*it);
+ return 0;
+ }
+ }
+ m_error=VarNotFind;
+ return m_error;
+ }
+ else return NotConnection;
+ }
+
+ int KNutNet::readVars (const int seqNumber, struct upsVarDef& allVar, const typeOfVar typVar) {
+
+ m_error =0;
+ if (m_state == Connected) {
+ int n = 1;
+ QValueVector<upsVarDef>::const_iterator it;
+
+ for (it = m_listVars.begin(); it != m_listVars.end(); it++) {
+ if ((typVar== AllVars) || ((typVar==ROVars) && ((*it).upsVarType)) ||
+ ((typVar==RWVars) && (!(*it).upsVarType))) {
+ if (n == seqNumber) {
+ allVar = (*it);
+ return 0;
+ }
+ n++;
+ }
+ }
+ m_error=VarNotFind;
+ return m_error;
+ }
+ else return NotConnection;
+ }
+
+
+QString KNutNet::readStringVar (const QString name) {
+
+ m_error =0;
+ if (m_state == Connected) {
+ QValueVector<upsVarDef>::const_iterator it;
+ for (it = m_listVars.begin(); it != m_listVars.end(); it++) {
+ if ((*it).upsVarName == name) return (*it).upsValue;
+ }
+ m_error = VarNotFind;
+ return 0l;
+ }
+ else return 0l;
+}
+
+
+QString KNutNet::readEnumValueVar (const QString name, const int valueNumber) {
+
+ m_error =0;
+ if (m_state == Connected) {
+// #if defined (KDE_VERSION_MAJOR)
+// #if KDE_VERSION_MAJOR >= 3
+ QValueVector<upsVarDef>::const_iterator it;
+// #else
+// QValueList<upsVar>::ConstIterator it;
+// #endif
+// #else
+// QValueList<upsVar>::ConstIterator it;
+// #endif
+
+
+ for (it = m_listVars.begin(); it != m_listVars.end(); it++) {
+ if ((*it).upsVarName == name) {
+ if ((valueNumber < 1) || (valueNumber > (*it).upsVarMax)) {
+ m_error=EnumValueNotFind;
+ return 0l;
+ }
+ // vratime hodnotu
+ return (*(*it).upsEnumValues)[valueNumber-1];
+ }
+ }
+ m_error = VarNotFind;
+ return 0;
+ }
+ else return 0;
+ }
+
+
+int KNutNet::readStatus(void) {
+
+ m_error=0;
+ return m_upsStatusVar;
+ }
+
+
+int KNutNet::setActivate ( const QString name ) {
+ return activate (name,true);
+ }
+
+
+int KNutNet::unSetActivate ( const QString name ) {
+ return activate (name,false);
+ }
+
+
+int KNutNet::unSetActivateAll ( void ) {
+ return activateAll (false);
+ }
+
+
+int KNutNet::existName ( const QString name ) {
+
+ m_error =0;
+ if (m_state == Connected) {
+ QValueVector<upsVarDef>::const_iterator it;
+ for (it = m_listVars.begin(); it != m_listVars.end(); it++) {
+ if ((*it).upsVarName == name) return 0;
+ }
+ m_error = VarNotFind;
+ return m_error;
+ }
+ else return NotConnection;
+ }
+
+/*************************************************************************/
+/* */
+/* PRIVATE FUNCTIONS */
+/* */
+/*************************************************************************/
+
+
+int KNutNet::version (int countRepeat, const int delay) {
+ QCString inBuffer;
+ QString outBuffer;
+
+ m_error =0;
+ do {
+ inBuffer="VER\n";
+ if (!(m_error=getUpsData (inBuffer,outBuffer))) {
+ outBuffer=outBuffer.stripWhiteSpace ();
+
+ if (outBuffer.length() > 0) {
+ outBuffer = outBuffer.mid(outBuffer.find("upsd")+4);
+ int n = outBuffer.find(".");
+ if (n > 0) {
+ QString firstNumber= outBuffer.left(n);
+ QString secondNumber= outBuffer.mid(n+1);
+ int n = secondNumber.find(".");
+ if (n > 0) {
+ bool ok;
+ secondNumber = secondNumber.left(n);
+ int secondInt = secondNumber.toInt(&ok);
+ if (!ok) {m_error = UnknownFormatVer; return m_error;}
+ int firstInt = firstNumber.toInt(&ok);
+ if (!ok) {m_error = UnknownFormatVer; return m_error;}
+ if ((firstInt == 0) || ((firstInt == 1) && (secondInt < 3))) {
+ m_nutProtocol =1;
+ m_nutVariables =1;
+ }
+ else {
+ m_nutProtocol =2;
+ m_nutVariables =2;
+ }
+ return 0;
+ }
+ else m_error = UnknownFormatVer; // n is <= 0 the second dot
+ }
+ else m_error = UnknownFormatVer; // n is <= 0 the first dot
+ }
+ m_error = UnknownAnswer; // i cannot specify number of protocol and number of variables
+ return m_error;
+ }
+ countRepeat--;
+ if (countRepeat) sleep (delay);
+ }
+ while ((countRepeat));
+ return m_error;
+ }
+
+
+
+int KNutNet::getFirstUpsName (QString& firstUpsName) {
+ QCString inBuffer;
+ QString outBuffer;
+ QString varOutBuffer;
+ int lenString;
+
+ m_error=0;
+ inBuffer = "LIST UPS\n";
+ if (!(m_error=getUpsData (inBuffer,outBuffer,"END LIST UPS"))) {
+
+ QString inLine, upsNameRet, varName, value;
+ int key, typeValue;
+ bool beginList = false;
+ QTextIStream varInputStream(&outBuffer);
+ while (!(inLine = varInputStream.readLine()).isNull()) {
+ key = parseLine (inLine, upsNameRet, varName, value, typeValue, lenString);
+ switch (key) {
+ case BEGIN_LIST_UPS: {
+ beginList = true;;
+ break;
+ }
+ case UPS:
+ if (beginList ) {
+ firstUpsName = upsNameRet;
+ return 0;
+ }
+ case END_LIST_UPS:
+ firstUpsName = "";
+ m_error=NoUpsHere;
+ return m_error;
+ case ERR:
+ m_error = upsTranslateError(value);
+ return m_error;
+ default:
+ m_error=UnknownAnswer;
+ return m_error;
+ }
+ }// end while
+ }
+ else {m_error=NoData; return m_error; }
+ return 0;
+ }
+
+
+
+int KNutNet::setKey (const QString line) {
+
+ QString myLine=line.stripWhiteSpace();
+ if (myLine == "OK") return OK;
+ if (myLine == "ERR") return ERR;
+ if (myLine == "BEGIN") return BEGIN;
+ if (myLine == "END") return END;
+ if (myLine == "VAR") return VAR;
+ if (myLine == "TYPE") return TYPE;
+ if (myLine == "DESC") return DESC;
+ if (myLine == "CMDDESC") return CMDDESC;
+ if (myLine == "UPSDESC") return CMDDESC;
+ if (myLine == "UPS") return UPS;
+ if (myLine == "LIST") return LIST;
+ if (myLine == "RW") return RW;
+ if (myLine == "CMD") return CMD;
+ if (myLine == "ENUM") return ENUM;
+ if (myLine == "STARTTLS") return STARTTLS;
+ return NONE;
+ }
+
+QString KNutNet::parseValue (const QString line) {
+
+ if (line.isEmpty()) return "";
+ if (line[0] != "\"") {
+ if ((m_posChar=line.find(' ')) == -1) return line;
+ else return line.left(m_posChar+1);
+ }
+ else {
+ int len = line.length();
+ QString outString = "";
+ for (int i=1; i < len; i++) {
+ if ( line[i] == "\\") {
+ if ((i+1) <len) {
+ if ((line[i+1] == "\"") || (line[i+1] == "\"")) {
+ outString +=line[i+1];
+ i++;
+ }
+ else i +=2;
+ }
+ outString +=line[i];
+ continue;
+ }
+ if (line [i] == "\"") {
+ return outString;
+ }
+ outString += line[i];
+ }
+ return outString;
+ }
+ return "";
+ }
+
+int KNutNet::parseTypeValue (QString line, int& lenString ) {
+ int ret=0;
+ QString word;
+
+ lenString = 0;
+ if (line.isEmpty()) return 0;
+ QTextIStream inputStream(&line);
+ while (!inputStream.atEnd()) {
+ inputStream >> word;
+ if (word == "RW") ret += RW_FLAG;
+ if (word == "ENUM") ret += ENUM_FLAG;
+ if (word.find("STRING:") != -1) {
+ word = word.mid(7);
+ ret += STRING_FLAG;
+ lenString = word.toInt();
+ }
+ }
+ return ret;
+ }
+
+
+int KNutNet::parseLine(QString& line, QString& upsName ,QString& varName, QString& value, int& typeValue, int& lenString) {
+ int posChar;
+ QString word1, word2, word3;
+ int key1, key2, key3;
+
+ line = line.stripWhiteSpace();
+
+ upsName = "";
+ varName = "";
+ value = "";
+ typeValue =0;
+
+ if (line.isEmpty()) return NONE;
+
+ if ((posChar=line.find(' ')) == -1) {
+ if (setKey(line) == OK) return OK;
+ else return NONE;
+ }
+ else {
+ key1 = setKey( line.left(posChar));
+ line = line.mid(posChar+1);
+
+ switch (key1) {
+
+ case NONE:
+ return key1;
+ case OK:
+ return key1;
+ case ERR:
+ value = parseValue(line);
+ return key1;
+ default:
+ if ((posChar=line.find(' ')) == -1) return NONE;
+ word2 = line.left(posChar);
+ key2 = setKey( word2);
+ line = line.mid(posChar+1);
+
+ switch (key1) {
+ case BEGIN:
+ if ((key2 == LIST) && (setKey(line) == UPS)) return BEGIN_LIST_UPS;
+ break;
+ case END:
+ if ((key2 == LIST) && (setKey(line) == UPS)) return END_LIST_UPS;
+ break;
+ case UPS:
+ upsName = word2;
+ value = parseValue(line);
+ return key1;
+ case CMD:
+ upsName = word2;
+ varName = parseValue(line);
+ return key1;
+ }
+
+ if ((posChar=line.find(' ')) == -1) return NONE;
+
+ word3 = line.left(posChar);
+ key3 = setKey( word3);
+ line = line.mid(posChar+1);
+
+ switch (key1) {
+ case VAR:
+ upsName = word2;
+ varName = word3;
+ value = parseValue(line);
+ return VAR;
+ case TYPE:
+ upsName = word2;
+ varName = word3;
+ typeValue = parseTypeValue(line,lenString);
+ return TYPE;
+ case ENUM:
+ upsName = word2;
+ varName = word3;
+ value = parseValue(line);
+ return ENUM;
+ case DESC:
+ upsName = word2;
+ varName = word3;
+ value = parseValue(line);
+ return DESC;
+ case CMDDESC:
+ upsName = word2;
+ varName = word3;
+ value = parseValue(line);
+ return CMDDESC;
+ case BEGIN:
+ if (key2 != LIST) return NONE;
+ if (key3 == VAR) {
+ upsName=line.stripWhiteSpace();
+ return BEGIN_LIST_VAR;
+ }
+ if (key3 == RW) {
+ upsName=line.stripWhiteSpace();
+ return BEGIN_LIST_RW;
+ }
+ if (key3 == CMD) {
+ upsName=line.stripWhiteSpace();
+ return BEGIN_LIST_CMD;
+ }
+ if (key3 == ENUM) {
+ if ((posChar=line.find(' ')) == -1) return NONE;
+ upsName = line.left(posChar);
+ line=line.mid(posChar+1);
+ varName = line.stripWhiteSpace();
+ return BEGIN_LIST_ENUM;
+ }
+ return NONE;
+ case END:
+ if (key2 != LIST) return NONE;
+ if (key3 == VAR) {
+ upsName=line.stripWhiteSpace();
+ return END_LIST_VAR;
+ }
+ if (key3 == RW) {
+ upsName=line.stripWhiteSpace();
+ return END_LIST_RW;
+ }
+ if (key3 == CMD) {
+ upsName=line.stripWhiteSpace();
+ return END_LIST_CMD;
+ }
+ if (key3 == ENUM) {
+ if ((posChar=line.find(' ')) == -1) return NONE;
+ upsName = line.left(posChar);
+ line=line.mid(posChar+1);
+ varName = line.stripWhiteSpace();
+ return END_LIST_ENUM;
+ }
+ return NONE;
+ default:
+ return NONE;
+ }
+ }
+ }
+ }
+
+
+int KNutNet::newDescription (const QCString inBuffer, QString& upsDescription) {
+ QString outBuffer;
+
+ if (!(m_error=getUpsData (inBuffer,outBuffer))) {
+ outBuffer=outBuffer.stripWhiteSpace ();
+ QString word1, word2, word3;
+
+ if ((m_posChar = outBuffer.find(' ')) == -1)
+ word1 = outBuffer;
+ else {
+ word1 = outBuffer.left(m_posChar);
+ word2 = outBuffer.mid(m_posChar+1);
+ }
+ if (word1 == "DESC") {
+ if ((m_posChar = word2.find('\"')) == -1) word3="";
+ else
+ {
+ word3 = word2.mid(m_posChar+1);
+ if ((m_posChar = word3.find('\"')) != -1) word3=word3.left(m_posChar);
+ }
+ if (!word3.isEmpty()) upsDescription=word3;
+ }
+ else {
+ if (word1 == "ERR" ) return upsTranslateError(word2);
+ else return UnknownAnswer;
+ }
+ }
+ else return m_error;
+ return 0;
+ }
+
+
+void KNutNet::cleanConnecting (void) {
+ Q_ULONG rMaxLen;
+ QCString recvBuffer(rBufferLen);
+ Q_LONG lengthInputData;
+
+ int n = 0;
+ while (m_commandSocket->bytesAvailable() > 0) {
+
+ if ( (m_commandSocket->bytesAvailable()+1) > rBufferLen) rMaxLen = rBufferLen;
+ else rMaxLen=m_commandSocket->bytesAvailable()+1;
+
+ recvBuffer.resize(rMaxLen);
+ if ((lengthInputData = m_commandSocket->readBlock(recvBuffer.data(),rMaxLen)) == -1) {
+ }
+ if (lengthInputData == 0) break;
+ if (n > 20) break; else n++;
+ }
+ }
+
+
+int KNutNet::getUpsData (const QCString sBuffer, QString& rBuffer, const QCString endString) {
+
+ //rbufferLen a sbufferLen are maximal value of buffers
+ QCString recvBuffer(rBufferLen);
+ Q_LONG lengthInputData;
+ Q_ULONG dataAvailable;
+
+
+ QMutexLocker getUpsDataLocker( &m_getUpsDataMutex );
+
+ cleanConnecting();
+ // first we clean input TCP buffer
+
+ //cleans buffer
+ rBuffer=""; // clean main input buffer;
+
+
+ // after write block, runs command flush for sending data to server inmediately
+ if (m_commandSocket->writeBlock(sBuffer.data(),sBuffer.length()) < 0 ) return SendErr;
+ m_commandSocket->flush();
+
+ if (m_commandSocket->waitForMore(1000) == 0) {
+ m_commandSocket->waitForMore(500); // workaround
+ }
+ bool endRecv = false;
+ do {
+ dataAvailable=m_commandSocket->bytesAvailable();
+ if (recvBuffer.size() < (dataAvailable+1) ) recvBuffer.resize(dataAvailable+1);
+ if ((lengthInputData = m_commandSocket->readBlock(recvBuffer.data(),dataAvailable)) == -1) return RecvErr;
+
+//correct for X86_64 by Alexey Sidorov
+ recvBuffer[(int)lengthInputData]='\0';
+ // recvBuffer[lengthInputData]='\0';
+
+ //Problem is that
+ //for 64bit environment is Q_LONG defined like _int64 and
+ //for other environments is Q_LONG defined like long
+
+
+
+
+ rBuffer.append(recvBuffer.data()); // adds reading data to main input buffer
+ if (endString.isEmpty()) endRecv = false;
+ else {
+ if (recvBuffer.findRev(endString) == -1) {
+//doesn't find right end of input data
+ if (m_commandSocket->bytesAvailable() == 0) m_commandSocket->waitForMore(1000);
+ if (m_commandSocket->bytesAvailable() > 0) endRecv=true; // makes other cyckle og while
+ else endRecv=false;
+ }
+//finds right end of input data
+ else endRecv = false; // we have found what we want to find
+ }
+ } while (endRecv);
+ return 0; // all is OK
+ }
+
+
+
+ void KNutNet::setRWVars (const QString varName, const bool valueType, const int varMax, QValueVector<QString>* enumValues) {
+ QValueVector<upsVarDef>::iterator it;
+
+ for (it = m_listVars.begin(); it != m_listVars.end(); it++) {
+ if ((*it).upsVarName == varName) {
+ (*it).upsVarMax = varMax;
+ (*it).upsValueType=valueType;
+ (*it).upsEnumValues=enumValues;
+ (*it).upsVarType=false;
+ break;
+ }
+ }
+ }
+
+void KNutNet::upsSetType (struct upsVarDef& upsVar, const QString name, const QString value) {
+
+ if (((m_nutVariables = 2) && (name == "STATUS")) || ((m_nutVariables = 2) && (name == "ups.status")))
+ upsVar.upsVarActivate=true;
+ else upsVar.upsVarActivate=false;
+
+ upsVar.upsVarName = name;
+ upsVar.upsVarType=true;
+ upsVar.upsValueType=true;
+ upsVar.upsVarMax=0;
+ upsVar.upsValue=value;
+ upsVar.upsDescription="";
+ upsVar.upsEnumValues=0L;
+}
+
+
+void KNutNet::deleteVars (void) {
+// #if defined (KDE_VERSION_MAJOR)
+// #if KDE_VERSION_MAJOR >= 3
+ QValueVector<upsVarDef>::iterator it;
+// #else
+// QValueList<upsVar>::Iterator it;
+// #endif
+// #else
+// QValueList<upsVar>::Iterator it;
+// #endif
+ for (it = m_listVars.begin(); it != m_listVars.end(); it++) {
+ if ((*it).upsEnumValues != 0) {
+ (*it).upsEnumValues->clear();
+ delete (*it).upsEnumValues;
+ }
+ }
+ m_listVars.clear();
+ m_listIComms.clear();
+ }
+
+void KNutNet::genStatusFlags (QString value) {
+ m_upsStatusVar = 0;
+ QTextIStream inputStream(&value);
+ QString word;
+ while (!inputStream.atEnd()) {
+ inputStream >> word;
+ if (word == "OFF") m_upsStatusVar +=OFF;
+ if (word == "OL") m_upsStatusVar +=OL;
+ if (word == "OB") m_upsStatusVar +=OB;
+ if (word == "LB") m_upsStatusVar +=LB;
+ if (word == "CAL") m_upsStatusVar +=CAL;
+ if (word == "TRIM") m_upsStatusVar +=TRIM;
+ if (word == "BOOST") m_upsStatusVar +=BOOST;
+ if (word == "OVER") m_upsStatusVar +=OVER;
+ if (word == "RB") m_upsStatusVar +=RB;
+ if (word == "WAIT") m_upsStatusVar = WAIT;
+ //OFF - 1 ups je vypnuta
+ //OL - 2 ups je bezi na sit
+ //OB - 4 ups bezi na baterie
+ //LB - 8 baterie je vybyta (pokud je zaroven OB dojde k shutdownu)
+ //CAL - 16 je spustena kalibrace
+ //OVER - 128 ups je pretizena
+ //RB - 256 ups pozaduje vymenu baterie
+ //WAIT - 512 ups zada o strpeni // UPS asks for waiting
+ }
+ }
+
+
+int KNutNet::getDescription1 (bool always) {
+
+ if (always || (! m_description)) {
+ QCString inBuffer;
+ QString outBuffer;
+
+ QValueVector<upsVarDef>::iterator itv;
+ QValueVector<upsICommDef>::iterator itc;
+ for (itv = m_listVars.begin(); itv != m_listVars.end(); itv++) {
+ //nacteme promenou
+ inBuffer = "VARDESC " + (*itv).upsVarName + "\n";
+ if ((m_error = newDescription (inBuffer, (*itv).upsDescription))) {
+ //netMutex.unlock();
+// netMutex=false;
+ return m_error;
+ }
+ }
+ for (itc = m_listIComms.begin(); itc != m_listIComms.end(); itc++) {
+ //nacteme promenou
+ inBuffer = "INSTCMDDESC "+(*itc).upsCommName+"\n";
+ if ((m_error = newDescription (inBuffer, (*itc).upsDescription))) {
+ //netMutex.unlock();
+ //netMutex=false;
+ return m_error;
+ }
+ }
+ //netMutex=false;
+ m_description = true;
+ }
+ return 0;
+ }
+
+
+
+int KNutNet::getDescription2 (bool always) {
+
+ if (always || (! m_description)) {
+ QCString inBuffer;
+ QString outBuffer;
+ QString upsNameRet;
+ QString varName;
+ QString value;
+ int typeValue;
+ int lenString;
+
+ QValueVector<upsVarDef>::iterator itv;
+ QValueVector<upsICommDef>::iterator itc;
+ for (itv = m_listVars.begin(); itv != m_listVars.end(); itv++) {
+ //nacteme promenou
+ inBuffer = "GET DESC " + m_upsName + " " + (*itv).upsVarName+"\n";
+
+ if (!(m_error=getUpsData (inBuffer,outBuffer))) {
+ outBuffer=outBuffer.stripWhiteSpace ();
+ if ( !outBuffer.isEmpty() ) {
+ int key = parseLine(outBuffer, upsNameRet, varName, value, typeValue, lenString);
+ switch (key) {
+ case DESC:
+ (*itv).upsDescription = value;
+ break;
+ case ERR:
+ m_error=upsTranslateError(value);
+ return m_error;
+ default:
+ m_error=UnknownAnswer;
+ return m_error;
+ }
+ }
+ else {
+ m_error = NoData;
+ return m_error;
+ }
+ }
+ else {
+ return m_error;
+ }
+ }
+ for (itc = m_listIComms.begin(); itc != m_listIComms.end(); itc++) {
+ //nacteme promenou
+ inBuffer = "GET CMDDESC " + m_upsName + " " + (*itc).upsCommName+"\n";
+ if (!(m_error=getUpsData (inBuffer,outBuffer))) {
+ outBuffer=outBuffer.stripWhiteSpace ();
+ if ( !outBuffer.isEmpty() ) {
+ int key = parseLine(outBuffer, upsNameRet, varName, value, typeValue, lenString);
+ switch (key) {
+ case CMDDESC:
+ (*itc).upsDescription = value;
+ break;
+ case ERR:
+ m_error=upsTranslateError(value);
+ return m_error;
+ default:
+ m_error=UnknownAnswer;
+ return m_error;
+ }
+ }
+ else {
+ m_error = NoData;
+ return m_error;
+ }
+ }
+ else {
+ return m_error;
+ }
+ }
+ m_description = true;
+ }
+ return 0;
+ }
+
+
+
+int KNutNet::getUpsVars1 ( void) {
+// getUpsVars nacte promene a jejich typ
+// vraci kod chyby nebo 0 pokud je vse v poradku
+ QCString inBuffer;
+ QString outBuffer;
+ QString varOutBuffer;
+ upsVarDef upsVar;
+ upsICommDef upsIComm;
+
+ // init vars and lists
+ if (!m_upsName.isEmpty()) { // pokud upsName neni je vzdy nastaveno na null
+ inBuffer="LISTVARS ";
+ inBuffer.append(m_upsName);
+ inBuffer.append("\n");
+ }
+ else inBuffer ="LISTVARS\n";
+
+ if (!(m_error=getUpsData (inBuffer,outBuffer))) {
+ outBuffer=outBuffer.stripWhiteSpace ();
+ if (outBuffer.length() > 0) {
+ // precteme data
+ QTextIStream inputStream(&outBuffer);
+ QString word;
+ int count =1 ;
+ while (!inputStream.atEnd()) {
+ inputStream >> word;
+ switch (count) {
+ case 1:
+ // vyndame prvni polozku
+ if (word == "VARS") count++;
+ else {
+ if (word == "ERR") {
+ inputStream >> word;
+ m_error = upsTranslateError(word);
+ }
+ else m_error=UnknownAnswer;
+ return m_error;
+ }
+ break;
+ case 2:
+ count++;
+ if ((word.length() > 0) && word.startsWith("@")) break;
+ default:
+ // pridame polozku do tabulky
+ upsSetType(upsVar, word);
+ m_listVars.push_back(upsVar);
+ m_numberVars++;
+ break;
+ }
+ }
+ }
+ else { m_error=NoData; return m_error; }
+ }
+ else return m_error;
+
+ if ((m_error = getUpsValues1(true))) return m_error;
+
+ // *********** RW VARIABLES
+ if (!m_upsName.isEmpty()) { // pokud upsName neni je vzdy nastaveno na null
+ inBuffer="LISTRW ";
+ inBuffer.append(m_upsName);
+ inBuffer.append("\n");
+ }
+ else inBuffer ="LISTRW\n";
+
+ if (!(m_error=getUpsData (inBuffer,outBuffer))) {
+ outBuffer=outBuffer.stripWhiteSpace();
+ if (!outBuffer.isEmpty()) {
+ // precteme data
+ QTextIStream inputStream(&outBuffer);
+ QString word;
+ int count =1 ;
+ bool valueType;
+ int varMax;
+ while (!inputStream.atEnd()) {
+ inputStream >> word;
+ switch (count) {
+ case 1:
+ // vyndame prvni polozku
+ if (word == "RW") count++;
+ else {
+ if (word == "ERR") {
+ inputStream >> word;
+ m_error = upsTranslateError(word);
+ }
+ else m_error=UnknownAnswer;
+ return m_error;
+ }
+ break;
+ case 2:
+ count++;
+ if ((word.length() > 0) && word.startsWith("@")) break;
+ default:
+ // Zpracujeme polozku v tabulce
+ // zjistime informaci o promene
+ inBuffer="VARTYPE ";
+ inBuffer.append(word);
+ if (!m_upsName.isEmpty()) {
+ inBuffer.append("@"); // pokud upsName neni je vzdy nastaveno na null
+ inBuffer.append(m_upsName);
+ }
+ inBuffer.append("\n");
+ if (!(m_error=getUpsData (inBuffer,varOutBuffer))) {
+ varOutBuffer=varOutBuffer.stripWhiteSpace();
+ if ( !outBuffer.isEmpty() ) {
+ QTextIStream varInputStream(&varOutBuffer);
+ QString word1, word2, word3;
+ varInputStream >> word1;
+ varInputStream >> word2;
+ varInputStream >> word3;
+ if (word1 == "TYPE") {
+ if ((word2.isEmpty()) || (word3.isEmpty())) {
+ m_error=UnknownFormat;
+ return m_error;
+ }
+ if (word2 == "ENUM") valueType=false;
+ else {
+ if (word2 =="STRING") valueType=true;
+ else {
+ m_error=UnknownFormat;
+ return m_error;
+ }
+ }
+ bool ok = true;
+ varMax=word3.toInt(&ok);
+ if (!ok) {m_error=UnknownFormat; return m_error;};
+ } // word1 = Type
+ else {
+ if (word1=="ERR") {
+ m_error = upsTranslateError(word2);
+ return m_error;
+ }
+ else {
+ m_error = UnknownAnswer;
+ return m_error;
+ }
+ }
+ }
+ else { m_error=NoData; return m_error; }
+ }
+ else return m_error;
+ // ********** ENUM / STRING ******************
+
+ QValueVector<QString>* enumString=0;
+ if (!valueType) {
+ // nacteme enum hodnoty
+ inBuffer="ENUM ";
+ inBuffer.append(word);
+ // pokud existuje pridame jmeno UPS-ky
+ if (!m_upsName.isEmpty()) {
+ inBuffer.append("@");
+ inBuffer.append(m_upsName);
+ }
+ inBuffer.append("\n");
+ if (!(m_error=getUpsData (inBuffer,varOutBuffer,"END\n"))) {
+// varOutBuffer.stripWhiteSpace(); nemuze provest protoze bychom si odstranili konce radek
+ if (!varOutBuffer.isEmpty()) {
+ QString inLine, word1, word2;
+ QTextIStream varInputStream(&varOutBuffer);
+ int inCountLine=1;
+ while (!(inLine = varInputStream.readLine()).isNull()) {
+ inLine=inLine.stripWhiteSpace();
+
+ if ((m_posChar=inLine.find(' ')) == -1) word1=inLine;
+ else {
+ word1=inLine.left(m_posChar);
+ inLine = inLine.mid(m_posChar+1);
+ }
+ if (word1.isEmpty()) { m_error = UnknownFormat; return m_error; }
+ if (inCountLine == 1) {
+ if ((m_posChar=inLine.find(' ')) == -1) word2=inLine;
+ else word2=inLine.left(m_posChar);
+ if (word1 =="ENUM") {
+ if (word2 != word) { m_error = UnknownFormat; return m_error; }
+ varMax=0;
+ inCountLine++;
+ enumString = new QValueVector<QString>;
+ enumString->clear();
+ }
+ else {
+ if (word1=="ERR")
+ m_error=upsTranslateError(word2); // prevede chybu na jeji kod
+ else m_error=UnknownAnswer;
+ return m_error;
+ }
+ }
+ else {
+ if (word1 == "END") break;
+ if (word1 != "OPTION") { m_error = UnknownFormat; return m_error; }
+ if ((m_posChar = inLine.find('\"')) == -1) word2 = "";
+ else {
+ word2 = inLine.mid(m_posChar+1);
+ if ((m_posChar=word2.find('\"')) != -1) word2 = word2.left(m_posChar);
+ }
+ enumString->push_back(word2);
+ varMax++;
+ }
+ } // end while
+ } // buffer is not empty
+ else { m_error = NoData ; return m_error; }
+ } // getUpsData
+ else return m_error;
+ } // type of var
+ else enumString = 0l;
+ // nacteme stringovou promenou
+ // ulozime promene
+ setRWVars (word,valueType,varMax,enumString);
+ m_numberRWVars++;
+ break;
+ }
+ } // end while (!inputStream.atEnd())
+ }
+ else { m_error = NoData ; return m_error; }
+ }
+ else return m_error;
+
+ // *************** INSTANT COMMAND
+ if (!m_upsName.isEmpty()) { // pokud upsName neni je vzdy nastaveno na null
+ inBuffer="LISTINSTCMD ";
+ inBuffer.append(m_upsName);
+ inBuffer.append("\n");
+ }
+ else inBuffer ="LISTINSTCMD\n";
+
+ if (!(m_error=getUpsData (inBuffer,outBuffer))) {
+ outBuffer=outBuffer.stripWhiteSpace ();
+ if ( !outBuffer.isEmpty() ) {
+ // precteme data
+ QTextIStream inputStream(&outBuffer);
+ QString word;
+ int count =1 ;
+ while (!inputStream.atEnd()) {
+ inputStream >> word;
+ switch (count) {
+ case 1:
+ // vyndame prvni polozku
+ if (word == "INSTCMDS") count++;
+ else {
+ if (word == "ERR") {
+ inputStream >> word;
+ m_error = upsTranslateError(word);
+ }
+ else m_error=UnknownAnswer;
+ return m_error;
+ }
+ break;
+ case 2:
+ count++;
+ if ((word.length() > 0) && word.startsWith("@")) break;
+ default:
+ // Zpracujeme polozku v tabulky
+ upsIComm.upsCommName=word;
+ upsIComm.upsDescription="";
+ m_listIComms.push_back(upsIComm);
+ m_numberIComms++;
+ break;
+ }
+ }
+ }
+ else { m_error=NoData; return m_error; }
+ }
+ else return m_error;
+ return 0;
+ }
+
+
+
+int KNutNet::getUpsVars2 ( void) {
+ QCString inBuffer;
+ QString outBuffer;
+ QString varOutBuffer;
+ upsVarDef upsVar;
+ upsICommDef upsIComm;
+ int key;
+ int typeValue;
+ int lenString;
+ int varMax=0;
+
+ QValueVector<QString>* enumString=0;
+ inBuffer = "LIST VAR " + m_upsName + "\n";
+ if (!(m_error=getUpsData (inBuffer,outBuffer,"END LIST VAR"))) {
+ QString inLine, upsNameRet, varName, varNameRet, value;
+ bool beginList = false;
+ QTextIStream varInputStream(&outBuffer);
+ while (!(inLine = varInputStream.readLine()).isNull()) {
+
+ key = parseLine (inLine, upsNameRet, varName, value, typeValue, lenString);
+ switch (key) {
+ case BEGIN_LIST_VAR:
+ if (upsNameRet == m_upsName) beginList = true;
+ break;
+ case VAR:
+ if (beginList ) {
+ upsSetType(upsVar, varName, value);
+
+ if (varName == "ups.status") genStatusFlags(value);
+ inBuffer = "GET TYPE " + m_upsName + " " + varName +"\n";
+ if (!(m_error=getUpsData (inBuffer,varOutBuffer))) {
+ key = parseLine (varOutBuffer, upsNameRet, varNameRet, value, typeValue, lenString);
+ switch (key) {
+ case TYPE:
+ if (typeValue & RW_FLAG) {
+ upsVar.upsVarMax = 0;
+ upsVar.upsEnumValues=0L;
+ if (typeValue & ENUM_FLAG) {
+ upsVar.upsValueType=false;
+ // nacteme enumValues
+ inBuffer = "LIST ENUM " + m_upsName + " " + varName +"\n";
+ if (!(m_error=getUpsData (inBuffer,varOutBuffer,"END LIST ENUM"))) {
+ bool beginEnumList = false;
+ QTextIStream varInputStream(&varOutBuffer);
+ while (!(inLine = varInputStream.readLine()).isNull()) {
+ key = parseLine (inLine, upsNameRet, varName, value, typeValue, lenString);
+ switch (key) {
+ case BEGIN_LIST_ENUM:
+ beginEnumList = true;
+ varMax=0;
+ enumString = new QValueVector<QString>;
+ enumString->clear();
+ upsVar.upsEnumValues=enumString;
+ break;
+ case ENUM:
+ if (beginList ) {
+ enumString->push_back(value);
+ varMax++;
+ }
+ break;
+ case ERR:
+ m_error = upsTranslateError(value);
+ return m_error;
+ default:
+ m_error=UnknownAnswer;
+ return m_error;
+ case END_LIST_ENUM:
+ upsVar.upsVarMax=varMax;
+ break;
+ }
+ }
+ }
+ }
+ else {
+ // Vse co nenini ENUM je STRING
+ upsVar.upsValueType=true;
+ upsVar.upsVarMax=lenString;
+ }
+ upsVar.upsVarType=false;
+ m_numberRWVars++;
+ }
+ break;
+ case ERR:
+ m_error = upsTranslateError(value);
+ return m_error;
+ default:
+ m_error=UnknownAnswer;
+ return m_error;
+ }
+ }
+ else { return m_error; }
+ m_listVars.push_back(upsVar);
+ m_numberVars++;
+ }
+ break;
+ case END_LIST_VAR:
+ break;
+ case ERR:
+ m_error = upsTranslateError(value);
+ return m_error;
+ default:
+ m_error=UnknownAnswer;
+ return m_error;
+ } // end switch
+ } // end while
+ }
+ else { return m_error; }
+ // INSTANT COMMANDS
+
+ inBuffer = "LIST CMD " + m_upsName + "\n";
+ if (!(m_error=getUpsData (inBuffer,outBuffer,"END LIST CMD"))) {
+
+ QString inLine, upsNameRet, varName, value;
+ int key, typeValue;
+ bool beginList = false;
+//std::cout << "CMD Buffer " << outBuffer << std::endl;
+
+ QTextIStream varInputStream(&outBuffer);
+ while (!(inLine = varInputStream.readLine()).isNull()) {
+ key = parseLine (inLine, upsNameRet, varName, value, typeValue, lenString);
+//std::cout << "CMD Line " << inLine << std::endl;
+
+ switch (key) {
+ case BEGIN_LIST_CMD: {
+ if (upsNameRet == m_upsName) beginList = true;
+ break;
+ }
+ case CMD:
+ if (beginList ) {
+ // Zpracujeme polozku v tabulky
+ upsIComm.upsCommName=varName;
+ upsIComm.upsDescription="";
+ m_listIComms.push_back(upsIComm);
+ m_numberIComms++;
+ }
+ break;
+ case END_LIST_CMD:
+ break;
+ case ERR:
+ m_error = upsTranslateError(value);
+ return m_error;
+ default:
+ m_error=UnknownAnswer;
+ return m_error;
+ } // end switch
+ } // end while
+ }
+ else { return m_error; }
+ return 0;
+ }
+
+
+
+int KNutNet::getUpsValues1 (const bool allVars ) {// allVars = true vse; allVars = false jen activate
+ QString endChar;
+ QCString inBuffer;
+ QString outBuffer;
+ QValueVector<upsVarDef>::iterator it;
+
+ // Nacte hodnotu promenych
+ // reads value of variables
+
+
+ emit getVarDesc (m_numberVars, 0);
+
+ int numberVar = 0;
+ for (it = m_listVars.begin(); it != m_listVars.end(); it++) {
+ numberVar++;
+ if ((allVars) || ((*it).upsVarActivate)) {
+ //nacteme promenou
+ inBuffer = "REQ ";
+ inBuffer.append((*it).upsVarName);
+ if (!m_upsName.isEmpty()) { // pokud upsName neni je vzdy nastaveno na null
+ inBuffer.append("@");
+ inBuffer.append(m_upsName);
+ }
+ inBuffer.append("\n");
+// if (!(error=getUpsData (inBuffer,outBuffer))) {
+ m_error=getUpsData (inBuffer,outBuffer);
+ // when outBuffer is empty sends and reads date again, but only the only time
+ if ((!(m_error)) && (outBuffer.isEmpty())) m_error=getUpsData (inBuffer,outBuffer);
+ if (!(m_error)) {
+
+ endChar = "";
+ if ((outBuffer.length()>0) && (outBuffer.at(outBuffer.length()-2)==' ')) endChar=' ';
+
+ outBuffer=outBuffer.stripWhiteSpace ();
+ outBuffer += endChar;
+ emit getVarDesc (m_numberVars, numberVar);
+
+ if ( !outBuffer.isEmpty() ) {
+ QTextIStream inputStream(&outBuffer);
+ QString word1, word2, word3 ;
+ inputStream >> word1;
+ inputStream >> word2;
+ if (inputStream.atEnd()) { // neexistuje treti cast VALUE
+ if (word1 == "ERR") {
+ // vracena chyba
+ m_error=upsTranslateError(word2);
+ return m_error;
+ }
+ else {
+// if ((word2 != "MODEL") && (word2 != "MFR")) {
+ if (endChar != " ") { // if values of variable is empty, string is ended on char space
+ m_error=UnknownFormat;
+ return m_error;
+ }
+ }
+ }
+ inputStream >> word3;
+ if (word1 == "ANS") {
+ // answer - odpoved
+ // odstranime pripadne jmeno upsky
+ if ((m_posChar = word2.find('@')) != -1) word2 = word2.left(m_posChar);
+ if ( word2 != (*it).upsVarName ) {
+ m_error=UnknownAnswer;
+ return m_error;// neni to odpoved na spravnou promennou
+ }
+ // test pro starsi format modulu, vraceli chybu v hodnote promene
+ if ((m_error=upsOldTranslateError(word3))) {
+ return m_error;
+ }
+ // zalozime hodnotu do vectoru;
+ (*it).upsValue=word3;
+ if ((*it).upsVarName == "STATUS") {
+ // dogenerujeme dalsi slova pro status
+ word3 += inputStream.readLine();
+ genStatusFlags(word3);
+ }
+ }
+ else {
+ // neznama odpoved - neni ANS ani ERR
+ m_error=UnknownAnswer;
+ return m_error;
+ }
+ }
+ else {
+ m_error=NoData;
+ return m_error;
+ }
+ }
+ else {
+ return m_error;
+ }
+ }
+ }
+ return 0;
+ }
+
+
+
+int KNutNet::getUpsValues2 (const bool allVars ) {// allVars = true vse; allVars = false jen activate
+ QString varName;
+ QString upsNameRet;
+ QString value;
+ int typeValue;
+ int lenString;
+
+ // reads value of variables
+ QCString inBuffer;
+ QString outBuffer;
+ QValueVector<upsVarDef>::iterator it;
+
+ emit getVarDesc (m_numberVars, 0);
+ int numberVar = 0;
+ for (it = m_listVars.begin(); it != m_listVars.end(); it++) {
+ numberVar++;
+ if ((allVars) || ((*it).upsVarActivate)) {
+ //reads variable
+ inBuffer = "GET VAR "+m_upsName+" "+(*it).upsVarName+"\n";
+// if (!(error=getUpsData (inBuffer,outBuffer))) {
+ m_error=getUpsData (inBuffer,outBuffer);
+ // when outBuffer is empty sends and reads date again, but only the only time
+ if ((!(m_error)) && (outBuffer.isEmpty())) m_error=getUpsData (inBuffer,outBuffer);
+ if (!(m_error)) {
+ outBuffer=outBuffer.stripWhiteSpace ();
+ emit getVarDesc (m_numberVars, numberVar);
+ if ( !outBuffer.isEmpty() ) {
+ int key = parseLine(outBuffer, upsNameRet, varName, value, typeValue, lenString);
+ switch (key) {
+ case VAR:
+ if ( varName != (*it).upsVarName ) {
+ m_error=UnknownAnswer;
+ return m_error;// it isn't answer for right variable - neni to odpoved na spravnou promennou
+ }
+ (*it).upsValue=value;
+ if ((((*it).upsVarName == "STATUS") && (m_nutVariables == 1)) || (((*it).upsVarName == "ups.status") && (m_nutVariables == 2))) {
+ // dogenerujeme dalsi slova pro status
+ genStatusFlags(value);
+ }
+ break;
+ case ERR:
+ m_error=upsTranslateError(value);
+ return m_error;
+ default:
+ m_error=UnknownAnswer;
+ return m_error;
+ }
+ }
+ else {
+ m_error= NoData;
+ return m_error;
+ }
+ }
+ else {
+ return m_error;
+ }
+ }
+ }
+ return 0;
+ }
+
+
+int KNutNet::sendComm (const QString command, const QString arg1, const QString arg2, const bool useUpsName) {
+ int localError;
+// nenastavi promenou error ale nenuluje ji
+ QCString inBuffer;
+ QString outBuffer;
+
+ switch (m_nutProtocol) {
+ case 1:
+ inBuffer=command + " " + arg1;
+ if (useUpsName && (!m_upsName.isEmpty())) // pokud upsName neni je vzdy prazdne
+ inBuffer += "@"+m_upsName;
+ if (!arg2.isEmpty()) inBuffer += " " + arg2;
+ break;
+ case 2:
+ inBuffer = command + " ";
+ if (useUpsName) inBuffer += m_upsName + " ";
+ inBuffer.append(arg1);
+ if (!arg2.isEmpty()) inBuffer += " \"" + arg2 +"\"";
+ break;
+ }
+ inBuffer.append("\n");
+
+ if (!(localError=getUpsData (inBuffer,outBuffer))) {
+ outBuffer=outBuffer.stripWhiteSpace();
+ QTextIStream inputStream(&outBuffer);
+ QString word1, word2;
+ inputStream >> word1;
+ inputStream >> word2;
+ if (word1.isEmpty()) return UnknownAnswer; // zadna odpoved
+ if (word1 != "OK") {
+ // neni rovno OK
+ if (word1 == "ERR") return upsTranslateError (word2);
+ else return UnknownAnswer;
+ }
+ else return 0;
+ }
+ else return localError;
+ }
+
+
+int KNutNet::activate ( const QString name, const bool setActivate ) {
+ m_error =0;
+ if (m_state == Connected) {
+ QValueVector<upsVarDef>::iterator it;
+ for (it = m_listVars.begin(); it != m_listVars.end(); it++) {
+ if ((*it).upsVarName == name) {
+ (*it).upsVarActivate = setActivate;
+ return 0;
+ }
+ }
+ m_error = VarNotFind;
+ return m_error;
+ }
+ else return NotConnection;
+ }
+
+int KNutNet::activateAll ( const bool setActivate ) {
+ m_error =0;
+ if (m_state == Connected) {
+ QValueVector<upsVarDef>::iterator it;
+ for (it = m_listVars.begin(); it != m_listVars.end(); it++) {
+ (*it).upsVarActivate = setActivate;
+ }
+ return 0;
+ }
+ else return NotConnection;
+ }
+
+
+int KNutNet::upsTranslateError (const QString string) {
+ if (string == "VAR-NOT-SUPPORTED") return VarNotSupported;
+ if (string == "VAR-UNKNOWN") return VarUnknown;
+
+ if (string == "ACCESS-DENIED") return AccessDenied;
+ if (string == "PASSWORD-REQUIRED") return PasswordRequired;
+ if (string == "PASSWORD-INCORRECT") return PasswordIncorrect;
+ if (string == "UNKNOWN-UPS") return UnknownUps;
+ if (string == "ALREADY-LOGGED_IN") return AlreadyLoggedIn;
+ if (string == "ALREADY-SET-PASSWORD") return AlreadySetPassword;
+ if (string == "ALREADY-SET-USERNAME") return AlreadySetUsername;
+ if (string == "UNKNOWN-COMMAND") return UnknownCommand;
+
+ if (string == "UNKNOWN-INSTCMD") return UnknownInstCmd;
+ if (string == "CMD-NOT-SUPPORTED") return CmdNotSupported;
+
+ if (string == "INVALID-VALUE") return InvalidValue;
+
+ if (string == "NO-RESPONSE") return NoResponse;
+ if (string == "UNKNOWN-REPLY") return UnknownReply;
+ if (string == "NOT-IMPLEMENTED") return NotImplemented;
+ if (string == "COMMAND-FAILED") return CommandFailed;
+
+ if (string == "MISSING-ARGUMENT") return MissingArgument;
+ if (string == "DATA-STALE") return DataStale;
+ if (string == "UNKNOWN-TYPE") return UnknownType;
+
+ if (string == "DRIVER-NOT-CONNECTED") return DriverNotConnected;
+
+ if (string == "") return UnknownFormat;
+
+ return UnknownErr;
+ }
+
+int KNutNet::upsOldTranslateError (const QString string) {
+ if (string == "NOT-SUPPORTED") return VarNotSupported;
+ if (string == "UNKNOWN") return VarUnknown;
+ if (string == "DATA-STALE") return DataStale;
+ return 0; // nebylo nalezeno
+ }
+
+//--------------------Socket----------------
+
+
+void KNutNet::slotConnectionError(int error) {
+//std::cout << "--KNutNet::slotConnectionError" << std::endl;
+//qDebug ("--KNutNet::slotConnectionError");
+
+ m_state = ConnectError;
+ m_unConnectTimer->stop();
+ if (error == QSocket::ErrHostNotFound) {
+ error = NoSuchHost;
+ emit connectionError(error);
+ return;
+ }
+ //connection was refused // no connection
+ if ((error == QSocket::ErrConnectionRefused) && (m_commandSocket->state()==QSocket::Idle)) {
+ if (m_firstConnect) {
+ if (m_numberConnection < m_countRepeat) {
+ m_numberConnection++;
+// qDebug ("--KNutNet:: connect error - try connect on next time");
+ m_unConnectTimer->start( m_delay, TRUE );
+ }
+ else {
+ // i don't connect server
+ error=CantConnect;
+// qDebug("--KNutNet::emit - connection error ");
+ emit connectionError(error);
+ return;
+ }
+ } // end of if (firstConnection)
+ else {
+ // connecting is down, try repeated connection
+
+// qDebug ("--KNutNet::no first connect connection error ");
+ m_unConnectTimer->start( m_delay, TRUE );
+ }
+ return;
+ }
+ if (error == QSocket::ErrConnectionRefused) {
+ error = ConnectionRefused;
+// std::cout << "--KNutNet::connection error ErrConnectionRefused " << QSocket::Idle << " - " << error << std::endl;
+ emit connectionError(error);
+ return;
+ }
+ if (error == QSocket::ErrSocketRead) {
+ error = SocketReadErr;
+// std::cout << "--KNutNet::connection error QSocket::ErrSocketRead " << error << std::endl;
+ emit connectionError(error);
+ return;
+ }
+ }
+
+
+void KNutNet::slotConnected(void) {
+ int n;
+
+ if ((n = version (m_countRepeat, m_delay)) == 0) { // 0 OK, 0> error
+ if ((m_nutProtocol == 0) || (m_nutVariables == 0)) { // answer from upsd (VER) is unknown
+ m_error=NutProtocolVarErr;
+ m_state = Closing;
+ m_commandSocket->close();
+ while (m_commandSocket->state() == QSocket::Closing) {
+ sleep (100);
+ }
+ m_state = ConnectError;
+
+ return;
+ }
+ if ((m_nutProtocol == 2) && m_upsName.isEmpty()) {
+ // if upsName is empty reads first ups name from upsd server
+ if ((m_error =KNutNet::getFirstUpsName (m_upsName))) { // reading first upsName
+ // upsd server doesn't support any ups
+ m_state = Closing;
+ m_commandSocket->close();
+ while (m_commandSocket->state() == QSocket::Closing) {
+ sleep (100);
+ }
+ m_state = ConnectError;
+
+ }
+ }
+ m_state=Connected;
+ }
+ else {
+ m_commandSocket->close();
+ }
+ emit firstConnection();
+// std::cout << "KNutNet::emit - firstConnection" << std::endl;
+ }
+
+void KNutNet::slotHostFound(void) {
+
+// std::cout << "--KNutNet::slotHostFound" << std::endl;
+ m_state = Connecting;
+ emit hostFound();
+ }
+
+
+void KNutNet::slotConnectionClosed(void) {
+
+// std::cout << "--KNutNet::slotConnectionClosed" << std::endl;
+ m_unConnectTimer->stop();
+ deleteVars();
+ m_state = Idle;
+ emit connectionClosed();
+ }
+
+
+
+void KNutNet::slotTimerReconnect(void) {
+// std::cout << "--KNutNet::slotTimerReconnect" << std::endl;
+
+ m_unConnectTimer->stop();
+ if (m_commandSocket->state()==QSocket::Idle) {
+ //std::cout << "--KNutNet::slotTimerReconnect QSOcket::Idle" << std::endl;
+ emit tryRepeatFirstConnection(m_numberConnection);
+ // std::cout << "KNutNet::emit-tryRepeatFirstConnection" << std::endl;
+ m_state=Connecting;
+ if ( m_commandSocket->state() != QSocket::Connecting )
+ m_commandSocket->connectToHost(m_upsAddress,m_port);
+ }
+ }
+
+
+#include "knutnet.moc"
diff --git a/src/knutnet.h b/src/knutnet.h
new file mode 100755
index 0000000..00b8e9a
--- /dev/null
+++ b/src/knutnet.h
@@ -0,0 +1,869 @@
+/***************************************************************************
+ knutnet.h - description
+ -------------------
+ begin : Ne led 12 2003
+ copyright : (C) 2003 by Daniel Prynych
+ email : Daniel@prynych.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTNET_H
+#define KNUTNET_H
+
+//Od verze 3 je kapp jen odkaz na kapplication
+//Since version 3 is kapp pointer on kapplication only
+//#include <kapplication.h>
+#include <kapp.h>
+
+#include <qobject.h>
+#include <qsocket.h>
+#include <qsocketdevice.h>
+#include <qnetworkprotocol.h>
+#include <qmutex.h>
+
+#include <qvaluevector.h>
+
+
+ struct upsVarDef {
+ QString upsVarName;
+ bool upsVarActivate;
+ bool upsVarType; // typ true(1) RO - false (0) RW (muzeme menit)
+ bool upsValueType; // typ true(1) char - false (0) enum (vyctova)
+ // ma vyznam jen pro RW promenne
+ int upsVarMax; // udave max delku string promenne nebo pocet moznosti pro enum promennou
+ // ma vyznam jen pro RW promenne
+ QString upsValue; // hodnota promene
+ QString upsDescription; // informace o promene
+ QValueVector<QString>* upsEnumValues;
+ };
+
+
+ struct upsICommDef {
+ QString upsCommName;
+ QString upsDescription;
+ };
+
+class QString;
+class QCString;
+class QSocket;
+class QTimer;
+
+
+/**
+ *@author Daniel Prynych
+ */
+
+/**
+ * This class reads data from serveru NUT.
+ * Since version 0.5 is written and API is changet.
+ * Since 0.6.1 supports protocol client-server and variables for upsd >= nut 1.3
+ * Since 0.6.1 doesn't ups name like ups_name@host_address
+ * Since 0.7 doesn't support UDP
+ * Tato trida zajistuje cteni dat ze serveru NUT.
+ * Od verze 0.5 je uplne prepsana a je zmeneno i API.
+ * Od verze 0.6.1 proporuje take client-server protokol a promenne pro upsd >= nut 1.3
+ * Od verze 0.6.1 nepodporuje jmeno ups ve tvaru jmeno_ups@adresa_pc
+ * Od verze 0.7 neni podporovano UDP
+ *
+ * @author Daniel Prynych
+ * @short Communication with UPS - Komunikace s UPS
+ * @version 0.7
+*/
+class KNutNet : public QObject {
+ Q_OBJECT
+public:
+
+ enum NetState {Idle, HostLookup, Connecting, Connected, ConnectError,Closing };
+ // idle is same like NotConnected
+ // neni pripojeno chyba pri pripojeni,pripojeno, pripojuji
+
+
+ enum typeOfVar {AllVars, ROVars, RWVars };
+
+ enum NetError {
+ NoError,
+ LowMem, // no memmory - nebyla pridelena pamet
+ NullAddress, // no address of host nebyla zadana adresa pocitace
+ NoSuchHost, // this host noexist neexistuje takovy pocitac
+ CantConnect, // I cannot connect to server Nemohu se spojit se serverem
+ SocketReadErr, // I cannot read data from socket - Nelze cist data ze soketu
+ ConnectErr, // connect isn't maked - Nejde provest connect
+ NutProtocolVarErr, // Nelze zjistit verze protokolu
+ NoUpsHere, // ni UPS on this address na teto adrese neni zadna UPS
+ ConnectionRefused, // server refused connection
+ ConnetionClosedByServer, // connection was closed by server upsd // by the second side
+
+ SendErr, // doesn't send date - Nelze odeslat data
+ RecvErr, // doesn't receive data - Nelze prijmout data
+ NoData, // no data was received, empty string was received - Nebyla prijmuta zadna data, byl prijmut prazdny retezec
+ UnknownAnswer, // Server answer no right - Server neodpovedel spravne
+ UnknownFormat, // Data hasn't got right structure - Data nemaji spravnou strukturu
+ UnknownFormatVer, //Data returned after command VER don't have right structure - Data vracena po prikazu VER nemaji spravnou strukturu
+ NoServerData, // doesn't read data from server (Server isn't answering) Nelze precist data ze serveru (Sever neodpovida)
+ NoUpsnetOk, // UpsNetOK is setting on faLse - je nastaven UpsNetOk na false
+ UnknownErr, // unknown error unknown text after ERR - neznama chyba - neznamy text za ERR
+ CommNotFind, // command hasn't been found in list of module's commands - prikaz nebyl nalezen v seznamu prikazu modulu
+ VarNotFind, // variable hasn't been found in list of module's variables promena nebyla nalezena v seznamu promenych modulu
+ EnumValueNotFind, //value of enumereted variable hasn't been found hodnota vyctove promene nebyla nalezena
+
+// tyto zpravy vraci server
+// this mesages is returned server upsd
+ AccessDenied, // access denied - pristup odmitnut
+ PasswordRequired, // password is required - pro akci je nutno zaslat heslo
+ PasswordIncorrect, // password is incorrect nespravane heslo
+ UnknownUps, // this ups isn't occured on address - tato ups neni na zadane adrese
+ AlreadyLoggedIn, // prihlaseni LOGIN jiz bylo provedeno
+ AlreadySetPassword, // password has been already entered - heslo jiz bylo zadano
+ AlreadySetUsername, // username has been already entered - uzivatelske jmeno jiz bylo zadano
+ DataStale, // data from module isn't got - neni mozne ziskat z modulu nove data
+ MissingArgument, // misses argument - chyby argument
+ UnknownType, // unknown type of variable -neznamy typ promene
+ UnknownCommand, // umknown command example: sends maybe "UPERNAME admin" - nezmamy prikaz pr: poslem treba "UPERNAME admin"
+
+ //tyto chyby se vztahuji k driveru pro danny typ UPS-ky
+ // this mistake is refered for selected driver of UPS
+ DriverNotConnected, // driver isn't connected - driver neni pripojen
+ NoResponse, // driver pro ups neodpovedel ve vymezenem case
+ UnknownReply, // unknown reply - neznama odpoved
+ NotImplemented, //
+ CommandFailed, // failed command - chybny prikaz
+ VarUnknown, // values isn't selected by driver - promena neni driverem podporovana
+ VarNotSupported, // cannot get data for this values - neni mozno zislat data pro tuto promenou
+ InvalidValue, // unknown value - nespravna hodnota
+ UnknownInstCmd, // unknown instant command / neznamy okamzity prikaz
+ CmdNotSupported, // this instant command isn't supported - tento okamzity prikaz neni podporovan
+ NotConnection, // operace nelze provest protoze neni provedeno pripojeni
+ // this not error
+ NoListVars}; //upsd doesn't return list of variables, variable for STATUS has got value WAIT
+
+ enum typeOfStatus {
+ NS = 0, // - NONE status of UPS wasn't read
+ OFF = 1, // - UPS is off (not supplying power)
+ OL = 2, // - UPS is online (supplying power from the line/mains)
+ OB = 4, // - UPS is on battery
+ LB = 8, // - UPS battery is low (with OB = shutdown situation)
+ CAL = 16, // - UPS is performing calibration
+ TRIM = 32, // - UPS is trimming incoming voltage (APC "SmartTrim")
+ BOOST = 64, // - UPS is boosting incoming voltage (APC "SmartBoost")
+ OVER = 128, // - UPS is overloaded
+ RB = 256, // - UPS battery needs to be replaced
+ WAIT = 512 // - UPS as for waiting
+ };
+
+ enum keyWord {
+ NONE,
+ OK,
+ ERR,
+ BEGIN,
+ END,
+ VAR,
+ TYPE,
+ DESC,
+ UPSDESC,
+ CMDDESC,
+ UPS,
+ LIST,
+ RW,
+ CMD,
+ ENUM,
+ STARTTLS,
+ BEGIN_LIST_VAR,
+ BEGIN_LIST_RW,
+ BEGIN_LIST_CMD,
+ BEGIN_LIST_UPS,
+ BEGIN_LIST_ENUM,
+ END_LIST_VAR,
+ END_LIST_RW,
+ END_LIST_CMD,
+ END_LIST_UPS,
+ END_LIST_ENUM
+ };
+
+ enum flagsVar {
+ RW_FLAG = 1,
+ ENUM_FLAG = 2,
+ STRING_FLAG = 4
+ };
+
+
+
+/**
+ * Constructor sets basic variables and structures only, but doesn't read variables from server NUT
+ * Konstruktor pouze nastavi zakladni promene a struktury, ale necte promene se serveru NUT.
+ * @param upsName in name of UPS
+ * @param upsAddress Is address of UPS (adresa pocitace na ktery je UPS pripojena)
+ * netAddress can is entered like ip address or domain name
+ * example: localhost karel.domain,cz 194.212.25.55.
+ * @param tPort Is name if port, for NUT server (NUT is received on this port), default is 3493.
+ * @param delay is delay in msec. System waits before one tries to make connection again. When test of connection fails,
+ * @param countRepeat is maximal number of repeating for make connection.
+ *
+ * Since 0.7.5 version protocol UDP is not supported
+ * @param upsAddress Je adresa ups-ky (adresa pocitace na ktery je UPS pripojena)
+ * netAddress muze byt zadan jako ip adresa nebo domenove jmeno pocitace
+ * @param upsName je jmeno UPSky
+ * pr.: localhost karel.domena.cz 194.212.25.55.
+ * @param tPort je cislo portu na kterem nasloucha NUT server, default je 3493.
+ * @param delay je zpozdeni v msec, System ceka nez znovu pokusi ukutecnit spojeni. Kdyz pokus o spojeni selhal.
+ * @param countRepeat je maximalni pocet opakovani spojeni pro navazani spojeni.
+ * Od verze 0.7 neni podporovano UDP
+ *
+ * @since 0.7.5
+ **/
+ KNutNet (const QString upsAddress, const QString upsName="", const unsigned short port=3493, unsigned int countRepeat =0, const unsigned int delay = 200);
+
+/**
+ * @since 0.5
+ **/
+ ~KNutNet();
+
+
+
+/**
+ * Zavre spojeni a nastavi hodnoty pro novou UPSku
+ * Closes conneting and sets values for new UPS
+ *
+ * @since 0.1
+ **/
+ void newUPS (const QString upsAddress, const QString upsName, const unsigned short port=3493);
+
+
+/**
+ * Provadi spojeni
+ * Makes conneting
+ *
+ * @since 0.1
+ **/
+ void open (void);
+
+/**
+ * Zavre spojeni
+ * Closes conneting
+ *
+ * @since 0.1
+ **/
+ void close (void);
+
+
+/**
+ * Returns kod of error, which is setted after last colling of same function this calls.
+ * Error NotConnected isn't returned (not for function getError, getState).
+ * It means then error NotConnected isn't remembered.
+ * Vraci kod chyby, ktera nastala pri poslednim volani kterekoliv funkce
+ * teto tridy (s vyjimkou getError, getState ),
+ * chyba NotConnected neni vracena;
+ * To znamena ze chyba NotConnected neni zapamatovana.
+ *
+ *
+ * @since 0.5
+ **/
+ int getError ( void );
+
+
+/**
+ * Vraci stav pripojeni.
+ * Returns state of connection.
+ *
+ * @since 0.5
+ **/
+ int getState ( void );
+
+
+/**
+ * Returns state of description, if descriptions is loaded.
+ * Vraci stav popisu, zda je nahran;
+ *
+ * @since 0.5
+ **/
+ bool isDescription ( void );
+
+
+/**
+ * Vraci zda doslo k prepnuti z UDP do TCP;
+ * Ma vyznam je pro verzi protokolu 2
+ *
+ * @since 0.1
+ **/
+bool switchedToTCP ( void );
+
+
+/**
+ * Vraci cislo protokolu pro komunikaci s NUT
+ * Returns nunber of protocol for comunications with NUT
+ * Od verze NUTu 1.3 je zmenen protokol
+ * Since version 1.3 protocol is changed
+ *
+ * @since 0.1
+ **/
+ int getNutProtocol ( void );
+
+/**
+ * Return number of NUT's version
+ * Vraci cislo verze nazvu NUT-u
+ * Since version if nut 1.3 are changed names of values
+ * Od verze NUTu 1.3 jsou zmeneny nazvy promenych
+ *
+ * @since 0.1
+ **/
+ int getNutVariables ( void );
+
+
+
+/**
+ * Nacte vsechny promene UPS-ky a nastavi jejich typ (znakove/char, vyctove/enum a status)
+ * Nastavi priznak aktivity jen pro status.
+ * Funkce vraci kod chyby nebo 0 pokud k chybe nedojde;
+ * Vzdy jsou nacteny i hodnoty promenych.
+ *
+ * @since 0.6.1
+ **/
+ int getUpsVars ( void);
+
+
+/**
+ * Nacte hodnoty vsech promenych UPS-ky pokud je nastaven jejich priznak aktivity,
+ * nebo je nastaven allVars na true.
+ * Pozor po provedeni getUpsVars je priznak aktivity nastaven jen pro status.
+ *
+ * @param allVars Urcuje zda se prikaz tyka vsech promenych, nebo jen tech ktere
+ * maji nastaven priznak aktivity na TRUE.
+ *
+ * @since 0.6.1
+ **/
+ int getUpsValues (const bool allVars=true );
+
+
+/**
+ * Nacte popisy pro kazdou promennou
+ * Read descriptions for every variable
+ *
+ * @param always Urcuje zda se nacteny provede vzdy nebo jen kdy popis jeste
+ * nebyl nacten.
+ *
+ * @since 0.6
+ **/
+ int getDescription (bool always = false);
+
+
+/**
+ * Provede okamzity prikaz.
+ * Vraci 0 pokud provedeni skoncilo v poradku jinak kod chyby.
+ *
+ * @param command Udava nazev prikazu.
+ * @param userName Udava uzivatelske jmeno.
+ * @param password Udava heslo.
+ * @param onlyCommand udava zda ma byt poslan pouze prikaz, nebo i nastaveno uzivatelske jmeno a heslo.
+ * POZOR!! uzivatelske jmeno nejde zmenit bez odpojeni a znovu pripojeni.
+ *
+ * @since 0.7
+ **/
+ int instantCommand (const QString command, const QString userName, const QString password, const bool onlyCommand = false);
+
+
+/**
+ * Nastavi RW promenou.
+ * Vraci 0 pokud provedeni skoncilo v poradku jinak kod chyby;
+ *
+ * @param variable Udava nazev promenne.
+ * @param value Udava hodnotu.
+ * @param userName Udava uzivatelske jmeno.
+ * @param password Udava heslo.
+ * @param onlyVariable udava zda ma byt poslana pouze zadost na zmenu promenne, nebo i nastaveno uzivatelske jmeno a heslo.
+ * POZOR!! uzivatelske jmeno nejde zmenit bez odpojeni a znovu pripojeni.
+ *
+ * @since 0.7
+ **/
+ int setVariable (const QString variable, const QString value, const QString userName, const QString password, const bool onlyVariable = false);
+
+
+
+/**
+ * Returns number of UPS's variables. On error -1 is returned.
+ * Vrati pocet promenych UPS-ky. Pri chybe vraci -1.
+ *
+ * @param typVar Is type of variable, its number is found out.
+ * @param typVar Je typ promene pro ktere zjistujeme pocet
+ * muze se jednat o RO promenne RW promene nebo o vsechny promenne.
+ *
+ * @since 0.6
+ **/
+ int readNumberVars (typeOfVar typVar = AllVars);
+
+
+/**
+ * Returns number of UPS's commands. On erroe -1 is returned.
+ * Vrati pocet prikazu UPS-ky. Pri chybe vraci -1.
+ *
+ * @since 0.6
+ **/
+ int readNumberComms (void);
+
+
+
+/**
+ * Nastavi strukturu udavajici vsechny hodnoty pro prikaz.
+ * Pri chybe vrati kod chyby
+ *
+ * @param seqNumber Udava cislo promene.
+ * @param upsIComm Je struktura upsICommDef.
+ *
+ * @since 0.6
+ **/
+ int readIComm (const int seqNumber, upsICommDef& upsIComm);
+
+
+/**
+ * Nastavi strukturu obsahujici vsechny udaje promene.
+ * Pri chybe vrati kod chyby.
+ *
+ * @param name Udava jmeno promene.
+ *
+ * @since 0.6
+ **/
+ int readVars (const QString name, struct upsVarDef& allVar);
+
+
+/**
+ * Nastavi strukturu obsahujici vsechny udaje promene.
+ * Pri chybe vrati kod chyby.
+ *
+ * @param seqNumber Udava poradove cislo promene, ta zacina VZDY cislem 1.
+ * @param typVar Udava typ promene /RO/RW/ALL.
+ *
+ * @since 0.6
+ **/
+ int readVars (const int seqNumber, struct upsVarDef& allVar, const typeOfVar typVar = AllVars);
+
+
+/**
+ * Vrati hodnotu promenne.
+ * Pri chybe vrati 0l.
+ *
+ * @param name Udava jmeno promene.
+ *
+ * @since 0.6.1
+ **/
+ QString readStringVar (const QString name);
+
+/**
+ * Nacte jednu z hodnot vyctove promenne.
+ * Vraci jednu z hodnot vyctove promenne udanou poradovym cislem hodnoty.
+ * Pri chybe vrati 0l.
+ *
+ * @param name Udava nazev vyctove promenne.
+ * @param valueNumber Udava poradove cislo hodnoty vyctove promenne.
+ * @param enumValue Je naplnena hodnotou vyctove promenne.
+ *
+ * @since 0.6.1
+ **/
+ QString readEnumValueVar (const QString name, const int valueNumber);
+
+
+/**
+ * Vraci kod stavu (statusu) UPS-ky
+ * kody je mozne scitat napt OB+LB = 12
+ * OFF = 1, UPS-ka je vypnuta
+ * OL = 2, UPS-ka bezi na sit
+ * OB = 4 UPS-ka bezi na baterie
+ * LB = 8 baterie je vybyta (pokud je zaroven OB dojde k shutdownu)
+ * CAL = je spustena kalibrace UPS-ky
+ * OVER =128 UPS-ka je pretizena
+ * RB = 256 UPS-ka pozaduje vymenu baterie
+ *
+ * @since 0.5
+ **/
+int readStatus(void);
+
+
+/**
+ * Nastavi priznak aktivity.
+ * Pri chybe vrati kod chyby.
+ *
+ * @param name Udava jmeno promene.
+ *
+ * @since 0.6
+ **/
+ int setActivate ( const QString name );
+
+/**
+ * Zrusi nastaveni priznaku aktivity.
+ * Pri chybe vrati kod chyby.
+ *
+ * @param name Udava jmeno promene.
+ *
+ * @since 0.6
+ **/
+ int unSetActivate ( const QString name );
+
+/**
+ * Zrusi nastaveni priznaku aktivity pro VSECHNY promene.
+ * Pri chybe vrati kod chyby.
+ *
+ * @since 0.6
+ **/
+ int unSetActivateAll ( void );
+
+
+
+/**
+ * Testuje zda existuje promena danneho jmena.
+ * POZOR ZMENA v NAVRATOVYCH HODNOTACH
+ * Vraci 0 pokud existuje.
+ * Pokud neexistuje nebo pri chybe vrati kod chyby.
+ *
+ * @param name Udava jmeno promene.
+ *
+ * @since 0.6
+ **/
+ int existName ( const QString name );
+
+/********* Consts ****************/
+
+
+static const int initState = OL;
+
+signals:
+/**
+ * Signal je vyslan, kdyz dojde k chube.
+ * Signal is emited, when error is occurred
+ *
+ * param@ error je cislo chyby.
+ * param@ error je value of error.
+ **/
+void connectionError(int error);
+
+
+/**
+ * Signal je vyslan, kdyz druha starna uzavrela spojeni.
+ * Signal is emited, when other side closed connection.
+ *
+ * @since 0.1
+ **/
+void connectionClosed (void);
+
+/**
+ * Signal je vyslan, kdyz dojde k prvemu spojeni se serverem.
+ * Signal is emited, when the first connection with server is realized
+ *
+ * @since 0.1
+ **/
+void firstConnection(void); /**
+ * Signal je vyslan, kdyz dojde k dalsimu spojeni se serverem, znovu pripojeni.
+ * Signal is emited, when next connection with server is realized, reconnect.
+ *
+ * @since 0.1
+ **/
+void nextConnection(void);
+ /**
+ * Signal je vyslan, kdyz prevod jmena byl uspesny.
+ * Signal is emited, when host lookup has succeeded
+ *
+ * @since 0.1
+ **/
+void hostFound(void);
+
+
+ /**
+ * Signal je vyslan, kdyz spojeni je opet zkouseno.
+ * Signal is emited, when connection is tried again.
+ *
+ * @since 0.1
+ **/
+void tryRepeatFirstConnection( int );
+
+
+ /**
+ * Signal je vyslan, kdyz spojeni je zkouseno poprve.
+ * Signal is emited, when connection is tried at first.
+ *
+ * @since 0.1
+ **/
+void tryFirstConnection( int);
+
+
+// signals:
+
+ void getVarDesc (int count, int item);
+
+/********* Private part **********/
+
+ private:
+
+// internal funkcion
+
+
+/**
+ * Cleans input buffer
+ * Vycisti vstupni buffer
+ *
+ * @since 0.1
+ **/
+void cleanConnecting (void);
+
+
+/**
+ * Prevede textovy nazev klice na jeho numerickou hodnotu
+ * Jen pro protokol verze 2.
+ * Funkce vraci kod klice;
+ * param@ line textovy nazev klice.
+ *
+ * @since 0.1
+ **/
+int setKey (const QString line);
+
+QString parseValue (const QString line);
+
+/**
+ * Parsuje typ promenne (RW ENUM STRING).
+ * Jen pro protokol verze 2.
+ * Funkce vraci soucet kodu typu promenych;
+ * param@ line retezec ktery se parsuje.
+ * param@ lenString vraci maximalni delka promenne typu STRING.
+ *
+ * @since 0.1.1
+ **/
+int parseTypeValue (QString line, int& lenString );
+
+
+
+/**
+ * Parsuje navratovou hodnotu z upsd (protokol klient-server).
+ * Jen pro protokol verze 2.
+ * Funkce vraci kod prikazu (UPS, VAR BEGIN_LIST_VAR );
+ *
+ * @since 0.1
+ **/
+int parseLine(QString& line, QString& upsName ,QString& varName, QString& value, int& typeValue, int& lenString);
+
+
+
+/**
+ * Nacte popisy pro kazdou promennou
+ * Jen pro protokol verze 1.
+ *
+ * @param always Urcuje zda se nacteny provede vzdy nebo jen kdy popis jeste
+ * nebyl nacten.
+ *
+ * @since 0.1
+ **/
+ int getDescription1 (bool always = false);
+
+/**
+ * Nacte popisy pro kazdou promennou
+ * Jen pro protokol verze 2.
+ *
+ * @param always Urcuje zda se nacteny provede vzdy nebo jen kdy popis jeste
+ * nebyl nacten.
+ *
+ * @since 0.1
+ **/
+ int getDescription2 (bool always = false);
+
+
+
+/**
+ * internal
+ * Nacte nazev prvni UPS-ky na danne adrese.
+ * Jen pro protokol verze 2
+ * Funkce vraci kod chyby nebo 0 pokud k chybe nedojde;
+ *
+ * @since 0.1
+ **/
+int getFirstUpsName (QString& firstUpsName);
+
+
+/**
+ * internal
+ * Nacte vsechny promene UPS-ky a nastavi jejich typ (znakove/char, vyctove/enum a status)
+ * nastavi priznak aktivity jen pro status.
+ * Jen pro protokol verze 2
+ * Funkce vraci kod chyby nebo 0 pokud k chybe nedojde;
+ *
+ * @since 0.1
+ **/
+ int getUpsVars1 ( void);
+
+
+
+/**
+ * internal
+ * Nacte vsechny promene UPS-ky a nastavi jejich typ (znakove/char, vyctove/enum a status)
+ * nastavi priznak aktivity jen pro status.
+ * Jen pro protokol verze 2
+ * Funkce vraci kod chyby nebo 0 pokud k chybe nedojde;
+ *
+ * @since 0.2
+ **/
+ int getUpsVars2 ( void);
+
+
+
+/**
+ * Nacte hodnoty vsech promenych UPS-ky pokud je nastaven jejich priznak aktivity,
+ * nebo je nastaven allVars na true.
+ *
+ * @param allVars Urcuje zda se prikaz tyka vsech promenych, nebo jen tech ktere
+ * maji nastaven priznak aktivity na TRUE.
+ * Jen pro protokol verze 1
+ *
+ * @since 0.6
+ **/
+ int getUpsValues1 (const bool allVars );
+
+/**
+ * Nacte hodnoty vsech promenych UPS-ky pokud je nastaven jejich priznak aktivity,
+ * nebo je nastaven allVars na true.
+ *
+ * @param allVars Urcuje zda se prikaz tyka vsech promenych, nebo jen tech ktere
+ * maji nastaven priznak aktivity na TRUE.
+ * Jen pro protokol verze 2
+ *
+ * @since 0.6
+ **/
+ int getUpsValues2 (const bool allVars );
+
+
+/**
+ * @internal
+ * Zjisti verzi upsd
+ *
+ * @param countRepeat maximalni pocet pokusu (ne opakovani !!)
+ * @param delay zpozdeni, cas mezi opakovani
+ */
+ int version (int countRepeat, const int delay);
+
+
+/**
+ * @internal
+ * Nenastavuje promenou error.
+ * Doesn't set variable error
+ */
+ int getUpsData (const QCString sbuffer, QString& rbuffer, const QCString endString=0);
+
+/**
+ * @internal
+ */
+ void setRWVars (const QString varName, const bool valueType, const int varMax, QValueVector<QString>* enumValues);
+
+/**
+ * @internal
+ */
+void upsSetType (struct upsVarDef& upsVar, const QString name, const QString value = "");
+
+/**
+ * @internal
+ */
+ int upsTranslateError (const QString string);
+
+
+/**
+ * @internal
+ */
+ void deleteVars (void);
+
+/**
+ * @internal
+ */
+ int upsOldTranslateError (const QString string);
+
+
+/**
+ * @internal
+ * Pro qt mensi nez 3.0.0 nemuze byt value const
+ */
+ void genStatusFlags (QString value);
+
+/**
+ * @internal
+ * Nenastavuje promenou error.
+ */
+ int sendComm (const QString command, const QString arg1, const QString arg2, const bool useUpsName=false);
+
+
+/**
+ * @internal
+ */
+ int activate ( const QString name, const bool setActivate );
+
+
+/**
+ * @internal
+ */
+ int activateAll ( const bool setActivate );
+
+
+/**
+ * @internal
+ */
+ int newDescription (const QCString inBuffer, QString& upsDescription);
+
+private slots:
+ void slotConnectionError(int error);
+
+ void slotConnected(void);
+
+ void slotTimerReconnect(void);
+
+ void slotHostFound(void);
+
+ void slotConnectionClosed(void);
+
+ void slotClosed (void);
+
+
+private:
+
+ /******* CONST ********/
+
+ static const Q_ULONG rBufferLen = 1024;
+
+ QSocket *m_commandSocket;
+ QTimer* m_unConnectTimer;
+
+
+ /****** VARS *************/
+ QString m_upsAddress;
+ QString m_upsName;
+
+ unsigned int m_countRepeat;
+ unsigned short m_port;
+ unsigned int m_delay;
+
+ NetState m_state;
+ int m_error;
+ bool m_firstConnect;
+ unsigned int m_numberConnection;
+
+ int m_nutProtocol; // 1 for NUT <1.3, 2 for NUT => 1.3
+ int m_nutVariables; // 1 for NUT <1.3, 2 for NUT => 1.3
+
+
+ int m_numberVars; // number of all variables - pocet vsech promennych
+ int m_numberRWVars;
+ int m_numberIComms;
+
+ int m_upsStatusVar;
+ bool m_description;
+
+ bool m_switchToTCP;
+
+ QMutex m_getUpsDataMutex;
+
+ QValueVector<upsVarDef> m_listVars;
+ QValueVector<upsICommDef> m_listIComms;
+
+/********* Pomocne promenne ***********/
+ int m_posChar;
+
+};
+
+#endif
+
diff --git a/src/knutnewupsdlg.cpp b/src/knutnewupsdlg.cpp
new file mode 100644
index 0000000..6cdd2b9
--- /dev/null
+++ b/src/knutnewupsdlg.cpp
@@ -0,0 +1,294 @@
+/***************************************************************************
+ knutnewupsdlg.cpp - description
+ -------------------
+ begin : Tue Aug 21 2001
+ copyright : (C) 2001 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#include "knutnewupsdlg.h"
+
+#include <klocale.h>
+#include <kmessagebox.h>
+#include <kactionselector.h>
+
+#include <qstring.h>
+#include <qlayout.h>
+#include <qframe.h>
+#include <qlabel.h>
+#include <qgroupbox.h>
+//#include <qradiobutton.h>
+#include <qbuttongroup.h>
+#include <qcheckbox.h>
+#include <qlistbox.h>
+
+//#include <iostream>
+
+
+
+KNutNewUpsDlg::KNutNewUpsDlg (KNutUpsData* const upsData, KNutVarData* const analogData, const bool add, QWidget* parent, const char* name, const bool modal)
+ : KDialogBase(Plain, i18n("New Ups"),Help|Ok|Cancel,Ok, parent, name, modal, true ), addMember(add), m_myUpsData(upsData) {
+
+ setName( "KupsNewUpsDlg" );
+
+ QFrame *page =plainPage();
+ QVBoxLayout *mainLayout = new QVBoxLayout( page, 0, spacingHint(), "mainLayout" );
+ QHBoxLayout *dataLayout = new QHBoxLayout(mainLayout, spacingHint(),"dataLayout");
+
+
+ QGroupBox *hostBox = new QGroupBox (page,"hostBox");
+ QGridLayout *hostLayout = new QGridLayout (hostBox, 5, 2, spacingHint () );
+ hostBox->setFrameStyle(QFrame::NoFrame);
+ dataLayout->addWidget(hostBox);
+
+ QHBoxLayout *portLayout = new QHBoxLayout(-1,"portLayout");
+ hostLayout->addLayout(portLayout,4,1);
+
+ QHBoxLayout *loginLayout = new QHBoxLayout(-1,"loginLayout");
+ hostLayout->addLayout(loginLayout,5,1);
+
+
+ QGroupBox* GroupBox2 = new QGroupBox( page, "GroupBox2" );
+
+
+ QVBoxLayout *vActionSelectorLayout = new QVBoxLayout( GroupBox2, 0, spacingHint(), "VActionLayout" );
+ vActionSelectorLayout->addSpacing(fontMetrics().lineSpacing());
+ QHBoxLayout *hActionSelectorLayout = new QHBoxLayout( vActionSelectorLayout, spacingHint(), "HActionLayout" );
+ vActionSelectorLayout->addSpacing(10);
+
+
+ QLabel* TextLabel1 = new QLabel( i18n("Name")+":",hostBox, "TextLabel1" );
+ hostLayout->addWidget (TextLabel1,1,0);
+ m_lineEdit1 = new KLineEdit( hostBox, "LineEdit1" );
+ m_lineEdit1->setEnabled( add );
+ // pokud se nejedna o pridani (add) neni jmeno aktivovani
+ // when makes adding name isn;t activated
+ hostLayout->addWidget (m_lineEdit1,1,1);
+
+ QLabel* TextLabel2 = new QLabel(i18n("UPS address")+":", hostBox, "TextLabel2" );
+ hostLayout->addWidget (TextLabel2,2,0);
+ m_lineEdit2 = new KLineEdit( hostBox, "LineEdit2" );
+ hostLayout->addWidget (m_lineEdit2,2,1);
+
+// Name of UPS
+ QLabel* TextLabel7 = new QLabel(i18n("UPS name")+":", hostBox, "TextLabel7" );
+ hostLayout->addWidget (TextLabel7,3,0);
+ m_lineEdit7 = new KLineEdit( hostBox, "LineEdit7" );
+ hostLayout->addWidget (m_lineEdit7,3,1);
+
+
+ QLabel* TextLabel3 = new QLabel(i18n("Delay (ms):"), hostBox, "TextLabel3" );
+ hostLayout->addWidget (TextLabel3,4,0);
+ m_lineEdit3 = new KLineEdit( hostBox, "LineEdit3" );
+ m_lineEdit3->setText("5000");
+ portLayout->addWidget(m_lineEdit3);
+ portLayout->addSpacing(10);
+
+ QLabel* TextLabel4 = new QLabel(i18n("Port:"), hostBox, "TextLabel4" );
+ m_lineEdit4 = new KLineEdit( hostBox, "LineEdit4" );
+ m_lineEdit4->setText(QString("%1").arg(knc::DefaultPort));
+ portLayout->addWidget(TextLabel4);
+ portLayout->addWidget(m_lineEdit4);
+
+ QLabel* TextLabel5 = new QLabel(i18n("User name:"), hostBox, "TextLabel5" );
+ hostLayout->addWidget (TextLabel5,5,0);
+ m_lineEdit5 = new KLineEdit( hostBox, "LineEdit5" );
+ m_lineEdit5->setText("");
+ loginLayout->addWidget(m_lineEdit5);
+ loginLayout->addSpacing(10);
+
+ QLabel* TextLabel6 = new QLabel(i18n("Password:"), hostBox, "TextLabel6" );
+ m_lineEdit6 = new KLineEdit( hostBox, "LineEdit6" );
+ m_lineEdit6->setEchoMode(QLineEdit::Password);
+ m_lineEdit6->setText("");
+ loginLayout->addWidget(TextLabel6);
+ loginLayout->addWidget(m_lineEdit6);
+
+ m_savePassword = new QCheckBox (i18n("Store NUT password in configuration file"),page,"savePassword");
+ mainLayout->addWidget(m_savePassword);
+ mainLayout->addWidget(GroupBox2);
+
+
+ m_upsValueSelector = new KActionSelector(GroupBox2);
+
+ m_upsValueSelector->setAvailableLabel(i18n("Availabled UPS values"));
+ m_upsValueSelector->setSelectedLabel(i18n("Selected UPS values"));
+ m_upsValueSelector->setAvailableInsertionPolicy(KActionSelector::Sorted);
+ m_upsValueSelector->setSelectedInsertionPolicy(KActionSelector::AtBottom);
+
+ hActionSelectorLayout->addSpacing(10);
+ hActionSelectorLayout->addWidget(m_upsValueSelector);
+ hActionSelectorLayout->addSpacing(10);
+
+ mainLayout->addStretch(10);
+
+ GroupBox2->setTitle( i18n( "UPS Variables" ));
+
+ QListBox* aListBox = m_upsValueSelector->availableListBox();
+ for (int i=1; i < knc::NumberOfTypes; i++) { //values 0 is None, this values isn't showing
+ new KNutUpsBoxItem (aListBox,analogData->getNameAnalogData(i),i);
+ }
+
+ aListBox->sort(true);
+ }
+
+
+
+KNutNewUpsDlg::~KNutNewUpsDlg() {
+ }
+
+
+void KNutNewUpsDlg::moveToSelectedList (const int codeUpsVar) {
+
+if (codeUpsVar == 0) return;
+if (isExistSelectedItem(codeUpsVar)) return; //Value is moved yet
+
+KNutUpsBoxItem * availableItem;
+availableItem =(KNutUpsBoxItem*) m_upsValueSelector->availableListBox()->firstItem();
+
+while (availableItem != 0) {
+ if (availableItem->getVarCode() == codeUpsVar) {
+ break;
+ }
+ availableItem=(KNutUpsBoxItem*)availableItem->next();
+ }
+
+//remove item from left list
+if (availableItem != 0) {
+ QListBox* sListBox = m_upsValueSelector->selectedListBox();
+ new KNutUpsBoxItem (sListBox,availableItem->text(),codeUpsVar);
+ m_upsValueSelector->availableListBox()->removeItem(m_upsValueSelector->availableListBox()->index(availableItem));
+
+ }
+}
+
+
+bool KNutNewUpsDlg::isExistSelectedItem (const int codeUpsVar) const {
+
+KNutUpsBoxItem * selectedItem;
+selectedItem =(KNutUpsBoxItem*) m_upsValueSelector->selectedListBox()->firstItem();
+
+
+while (selectedItem != 0) {
+ if (selectedItem->getVarCode() == codeUpsVar) return true;
+ selectedItem=(KNutUpsBoxItem*)selectedItem->next();
+ }
+return false;
+}
+
+
+void KNutNewUpsDlg::putData (const KNutUpsData::upsRecordDef upsRecord ) {
+ m_lineEdit1->setText(upsRecord.name);
+ m_lineEdit2->setText(upsRecord.upsAddress);
+ m_lineEdit7->setText(upsRecord.upsName);
+ QString delay, port;
+ delay.setNum(upsRecord.delay);
+ m_lineEdit3->setText(delay);
+ port.setNum(upsRecord.port);
+ m_lineEdit4->setText(port);
+ m_lineEdit5->setText(upsRecord.userName);
+ m_lineEdit6->setText(upsRecord.password);
+// RadioButton1->setChecked( !upsInfo.tcp );
+// RadioButton2->setChecked( upsInfo.tcp );
+ m_savePassword->setChecked(m_savePassword);
+
+ for (int j=0; j <knc::NumberOfVars; j++) moveToSelectedList (upsRecord.upsVarCode[j]);
+
+ }
+
+
+KNutUpsData::upsRecordDef KNutNewUpsDlg::getData (void ) const {
+KNutUpsData::upsRecordDef upsRecord;
+
+ upsRecord.name=m_lineEdit1->text();
+ upsRecord.upsAddress=m_lineEdit2->text();
+ upsRecord.upsName= m_lineEdit7->text();
+ upsRecord.delay=m_lineEdit3->text().toLong();
+ upsRecord.port=(short unsigned)m_lineEdit4->text().toUInt();
+// upsInfo.tcp=RadioButton2->isChecked();
+ upsRecord.userName=m_lineEdit5->text();
+ upsRecord.password=m_lineEdit6->text();
+ upsRecord.savePassword=m_savePassword->isChecked();
+
+
+ int j =0;
+ KNutUpsBoxItem * selectedItem;
+ selectedItem =(KNutUpsBoxItem*) m_upsValueSelector->selectedListBox()->firstItem();
+
+ while (selectedItem != 0) {
+ upsRecord.upsVarCode[j++]=selectedItem->getVarCode();
+ selectedItem=(KNutUpsBoxItem*)selectedItem->next();
+ }
+
+ for (int i=j; i < knc::NumberOfVars; i++) {
+ upsRecord.upsVarCode[i]=0;
+ }
+
+ return upsRecord;
+ }
+
+/*********************************************************************************************/
+/* */
+/* PRIVATE SLOTS */
+/* */
+/*********************************************************************************************/
+
+
+
+void KNutNewUpsDlg::slotOk() {
+ bool ok;
+ // closes window
+ m_lineEdit1->setText(m_lineEdit1->text().stripWhiteSpace());
+ m_lineEdit2->setText(m_lineEdit2->text().stripWhiteSpace());
+
+ if ((m_lineEdit1->text().length() <1 )
+ || (m_lineEdit2->text().length() <1 )) {
+ KMessageBox::sorry (0,i18n("No Name or UPS address"));
+ return;
+ }
+
+ if (addMember) {
+ // when UpsName is existed we cannot make new record
+ // pokud UpsName jiz existuje nemuzeme vytvorit novy zaznam
+ if ( m_myUpsData->findName(m_lineEdit1->text()) != 0L ) {
+ KMessageBox::sorry (0,i18n("This Name exist"));
+ return;
+ }
+ }
+
+ long delay = m_lineEdit3->text().toLong(&ok);
+ if (! ok) {
+ KMessageBox::sorry (0,i18n("Delay must be number"));
+ return;
+ }
+
+ long port = m_lineEdit4->text().toLong(&ok);
+ if (! ok) {
+ KMessageBox::sorry (0,i18n("Port must be number"));
+ return;
+ }
+
+ if ((port < knc::StartPort) || (port > knc::StopPort)) {
+ KMessageBox::sorry (0,i18n("Port must be from 1025 until 65535"));
+ return;
+ }
+
+ if (delay < knc::MinDelay) {
+ KMessageBox::sorry (0,i18n("Delay is too small"));
+ return;
+ }
+ accept ();
+ }
+
+
+
+#include "knutnewupsdlg.moc"
diff --git a/src/knutnewupsdlg.h b/src/knutnewupsdlg.h
new file mode 100644
index 0000000..447c089
--- /dev/null
+++ b/src/knutnewupsdlg.h
@@ -0,0 +1,160 @@
+/***************************************************************************
+ knutnewupsdlg.h - description
+ -------------------
+ begin : Tue Aug 21 2001
+ copyright : (C) 2001 by Daniel Prynych
+ email : Daniel@prynych.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTNEWUPSDLG_H
+#define KNUTNEWUPSDLG_H
+
+#include "knutupsdata.h"
+#include "knutvardata.h"
+
+#include <kdialogbase.h>
+#include <kcombobox.h>
+#include <klineedit.h>
+#include <kpushbutton.h>
+#include <kactionselector.h>
+
+#include <qlistbox.h>
+
+
+class QLabel;
+class QGroupBox;
+class QButtonGroup;
+class QCheckBox;
+
+/**
+ * This class is dialog for makeing or correting informations about UPS.
+ * It can set address, port and seletcts values its values will be found,
+ * Tato trida je dialog pro vytvoreni nebo opravu informaci a UPS.
+ * Umoznuje nastavit adresu, port, a vybrat promennou jejiz hodnota se bude zjistovat.
+ * @author Daniel Prynych
+ * @short Panel for setting parameters of UPS
+ *
+ * @version 0.4
+ */
+class KNutNewUpsDlg : public KDialogBase
+{
+ Q_OBJECT
+
+public:
+
+/**
+ * Constructor - makes configure dialog.
+ * Konstruktor - vytvori konfiguracni dialog.
+ *
+ * @param add Urcuje zda budeme data opravovat nebo pridavat.
+ * @param settingData pointer on structure, which includes values which is setted in dialog.
+ * @param upsdata is pointer on instance of class KNutUpsData.
+ * @param analogData is pointer on instance of class KNutVardata
+ * @param add Urcuje zda budeme data opravovat nebo pridavat.
+ * @param settingData Je odkaz na strukturu ktera obsahuje hodnoty nastavovane v dialogu.
+ * @param upsData Je odkaz na na instanci tridy KNutUpsData.
+ * @param analogData Je odkaz na na instanci tridy KNutVarData.
+ *
+ * @since 0.7
+ **/
+ KNutNewUpsDlg (KNutUpsData* const upsData, KNutVarData* const analogData, const bool add = TRUE, QWidget* parent = 0, const char* name = 0, const bool modal = TRUE);
+
+/**
+ * @since 0.3
+ **/
+ ~KNutNewUpsDlg();
+
+/**
+ * Reads data from items of form.
+ * Precte data z polozek formulare.
+ *
+ * @param upRecordDef Struktura of UpsInfo - contains all items which is included in form.
+ * @param upsRecordDef Struktura UpsInfo - obsahuje vsechny polozky ktere jsou ve formulari.
+ *
+ * @since 0.4
+ **/
+ KNutUpsData::upsRecordDef getData (void ) const;
+
+/**
+ * Puts date into intems of form
+ * Vlozi data do polozek formulare.
+ *
+ * @param upsRecord Struktura of upsRecordDef - contains all items which is included in form.
+ * @param upsRecord Struktura psRecordDef - obsahuje vsechny polozky ktere jsou ve formulari.
+ *
+ * @since 0.4
+ **/
+ void putData (const KNutUpsData::upsRecordDef upsRecord );
+
+/********************* PRIVATE **************************/
+
+ private slots:
+
+/**
+ * Is activated when button ok is pressed.
+ * Provede se pri stisknuti tlacitka ok.
+ *
+ * @since 0.1
+ **/
+ virtual void slotOk();
+
+
+private:
+/**
+ * This class is inner class for showing items.
+ * Add information about order number of UPS values.
+ * Tato trida je vnorena trida pro zobrazeni polozek.
+ * Pridava informaci o poradovem cisle UPS promennych.
+ * @author Daniel Prynych
+ * @short Item of listBox
+ *
+ * @version 0.1
+ */
+ class KNutUpsBoxItem : public QListBoxText
+ {
+ private:
+ int m_ordVarCode;
+
+ public:
+ KNutUpsBoxItem ( QListBox* listbox, const QString & text=QString::null, const int ordVarCode = 0 ) :
+ QListBoxText (listbox, text), m_ordVarCode (ordVarCode) {};
+ KNutUpsBoxItem ( QListBox* listbox, const QString & text, QListBoxItem *after, const int ordVarCode = 0 ) :
+ QListBoxText (listbox, text, after), m_ordVarCode (ordVarCode) {};
+ int getVarCode (void) const {return m_ordVarCode;};
+ void putGetCode (const int ordVarCode) {m_ordVarCode = ordVarCode;};
+// QString text () const {return QListBoxItem::text();};
+ };
+
+
+ void moveToSelectedList (const int codeUpsVar);
+
+ bool isExistSelectedItem (const int codeUpsVar) const;
+
+
+ bool addMember; // true pokud se pridava polozka, false edit
+ KNutUpsData* m_myUpsData; // Ups data object
+
+ KLineEdit* m_lineEdit1;
+ KLineEdit* m_lineEdit2;
+ KLineEdit* m_lineEdit3;
+ KLineEdit* m_lineEdit4;
+ KLineEdit* m_lineEdit5;
+ KLineEdit* m_lineEdit6;
+ KLineEdit* m_lineEdit7;
+
+ QCheckBox* m_savePassword;
+
+ KActionSelector* m_upsValueSelector;
+
+};
+
+#endif
diff --git a/src/knutpanelmeter.cpp b/src/knutpanelmeter.cpp
new file mode 100644
index 0000000..e27a246
--- /dev/null
+++ b/src/knutpanelmeter.cpp
@@ -0,0 +1,353 @@
+/***************************************************************************
+ knutpanelmeter.cpp - description
+ -------------------
+ begin : Út b?e 16 2004
+ copyright : (C) 2004 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#include "knutpanelmeter.h"
+
+#include <kdebug.h>
+
+#include <qlayout.h>
+#include <qlabel.h>
+#include <qfont.h>
+
+
+#include <math.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+//#include <iostream>
+
+
+extern const char *nameUpsVars1[];
+extern const char *nameUpsVars2[];
+
+
+KNutPanelMeter::KNutPanelMeter(QPalette aPanelPalette, KNutVarData::upsInfoDef* activeUpsInfo, KNutVarData::SettingDataDef* settingData, KNutVarData* analogRecords, QWidget *parent, const char *name ) : QScrollView(parent,name,Qt::WResizeNoErase|Qt::WStaticContents) {
+
+ m_settingData = settingData;
+ m_activeUpsInfo = activeUpsInfo;
+ m_analogRecords = analogRecords;
+ m_aPanelPalette = aPanelPalette;
+
+ m_analogArea = new QLabel(this->viewport());
+ addChild(m_analogArea);
+ setResizePolicy ( QScrollView::AutoOneFit ) ;
+
+
+////NUTNO PAK UPRAVIT ACTIVATE A DEAKTIVATE ANALOGS
+ m_analogPanels = new analogPanelRecordsDef;
+ for (int i=0; i< knc::NumberOfVars; i++)
+ m_analogPanels->upsAnalogs[i]=0L;
+
+ m_widthArea =0;
+ m_heightArea =0;
+ }
+
+KNutPanelMeter::~KNutPanelMeter(){
+
+ deActivateAnalogs();
+ delete m_analogPanels;
+ m_analogPanels=0L;
+ }
+
+
+
+void KNutPanelMeter::deActivateAnalogs (void) {
+
+//std::cout << "KNutPanelMeter::deActivateAnalogs" << std::endl;
+
+ if (m_analogPanels) {
+ for (int i=0; i< knc::NumberOfVars; i++) {
+ if (m_analogPanels->upsAnalogs[i] != 0) {
+ delete m_analogPanels->upsAnalogs[i]; // uvolnime meraky
+ }
+ m_analogPanels->upsAnalogs[i]=0L;
+ }
+ }
+ m_widthArea =0;
+ m_heightArea =0;
+ }
+
+void KNutPanelMeter::activateAnalogs (void) {
+//qDebug ("KNutPanelMeter::activateAnalogs start");
+
+
+ KNutVarData::VarStrucDef analogMemberData;
+ int ii =0;
+ // deletes vatiables which ups doeasn't support
+ // vyjmeme promene ktere ups nepodporuje
+
+ //// nasledujici radka neni nutna
+ for (int i=0; i< knc::NumberOfVars; i++) m_analogPanels->upsAnalogs[i]=0L;
+ for (int i=0; i< knc::NumberOfVars; i++) {
+ // otestujeme zda dane UPS podporuje tuto promenou
+ // pokud existuje vrati 1
+ switch (m_activeUpsInfo->nutVariables) {
+ case 1:
+ if (!m_activeUpsInfo->upsNet->existName(nameUpsVars1[m_activeUpsInfo->record.upsVarCode[i]]))
+ m_activeUpsInfo->record.upsVarCode[ii++] = m_activeUpsInfo->record.upsVarCode[i];
+ break;
+ case 2:
+ if (!m_activeUpsInfo->upsNet->existName(nameUpsVars2[m_activeUpsInfo->record.upsVarCode[i]]))
+ m_activeUpsInfo->record.upsVarCode[ii++] = m_activeUpsInfo->record.upsVarCode[i];
+ break;
+ }
+ }
+ for (int i=ii; i< knc::NumberOfVars; i++) m_activeUpsInfo->record.upsVarCode[i]=0;// doplnime zbytek nulami to znamena zadna promena
+
+ for (int i=0; i< knc::NumberOfVars; i++) {
+ if (m_activeUpsInfo->record.upsVarCode[i] != 0) {
+ analogMemberData=m_analogRecords->getData (m_activeUpsInfo->record.upsVarCode[i]);
+
+ m_analogPanels->scaleEnd[i]=analogMemberData.end;
+ m_analogPanels->scaleStart[i]=analogMemberData.start;
+ QColor analogFingerColor, analogScaleColor, analogFontColor;
+ if (m_settingData->customOAnalogColor) {
+ analogFingerColor = m_settingData->analogFingerColor;
+ analogScaleColor = m_settingData->analogScaleColor;
+ analogFontColor = m_settingData->analogFontColor;
+ }
+ else {
+ analogFingerColor = DEFAULT_FINGER_COLOR;
+ analogScaleColor = DEFAULT_SCALE_COLOR;
+ analogFontColor = DEFAULT_FONT_COLOR;
+ }
+
+ if (m_settingData->customFont)
+ // doesn't make background
+ m_analogPanels->upsAnalogs[i] = new KNutAnalog( m_analogArea,0L,analogMemberData.start,analogMemberData.end,analogMemberData.typeAnalog,analogMemberData.numberItem,analogMemberData.numberInItem,analogFingerColor,analogScaleColor,analogFontColor,&(m_settingData->aPanelFont),m_settingData->typeDigitalProcessing);
+ else
+ m_analogPanels->upsAnalogs[i] = new KNutAnalog( m_analogArea,0L,analogMemberData.start,analogMemberData.end,analogMemberData.typeAnalog,analogMemberData.numberItem,analogMemberData.numberInItem,analogFingerColor,analogScaleColor,analogFontColor,&(m_settingData->systemFont),m_settingData->typeDigitalProcessing);
+ //nastavime barvu mezikruzi
+
+
+ if (m_settingData->customOAnalogColor) {
+ m_analogPanels->upsAnalogs[i]->setArcColor(1,m_settingData->analogOKColor); // doesn't make background
+ m_analogPanels->upsAnalogs[i]->setArcColor(2,m_settingData->analogWarnningColor); // doesn't make background
+ m_analogPanels->upsAnalogs[i]->setArcColor(3,m_settingData->analogErrorColor); // doesn't make background
+ }
+ // po vygenerovani panelu jsou standartni barvy nastaveny automaticky
+ //nastavime mezikruzi
+ for (int j = 0; j < 5; j++ ) {
+ if (!((analogMemberData.scaleStruct[j].start == 0) && (analogMemberData.scaleStruct[j].end ==0 ))) {
+ m_analogPanels->upsAnalogs[i]->addArc (analogMemberData.scaleStruct[j].start,analogMemberData.scaleStruct[j].end,analogMemberData.scaleStruct[j].scaleColor, false); // doesn't make background
+ }
+ }
+ m_analogPanels->upsAnalogs[i]->setText(analogMemberData.nameAnalog,analogMemberData.nameUnit);
+ m_analogPanels->upsAnalogs[i]->setPalette(m_aPanelPalette);
+ m_analogPanels->upsAnalogs[i]->makeBackground(false); // makes background of analog panel
+
+ }
+ }
+
+//qDebug ( "KNutPanelMeter::activateAnalogs 1" );
+ m_analogArea->repaint(); //repaint all analog panels, background was made already
+//qDebug ("KNutPanelMeter::activateAnalogs - end");
+// analogSV->resizeContents(sizeHint().width(),sizeHint().height());
+ }
+
+
+
+void KNutPanelMeter::setSize (bool showPanels) {
+ int row =0;
+ int col=0;
+ int maxCols =0;
+ int maxRows =0;
+
+ if (!m_activeUpsInfo->netError) {
+ for (int i=0; i< knc::NumberOfVars; i++) {
+ if (m_activeUpsInfo->record.upsVarCode[i] != 0) {
+ if (maxCols < m_settingData->countCols) maxCols++;
+ maxRows = row+1;
+ // jestlize upsAnalogs =0 nejsou aktivovany
+ if (m_analogPanels->upsAnalogs[i]) {
+ m_analogPanels->upsAnalogs[i]->move (SpacePanels + (SpacePanels)+(col*(KNutAnalog::AnalogWidth+SpacePanels)),SpacePanels+(row*(KNutAnalog::AnalogWidth+SpacePanels)));
+ if (showPanels) m_analogPanels->upsAnalogs[i]->show();
+ }
+ col++;
+ if (col > (m_settingData->countCols-1) ) {col=0; row++;}; // prechod na dalsi radku
+ }
+ }
+ }
+ // musime nastavit velikost
+ m_widthArea = (KNutAnalog::AnalogWidth + SpacePanels)*maxCols +2*SpacePanels; // sirka
+ m_heightArea = (KNutAnalog::AnalogWidth + SpacePanels)*(maxRows) + SpacePanels; // minimalni velikost podle mericich panelu
+
+ m_analogArea->setMinimumSize (m_widthArea,m_heightArea);
+ adjustSize();
+ resizeContents(m_widthArea,m_heightArea);
+ repaint();
+ }
+
+void KNutPanelMeter::repaintScaleAnalogPanel (int panelNumber, float value) {
+
+ if (m_analogPanels->upsAnalogs[panelNumber] != 0L){
+ switch (m_activeUpsInfo->record.upsVarCode[panelNumber]) {
+ case knc::VarCurrent : // output.current
+ if (m_analogPanels->scaleEnd[panelNumber] < MaxCurrent) {
+ if (m_analogPanels->scaleEnd[panelNumber] < value) {
+ m_analogPanels->scaleEnd[panelNumber]=(static_cast<int>(floor((value+1)/5)))*5 +5;
+ if (m_analogPanels->scaleEnd[panelNumber] > MaxCurrent) m_analogPanels->scaleEnd[panelNumber]=MaxCurrent;
+ m_analogPanels->upsAnalogs[panelNumber]->setRange(m_analogPanels->scaleStart[panelNumber],m_analogPanels->scaleEnd[panelNumber],true);
+ }
+ }
+ break;
+ case knc::VarBattVolt : // battery.voltage
+ if (m_analogPanels->scaleEnd[panelNumber] < MaxBattVolt) {
+ if (m_analogPanels->scaleEnd[panelNumber] < value) {
+ m_analogPanels->scaleEnd[panelNumber]=(static_cast<int>(floor((value+1)/10)))*10 +10;
+ if (m_analogPanels->scaleEnd[panelNumber] > MaxBattVolt) m_analogPanels->scaleEnd[panelNumber]=MaxBattVolt;
+ m_analogPanels->upsAnalogs[panelNumber]->setRange(m_analogPanels->scaleStart[panelNumber],m_analogPanels->scaleEnd[panelNumber],true);
+ }
+ }
+ break;
+ case knc::VarBattCurrent : // battery.current
+ if (m_analogPanels->scaleEnd[panelNumber] < MaxBattCurrent) {
+ if ((m_analogPanels->scaleEnd[panelNumber] < value) || (m_analogPanels->scaleStart[panelNumber] > value)) {
+ if ((value >10) || (value <- 15)) {
+ if ((value >20) || (value < -30)) {
+ m_analogPanels->scaleEnd[panelNumber]=30;
+ m_analogPanels->scaleStart[panelNumber]=-45;
+ }
+ else {
+ m_analogPanels->scaleEnd[panelNumber]=20;
+ m_analogPanels->scaleStart[panelNumber]=-30;
+ }
+ m_analogPanels->upsAnalogs[panelNumber]->setPointer(value); // jistota pokud by nam to nekde propadlo
+ m_analogPanels->upsAnalogs[panelNumber]->hide();// schovame analogovy panel hides analog panel
+ m_analogPanels->upsAnalogs[panelNumber]->setRange (m_analogPanels->scaleStart[panelNumber],m_analogPanels->scaleEnd[panelNumber]);
+ m_analogPanels->upsAnalogs[panelNumber]->repaint(); // prekreslime , repaints panel
+ m_analogPanels->upsAnalogs[panelNumber]->show(); //zobrazime merak shows analog panel
+ }
+ }
+ }
+ break;
+ } // end switch
+ }
+ }
+
+
+
+void KNutPanelMeter::repaintAnalogPointer (int panelNumber, float value, bool run) {
+ if (m_analogPanels->upsAnalogs[panelNumber] != 0L)
+ m_analogPanels->upsAnalogs[panelNumber]->setPointer (value,run); // nastavi hodnotu rucicky
+ }
+
+
+
+void KNutPanelMeter::setAnalogBG(QPalette aPanelPalette) {
+
+ m_aPanelPalette = aPanelPalette;
+ for (int i=0; i< knc::NumberOfVars; i++) {
+ if ((m_activeUpsInfo->record.upsVarCode[i]) && (m_analogPanels->upsAnalogs[i]))
+ m_analogPanels->upsAnalogs[i]->setPalette(m_aPanelPalette);
+ }
+ }
+
+
+void KNutPanelMeter::changeAnalogPanelsDigProcessing (void) {
+
+ if (m_analogPanels == 0) return;
+
+ for (int i=0; i< knc::NumberOfVars; i++) {
+ if (m_analogPanels->upsAnalogs[i] != 0L) m_analogPanels->upsAnalogs[i]->setDigitalProcesing(m_settingData->typeDigitalProcessing,true);
+ }
+
+ }
+
+
+void KNutPanelMeter::repaintAnalogPanels (bool repaintFrequencyPanels, bool repaintVoltagePanels, bool repaintAllPanels) {
+
+KNutVarData::VarStrucDef analogMemberData;
+
+ if (m_analogPanels == 0) return;
+
+ // pregenerovani panelu slouzi pro settingMain a setting Analog
+ for (int i=0; i< knc::NumberOfVars; i++) {
+ if ((m_activeUpsInfo->record.upsVarCode[i]) && (m_analogPanels->upsAnalogs[i])) {
+ //if upsAnalogs[x] is set to zero, this upsAnalog is not used
+ // record.upsVarCode contain list of code of analog meter
+ // 0 is code for none analog meter, 1 for Input Voltage, 2 for Battery Charge,
+ if (((m_activeUpsInfo->record.upsVarCode[i] == knc::VarAcfreq) && (repaintFrequencyPanels)) ||
+ ((m_activeUpsInfo->record.upsVarCode[i] == knc::VarOutFreq) && (repaintFrequencyPanels)) ||
+ (((m_activeUpsInfo->record.upsVarCode[i] == knc::VarUtility) ||
+ (m_activeUpsInfo->record.upsVarCode[i] == knc::VarOutVolt)) && (repaintVoltagePanels))) {
+
+ analogMemberData=m_analogRecords->getData (m_activeUpsInfo->record.upsVarCode[i]); // nacteme data
+
+ m_analogPanels->upsAnalogs[i]->hide();// schovame analogovy panel
+ m_analogPanels->upsAnalogs[i]->delArc(); //zrusime segmenty
+ m_analogPanels->upsAnalogs[i]->setRange (analogMemberData.start,analogMemberData.end);
+ for (int j = 0; j < 5; j++ ) {
+ if (!((analogMemberData.scaleStruct[j].start == 0) && (analogMemberData.scaleStruct[j].end ==0 ))) {
+ m_analogPanels->upsAnalogs[i]->addArc (analogMemberData.scaleStruct[j].start,analogMemberData.scaleStruct[j].end,analogMemberData.scaleStruct[j].scaleColor, false);
+ } // end if (!
+ }// end for (int i=0
+
+ m_analogPanels->upsAnalogs[i]->makeBackground(false); // repaints analog meter
+ m_analogPanels->upsAnalogs[i]->repaintPointer(false); // repaints analog meter
+ m_analogPanels->upsAnalogs[i]->repaint(); // repaints analog meter
+ m_analogPanels->upsAnalogs[i]->show(); // shows analog meter
+ } // end if (((activeUpsInfo
+ if (repaintAllPanels) {
+ if (m_settingData->customOAnalogColor) {
+ m_analogPanels->upsAnalogs[i]->setPointerColor(m_settingData->analogFingerColor);
+ m_analogPanels->upsAnalogs[i]->setArcColor(1,m_settingData->analogOKColor);
+ m_analogPanels->upsAnalogs[i]->setArcColor(2,m_settingData->analogWarnningColor);
+ m_analogPanels->upsAnalogs[i]->setArcColor(3,m_settingData->analogErrorColor);
+ m_analogPanels->upsAnalogs[i]->setScaleColor(m_settingData->analogScaleColor);
+ m_analogPanels->upsAnalogs[i]->setFontColor(m_settingData->analogFontColor);
+ }
+ else {
+ m_analogPanels->upsAnalogs[i]->setPointerColor (DEFAULT_FINGER_COLOR);
+ m_analogPanels->upsAnalogs[i]->setDefaultArcColor();
+ m_analogPanels->upsAnalogs[i]->setScaleColor (DEFAULT_SCALE_COLOR);
+ m_analogPanels->upsAnalogs[i]->setFontColor (DEFAULT_FONT_COLOR);
+ }
+ m_analogPanels->upsAnalogs[i]->repaintAll();
+ }
+ }
+ } // end for
+ }
+
+void KNutPanelMeter::zeroingPanels (void) {
+ if (m_analogPanels) {
+ for (int i=0; i< knc::NumberOfVars; i++) {
+ if ((m_analogPanels->upsAnalogs[i] != 0L) && (m_activeUpsInfo->record.upsVarCode[i] != 0)) // jistota pokud by nam to nekde propadlo
+ m_analogPanels->upsAnalogs[i]->setPointer (0); // nastavi hodnotu rucicky
+ }
+ }
+ }
+
+
+
+QSize KNutPanelMeter::sizeHint (void){
+
+ return QSize(m_widthArea,m_heightArea);
+ }
+
+
+void KNutPanelMeter::slotSetPanelsFont(QFont newFont) {
+
+ for (int i=0; i< knc::NumberOfVars; i++) {
+ if ((m_activeUpsInfo->record.upsVarCode[i]) && (m_analogPanels->upsAnalogs[i])) {
+ m_analogPanels->upsAnalogs[i]->slotSetAllFont(newFont);
+ // je nutno prekresli i rucicku
+ }
+ }
+ }
+
+#include "knutpanelmeter.moc"
diff --git a/src/knutpanelmeter.h b/src/knutpanelmeter.h
new file mode 100644
index 0000000..3bc8d47
--- /dev/null
+++ b/src/knutpanelmeter.h
@@ -0,0 +1,210 @@
+/***************************************************************************
+ knutpanelmeter.h - description
+ -------------------
+ begin : Út b?e 16 2004
+ copyright : (C) 2004 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTPANELMETER_H
+#define KNUTPANELMETER_H
+
+#include "knutanalog.h"
+#include "knutvardata.h"
+
+
+//#include <qwidget.h>
+#include <qscrollview.h>
+
+
+class QLabel;
+class QFont;
+
+/**
+ *@author Daniel Prynych
+ */
+class KNutPanelMeter : public QScrollView {
+ Q_OBJECT
+public:
+
+/**
+ * Konstruktor
+ *
+ * Param taPanelPalette je paleta pozadi subpanelu MERAKU !!!
+ * @param activeUpsInfo ukazatel na data o aktivni UPS
+ * @param settingData ukazatel na zakladni data programu (barvy pozadi, mezikruzi, rucicky ... ,fonty atd )
+ * @param analogRecords ukazatel na tridu ktera pracuje s daty o upsekach
+ *
+ * @since 0.2
+ **/
+ KNutPanelMeter(QPalette aPanelPalette, KNutVarData::upsInfoDef* activeUpsInfo, KNutVarData::SettingDataDef* settingData, KNutVarData* analogRecords, QWidget *parent=0, const char *name=0);
+
+/**
+ * Destruktor
+ *
+ * @since 0.1
+ **/
+ ~KNutPanelMeter();
+
+/**
+ * Zrusi analogove panely vcetne uvoneni pameti.
+ *
+ * @since 0.1
+ **/
+ void deActivateAnalogs (void);
+
+
+/**
+ * Vytvori a inicializuje analogove panely.
+ *
+ * @since 0.1
+ **/
+ void activateAnalogs (void);
+
+/**
+ * Rozmisti analogove panely po hlavnim panelu a spocte jeho rozmery.
+ *
+ * @param showPanels je true jsou rozsviceny (show) subpanely
+ * @since 0.2
+ **/
+ void setSize (bool showPanels = false);
+
+
+/**
+ * Prekresli zmenu rozsahu pro dany analogovy panel (jenom jeden)
+ * Pokud panel nepodporuje zmeny rozsahu neprovede nic.
+ * Zmenu rozsahu podporuji nasledujici panely: Current,BattVolt,BattCurrent
+ *
+ * @param panelNumber je cislo analogoveho panelu.
+ * @param value je hodnota na kterou je panel nastaven.
+ *
+ * @since 0.1
+ **/
+ void repaintScaleAnalogPanel (int panelNumber, float value);
+
+/**
+ * Paints pointer for selected analog panel
+ * Prekresli rucicku pro vybrany analogovy panel.
+ *
+ * @param panelNumber is number of analog panel.
+ * @param value is value of settimg amalog panel.
+ * @param run = TRUE makes immediately repaint of panel
+ * @param panelNumber je cislo analogoveho panelu.
+ * @param value je hodnota na kterou je panel nastaven.
+ * @param run = TRUE provede okamzite prekresleni
+ *
+ * @since 0.2
+ **/
+ void repaintAnalogPointer (int panelNumber, float value, bool run = true);
+
+
+/**
+ * Repaints analog panels
+ * Repainting range of panel for frequency and voltage, based on current setting.
+ * Prekresli a prebarvi analogove panely.
+ * Prekresuje rozsah panelu pro frekvenci a nepeti na zaklade soucasneho nastaveni.
+ *
+ * @param repaintFrequencyPanels urcuje ze ma prekreslit panely ktere zobrazuji vstupni frequency.
+ * @param repaintVoltagePanels urcuje ze ma prekreslit panely ktere zobrazuji vstupni a vystupni napeti.
+ * @param repaintAllPanels urcuje ze ma prebarvit vsechny prvky panelu.
+ *
+ * @since 0.1
+ **/
+ void repaintAnalogPanels (bool repaintFrequencyPanels, bool repaintVoltagePanels, bool repaintAllPanels);
+
+
+
+
+
+
+/**
+ * Changes type of digital processing of pointer and repaints it.
+ * Zmeni zpusob digitalniho zpracovani rucucky a prekresli ji
+ *
+ * @since 0.1
+ **/
+ void changeAnalogPanelsDigProcessing (void);
+
+
+/**
+ * Sets value of panels to zero
+ * Nastavi hodnotu vsech panelu na nulu
+ *
+ * @since 0.1
+ **/
+ void zeroingPanels (void);
+
+/**
+ * Repaints backgroud of analog panels
+ * Prebarvi pozadi analogovych panelu.
+ *
+ * @param taPanelPalette je hodnota nove palety pro pozadi
+ *
+ * @since 0.1
+ **/
+ void setAnalogBG(QPalette aPanelPalette);
+
+
+
+/**
+ * Vraci soucasnou velikost panelu.
+ *
+ * @since 0.1
+ **/
+ virtual QSize sizeHint (void);
+
+public slots:
+
+ /**
+ * Sets new font for all panels
+ * Nastavy novy font ve vsech panelech.
+ *
+ * @since 0.1
+ **/
+ void slotSetPanelsFont(QFont newFont);
+
+
+private:
+/************ private const *****************/
+
+ static const int SpacePanels = 2; //vzdalenost mezi meraky, length between panels
+
+ static const int MaxBattVolt = 350; // max battery.voltage
+ static const int MaxCurrent = 50; // max output.current
+ static const int MaxBattCurrent = 50; // max battery.current
+/************ private struct ************************/
+
+ struct analogPanelRecordsDef {
+ int scaleEnd[knc::NumberOfVars];
+ int scaleStart[knc::NumberOfVars];
+ KNutAnalog* upsAnalogs[knc::NumberOfVars];
+ };
+
+
+/*********** private vars *******************/
+
+ QLabel* m_analogArea;
+
+ analogPanelRecordsDef* m_analogPanels;
+
+ KNutVarData::upsInfoDef* m_activeUpsInfo; // values for selected ups -- hodnoty pro vybrane ups
+ KNutVarData::SettingDataDef* m_settingData; // v teto strukture jsou ulozeny promene ktere nastavuji konfiguraci
+
+ KNutVarData* m_analogRecords;
+
+ QPalette m_aPanelPalette;
+
+ int m_widthArea;
+ int m_heightArea;
+};
+
+#endif
diff --git a/src/knutprefdlg.cpp b/src/knutprefdlg.cpp
new file mode 100644
index 0000000..68ce4ce
--- /dev/null
+++ b/src/knutprefdlg.cpp
@@ -0,0 +1,979 @@
+/***************************************************************************
+ knutprefdlg.cpp - description
+ -------------------
+ begin : Tue Aug 21 2001
+ copyright : (C) 2001 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#include "knutprefdlg.h"
+#include "knutvardata.h"
+#include "knutfrontpanel.h"
+#include "knutdock.h"
+
+#include <kiconloader.h>
+
+#include <qlayout.h>
+#include <qgroupbox.h>
+#include <qbuttongroup.h>
+#include <qradiobutton.h>
+#include <qfont.h>
+#include <qlabel.h>
+#include <qcheckbox.h>
+#include <qspinbox.h>
+
+
+#include <stdio.h>
+//#include <iostream>
+
+#define MAIN_PANEL_FONT 0
+#define ANALOG_PANEL_FONT 1
+
+
+
+KNutPrefDlg::KNutPrefDlg(KNutUpsData* const upsData, KNutVarData* const analogData, KNutVarData::SettingDataDef* const settingData,
+ const QString upsName, QWidget* parent, const char* name, const bool modal)
+ :KDialogBase(IconList, i18n("Preferences"),Help|Default|Apply|Ok|Cancel,Ok, parent, name, modal, true),
+ m_activeUpsName (upsName), m_myUpsData(upsData), m_myAnalogData(analogData), m_settingData(settingData) {
+
+ setName( "UpsMemberDlg" );
+
+ m_checked = false; // no change of definition of UPS // neni zadna zmena na definici UPS
+ m_checkedActiveUps = false; // change of active UPS hasn't been made // neni provedena zmena aktivni UPS
+
+ initSetting();
+ initUps();
+ initPanel();
+ initFonts();
+ initAnalog();
+ initDock(); // from 0.8 version
+ setMinimumSize (450, 300);
+ }
+
+
+KNutPrefDlg::~KNutPrefDlg(){
+ delete m_listBox2;
+ }
+
+
+
+
+/*********************************************************************************************/
+/* */
+/* PRIVATE SLOTS */
+/* */
+/*********************************************************************************************/
+
+
+void KNutPrefDlg::slotSetPictureKI (bool on) {
+if (!on) {
+ m_checkBoxCbi->setEnabled(true);
+ m_iconDockLabel->setEnabled(true);
+ m_BGIButton->setEnabled(m_checkBoxCbi->isChecked());
+ m_dockBackgroundColorLabel->setEnabled(m_checkBoxCbi->isChecked());
+
+ }
+else {
+ m_checkBoxCbi->setEnabled(false);
+ m_iconDockLabel->setEnabled(false);
+ m_BGIButton->setEnabled(false);
+ m_dockBackgroundColorLabel->setEnabled(false);
+
+ }
+
+}
+
+void KNutPrefDlg::slotEnableVoltage(bool enable) { m_voltageGroup->setEnabled(!enable);}
+
+void KNutPrefDlg::slotEnableFrequency(bool enable) { m_frequencyGroup->setEnabled(!enable);}
+
+void KNutPrefDlg::slotUseCustomBColor(bool enable) {
+ m_BGButton->setEnabled(enable);
+ m_mainBackgroundColorLabel->setEnabled(enable);
+ }
+
+void KNutPrefDlg::slotUseCustomBIconColor(bool enable) {
+ m_BGIButton->setEnabled(enable);
+ m_dockBackgroundColorLabel->setEnabled(enable);
+ }
+
+
+void KNutPrefDlg::slotUseCustomBPanelColor(bool enable) {
+ m_BGPButton->setEnabled(enable);
+ m_panelBackgroundColorLabel->setEnabled(enable);
+ }
+
+void KNutPrefDlg::slotUseCustomBAnalogColor(bool enable) {
+ m_BGAButton->setEnabled(enable);
+ m_analogBackgroundColorLabel->setEnabled(enable);
+ }
+
+void KNutPrefDlg::slotUseCustomOAnalogColor(bool enable) {
+ m_AFingerButton->setEnabled(enable);
+ m_AOKButton->setEnabled(enable);
+ m_AWarnningButton->setEnabled(enable);
+ m_AErrorButton->setEnabled(enable);
+ m_AScaleButton->setEnabled(enable);
+ m_AFontButton->setEnabled(enable);
+ m_analogPointerColorLabel->setEnabled(enable);
+ m_analogOKColorLabel->setEnabled(enable);
+ m_analogWarningColorLabel->setEnabled(enable);
+ m_analogErrorColorLabel->setEnabled(enable);
+ m_analogScaleColorLabel->setEnabled(enable);
+ m_analogFontColorLabel->setEnabled(enable);
+ }
+
+
+
+void KNutPrefDlg::slotChangeSettingFont(int index) {
+ if (m_settingFont != index) {
+ // vybirame jiny font
+ if (m_settingFont == MAIN_PANEL_FONT) {
+ m_mPanelFont=m_fontWidget->font();
+ m_fontWidget->setFont(m_aPanelFont);
+ }
+ else {
+ m_aPanelFont=m_fontWidget->font();
+ m_fontWidget->setFont(m_mPanelFont);
+ }
+ m_settingFont = index;
+ }
+}
+
+
+
+void KNutPrefDlg::slotDeleteUps() {
+ if (m_listBox2->currentItem() != -1) {
+ // smazeme policko
+ int ukListBox = m_listBox2->currentItem();
+ if ( m_activeUpsName == m_listBox2->currentText() ) m_checkedActiveUps = true;
+ m_myUpsData->deleteName(ukListBox);
+ m_listBox2->removeItem(ukListBox);
+ m_checked = true;
+ // when active ups is deleted, will set checkedActiveUps
+ // pokud smazeme aktivni UPS nastavime checkedActiveUps
+ }
+ }
+
+
+void KNutPrefDlg::slotEditUps() {
+ if (m_listBox2->currentItem() != -1) {
+ KNutUpsData::upsRecordDef upsRecord;
+ // makes dialog
+ newUpsDlg = new KNutNewUpsDlg(m_myUpsData,m_myAnalogData,false);
+ // reads record
+ m_myUpsData->get(m_listBox2->currentItem(),upsRecord);
+ // sets parameters for edit / nastavime parametry pro edit
+ newUpsDlg->putData(upsRecord);
+ int result = newUpsDlg->exec();
+ if (result == Accepted) {
+ // adds into list after OK will be clicked
+ // reads data from form
+ upsRecord = newUpsDlg->getData();
+ // corrects data in list
+ m_myUpsData->put(m_listBox2->currentItem(),upsRecord);
+ // corrects data in window
+ m_listBox2->changeItem(upsRecord.name,m_listBox2->currentItem());
+ m_checked = true;
+ // if active UPS is changed, will set checkedActiveUps
+ // pokud zmenime aktivni UPS nastavime checkedActiveUps
+ if ( m_activeUpsName == m_listBox2->currentText() ) m_checkedActiveUps = true;
+ }
+ delete newUpsDlg;
+ }
+ }
+
+
+void KNutPrefDlg::slotNewUps () {
+ KNutUpsData::upsRecordDef upsRecord;
+ // Zalozime novou UPS
+ // add new UPS
+ newUpsDlg = new KNutNewUpsDlg(m_myUpsData,m_myAnalogData);
+ int result = newUpsDlg->exec();
+ if (result == Accepted) {
+ // adds into list, when OK is pressed
+ //reads data from form
+ upsRecord = newUpsDlg->getData();
+ //pridame data do zaznamu
+ //adds data to record
+ m_myUpsData->add(upsRecord);
+ //add data to window
+ // pridame data do okenka
+ m_listBox2->insertItem(upsRecord.name);
+ // pokud pridame prvni prekreslime hlavni okno
+ // when adds the first sameone, will repaint window
+ m_checked = true;
+ if (m_myUpsData->getCount() ==1 ) m_checkedActiveUps = true;
+ }
+ delete newUpsDlg;
+ }
+
+
+void KNutPrefDlg::slotOk() {
+ slotApply ();
+ accept();
+ }
+
+void KNutPrefDlg::slotApply() {
+// budeme emitovat signal podle toho co se deje
+// will emit signal about situation
+ unsigned int changeSetting = 0;
+
+ // MainPage
+ if (m_settingData->countCols != m_numberOfColumns->value()) {
+ changeSetting += ChangeCountCols; // nastavime pocet sloupcu
+ m_settingData->countCols = m_numberOfColumns->value(); // nastavime pocet sloupcu
+ }
+
+ if (m_settingData->customBColor != m_checkBoxCbc->isChecked()) {
+ m_settingData->customBColor = m_checkBoxCbc->isChecked();
+ changeSetting += ChangeCustomBColor;
+ }
+
+ if (m_settingData->mainBackgroundColor != m_BGButton->color()) {
+ changeSetting += ChangeMBColor;
+ m_settingData->mainBackgroundColor = m_BGButton->color(); // nastavime barvu pozadi
+ }
+
+ // ovlivnuje jen ukonceni programu, neurcujeme type ChangeSetting
+ if (m_settingData->areYouSure != m_checkBoxAys->isChecked()) {
+ m_settingData->areYouSure = m_checkBoxAys->isChecked();
+ changeSetting = changeSetting | ChangeSomeThing;
+ }
+
+ //for next start only
+ if (m_comboBoxMainWindow->currentItem() != (int)m_settingData->useMainWindow) {
+ m_settingData->useMainWindow = (KNutVarData::mainWindowStartVariant)m_comboBoxMainWindow->currentItem();
+ changeSetting = changeSetting | ChangeSomeThing;
+ }
+
+// if (m_prefData->useMainWindow != m_checkBoxMW->isChecked()) {
+// m_prefData->useMainWindow = m_checkBoxMW->isChecked();
+// changeSetting = changeSetting | ChangeSomeThing;
+// }
+ //for next start only
+ if (m_settingData->useMessageWindow != m_checkBoxMesW->isChecked()) {
+ m_settingData->useMessageWindow = m_checkBoxMesW->isChecked();
+ changeSetting = changeSetting | ChangeSomeThing;
+ }
+
+ //for next start only
+ if (m_settingData->useMessageWindow != m_checkBoxMesW->isChecked()) {
+ m_settingData->useMessageWindow = m_checkBoxMesW->isChecked();
+ changeSetting = changeSetting | ChangeSomeThing;
+ }
+
+
+ int newInputVoltage, newInputFrequency;
+ if ( m_vRadioButton1->isChecked()) newInputVoltage = 230; else newInputVoltage = 120;
+ if ( m_fRadioButton1->isChecked()) newInputFrequency = 50; else newInputFrequency = 60;
+
+ if (m_settingData->inputVoltage != newInputVoltage) {
+ m_settingData->inputVoltage = newInputVoltage;
+ changeSetting += ChangeVoltage;
+ }
+
+ if (m_settingData->inputFrequency != newInputFrequency) {
+ m_settingData->inputFrequency = newInputFrequency;
+ changeSetting += ChangeFrequency;
+ }
+
+ if (m_settingData->lowHighXfer != m_xfer->isChecked()) changeSetting += ChangeXFer;
+ m_settingData->lowHighXfer = m_xfer->isChecked();
+
+ //Ups page
+ if ( m_checkedActiveUps ) { // zmena aktivni UPS
+ //change of active UPS or add the first UPS, because the first UPS is active always
+ changeSetting += ChangeUpsSetting;
+ }
+ else {
+ if (m_checked) changeSetting += ChangeUpsCount;
+ }
+ // panel Page
+ unsigned int prefPanelFlags = 3;
+ if (m_checkBoxOver->isChecked()) prefPanelFlags += KNutFrontPanel::PBOver;
+ if (m_checkBoxBL->isChecked()) prefPanelFlags += KNutFrontPanel::PBBattLow;
+ if (m_checkBoxRB->isChecked()) prefPanelFlags += KNutFrontPanel::PBRepBatt;
+ if (m_checkBoxCal->isChecked()) prefPanelFlags += KNutFrontPanel::PBCal;
+ if (m_checkBoxMFRM->isChecked()) prefPanelFlags += KNutFrontPanel::PBMFRMod;
+ if (m_checkBoxMFR->isChecked()) prefPanelFlags += KNutFrontPanel::PBMFR;
+ if (m_checkBoxModel->isChecked()) prefPanelFlags += KNutFrontPanel::PBModel;
+ if (m_checkBoxSerial->isChecked()) prefPanelFlags += KNutFrontPanel::PBSerial;
+ if (m_checkBoxFirm->isChecked()) prefPanelFlags += KNutFrontPanel::PBFirm;
+ if (m_checkBoxRun->isChecked()) prefPanelFlags += KNutFrontPanel::PBRun;
+
+ if (m_settingData->panelFlags != prefPanelFlags) {
+ m_settingData->panelFlags = prefPanelFlags;
+ changeSetting += ChangeMainPanelSetting;
+ }
+
+ if (m_settingData->customBPanelColor != m_checkBoxCbpc->isChecked()) {
+ m_settingData->customBPanelColor = m_checkBoxCbpc->isChecked();
+ changeSetting += ChangeCustomMPanelBColor;
+ }
+
+ if (m_settingData->mPanelBackgroundColor != m_BGPButton->color()) {
+ changeSetting += ChangeMPBColor;
+ m_settingData->mPanelBackgroundColor = m_BGPButton->color(); // sets color of background
+ }
+
+
+ // font Page:
+ unsigned int changeFonts;
+ changeFonts =0;
+
+ if (m_settingFont == MAIN_PANEL_FONT)
+ m_mPanelFont=m_fontWidget->font();
+ else
+ m_aPanelFont=m_fontWidget->font();
+
+ if ( m_customFont->isChecked() != m_settingData->customFont) {
+ // zmena typy fontu systemove <-> uzivatelske
+ m_settingData->customFont = m_customFont->isChecked();
+ if (m_settingData->customFont) {
+ // prejdeme na uzivatelske fonty
+ m_settingData->aPanelFont = m_aPanelFont;
+ m_settingData->mPanelFont = m_mPanelFont;
+ changeSetting += ChangeAnalogFont;
+ changeSetting += ChangePanelFont;
+ }
+ else {
+ // pouzijeme systemove fonty
+ changeSetting += ChangeAnalogFont;
+ changeSetting += ChangePanelFont;
+ }
+ }
+ else {
+ if ( m_settingData->customFont ) {
+ // otestujeme zda se zmenili nase fonty
+ if (m_aPanelFont != m_settingData->aPanelFont) {
+ m_settingData->aPanelFont = m_aPanelFont;
+ changeSetting += ChangeAnalogFont;
+ }
+ if (m_mPanelFont != m_settingData->mPanelFont) {
+ m_settingData->mPanelFont = m_mPanelFont;
+ changeSetting += ChangePanelFont;
+ }
+ }
+ }
+ // analog page
+
+ if (m_settingData->customBAnalogColor != m_checkBoxCbac->isChecked()) {
+ m_settingData->customBAnalogColor = m_checkBoxCbac->isChecked();
+ changeSetting += ChangeCustomAPanelBColor;
+ }
+
+ if (m_settingData->aPanelBackgroundColor != m_BGAButton->color()) {
+ changeSetting += ChangeAPBColor;
+ m_settingData->aPanelBackgroundColor = m_BGAButton->color(); // nastavime barvu pozadi
+ }
+
+ if (m_settingData->customOAnalogColor != m_checkBoxCoac->isChecked()) {
+ m_settingData->customOAnalogColor = m_checkBoxCoac->isChecked();
+ changeSetting += ChangeCustomAPanelOColor;
+ }
+
+ if ((m_settingData->analogFingerColor != m_AFingerButton->color()) ||
+ (m_settingData->analogOKColor != m_AOKButton->color()) ||
+ (m_settingData->analogWarnningColor != m_AWarnningButton->color()) ||
+ (m_settingData->analogErrorColor != m_AErrorButton->color()) ||
+ (m_settingData->analogScaleColor != m_AScaleButton->color()) ||
+ (m_settingData->analogFontColor != m_AFontButton->color())) {
+ changeSetting += ChangeAPOColor;
+ m_settingData->analogFingerColor = m_AFingerButton->color(); // sets color of pointers-- nastavime barvu rucicky
+ m_settingData->analogOKColor = m_AOKButton->color(); // sets color of OK -- nastavime barvu ok
+ m_settingData->analogWarnningColor = m_AWarnningButton->color(); // nastavime barvu varovano
+ m_settingData->analogErrorColor = m_AErrorButton->color(); // nastavime barvu chyby
+ m_settingData->analogScaleColor = m_AScaleButton->color(); // nastavime barvu stupnice
+ m_settingData->analogFontColor = m_AFontButton->color(); // nastavime barvu textu
+ }
+
+ if (m_settingData->typeDigitalProcessing != m_digitalProcesingOfPointers->currentItem()) {
+ m_settingData->typeDigitalProcessing = m_digitalProcesingOfPointers->currentItem();
+ changeSetting += ChangeTypeOfDigProcessing;
+ }
+
+ // Kicker Icon page
+
+ int stateKIcon;
+ if (m_iconRadioButton1->isChecked()) stateKIcon = KNutDock::pictureKI;
+ else stateKIcon = KNutDock::generalKI;
+ if (m_settingData->typeOfKIcon != stateKIcon) {
+ if (m_iconRadioButton1->isChecked()) m_settingData->typeOfKIcon = KNutDock::pictureKI;
+ if (m_iconRadioButton2->isChecked()) m_settingData->typeOfKIcon = KNutDock::generalKI;
+ changeSetting += ChangeTypeOfKIcon;
+ }
+
+ if (m_settingData->customKIconColor != m_checkBoxCbi->isChecked()) {
+ m_settingData->customKIconColor = m_checkBoxCbi->isChecked();
+ changeSetting += ChangeCustomKIconColor;
+ }
+
+ if (m_settingData->kIconBackgroundColor != m_BGIButton->color()) {
+ changeSetting += ChangeKIconBColor;
+ m_settingData->kIconBackgroundColor = m_BGIButton->color(); // nastavime barvu pozadi
+ }
+
+ unsigned int prefToolTipFlags = 0;
+ if (m_checkBoxTTMFR->isChecked()) prefToolTipFlags += KNutDock::TTMFR;
+ if (m_checkBoxTTModel->isChecked()) prefToolTipFlags += KNutDock::TTModel;
+ if (m_checkBoxTTSerial->isChecked()) prefToolTipFlags += KNutDock::TTSerial;
+ if (m_checkBoxTTFirm->isChecked()) prefToolTipFlags += KNutDock::TTFirm;
+ if (m_checkBoxTTRun->isChecked()) prefToolTipFlags += KNutDock::TTRun;
+ if (m_checkBoxTTCharge->isChecked()) prefToolTipFlags += KNutDock::TTCharge;
+ if (m_checkBoxTTLoad->isChecked()) prefToolTipFlags += KNutDock::TTLoad;
+
+ if (m_settingData->toolTipFlags != prefToolTipFlags) {
+ m_settingData->toolTipFlags = prefToolTipFlags;
+ changeSetting += ChangeToolTip;
+ }
+
+ if (changeSetting) emit signalChangeConfig( changeSetting );
+ }
+
+
+void KNutPrefDlg::slotDefault() {
+ switch (activePageIndex()) {
+ case mainSettingPage:
+ m_numberOfColumns->setValue( knc::DefaultCountCols );
+ m_BGButton->setColor(DEFAULT_BG_COLOR);
+ m_checkBoxAys->setChecked ( false );
+ m_checkBoxMesW->setChecked ( false );
+ m_comboBoxMainWindow->setCurrentItem(KNutVarData::mw_no); // sets NO
+ m_vRadioButton1->setChecked( true );
+ m_fRadioButton1->setChecked( true );
+ m_xfer->setChecked( false );
+ break;
+ case panelSettingPage:
+ m_checkBoxOver->setChecked(KNutFrontPanel::DefaultPanelFlags & KNutFrontPanel::PBOver);
+ m_checkBoxBL->setChecked(KNutFrontPanel::DefaultPanelFlags & KNutFrontPanel::PBBattLow);
+ m_checkBoxRB->setChecked(KNutFrontPanel::DefaultPanelFlags & KNutFrontPanel::PBRepBatt);
+ m_checkBoxCal->setChecked(KNutFrontPanel::DefaultPanelFlags & KNutFrontPanel::PBCal);
+ m_checkBoxMFRM->setChecked(KNutFrontPanel::DefaultPanelFlags & KNutFrontPanel::PBMFRMod);
+ m_checkBoxMFR->setChecked(KNutFrontPanel::DefaultPanelFlags & KNutFrontPanel::PBMFR);
+ m_checkBoxModel->setChecked(KNutFrontPanel::DefaultPanelFlags & KNutFrontPanel::PBModel);
+ m_checkBoxSerial->setChecked(KNutFrontPanel::DefaultPanelFlags & KNutFrontPanel::PBSerial);
+ m_checkBoxFirm->setChecked(KNutFrontPanel::DefaultPanelFlags & KNutFrontPanel::PBFirm);
+ m_checkBoxCbpc->setChecked(false);
+ m_BGAButton->setColor(DEFAULT_BG_COLOR);
+ break;
+ case fontSettingPage:
+ m_customFont->setChecked(false);
+ break;
+ case analogSettingPage:
+ m_checkBoxCbac->setChecked(false);
+ m_BGAButton->setColor(DEFAULT_BG_COLOR);
+ m_checkBoxCoac->setChecked(false);
+ m_AFingerButton->setColor(DEFAULT_FINGER_COLOR);
+ m_AOKButton->setColor(DEFAULT_OK_COLOR);
+ m_AWarnningButton->setColor(DEFAULT_WARNNING_COLOR);
+ m_AErrorButton->setColor(DEFAULT_ERROR_COLOR);
+ m_AScaleButton->setColor(DEFAULT_SCALE_COLOR);
+ m_AFontButton->setColor(DEFAULT_FONT_COLOR);
+ break;
+ case kickerSettingPage:
+ m_checkBoxCbi->setChecked(false);
+ m_BGAButton->setColor(DEFAULT_KICON_COLOR);
+ m_checkBoxTTMFR->setChecked(KNutDock::DefaultToolTipFlags & KNutDock::TTMFR);
+ m_checkBoxTTModel->setChecked(KNutDock::DefaultToolTipFlags & KNutDock::TTModel);
+ m_checkBoxTTSerial->setChecked(KNutDock::DefaultToolTipFlags & KNutDock::TTSerial);
+ m_checkBoxTTFirm->setChecked(KNutDock::DefaultToolTipFlags & KNutDock::TTFirm);
+ m_checkBoxTTRun->setChecked(KNutDock::DefaultToolTipFlags & KNutDock::TTRun);
+ m_checkBoxTTCharge->setChecked(KNutDock::DefaultToolTipFlags & KNutDock::TTCharge);
+ m_checkBoxTTLoad->setChecked(KNutDock::DefaultToolTipFlags & KNutDock::TTLoad);
+ m_iconRadioButton1->setChecked( true );
+ break;
+ }
+ }
+
+/*********************************************************************************************/
+/* */
+/* PRIVATE FUNCTIONS */
+/* */
+/*********************************************************************************************/
+
+void KNutPrefDlg::initSetting () {
+ m_mSetPix = UserIcon ("knc_mset");
+
+
+ QFrame *page = addPage( i18n("Setting"),i18n("Main Setting"),m_mSetPix);
+ QVBoxLayout *setTopLayout = new QVBoxLayout( page, 10, spacingHint (), "setTopLayout" );
+
+ QGroupBox *dataBox = new QGroupBox (page ,"dataBox");
+ QGridLayout *dataLayout = new QGridLayout (dataBox,5,2,spacingHint());
+ dataBox->setFrameStyle(QFrame::NoFrame);
+ setTopLayout->addWidget(dataBox);
+
+ QButtonGroup *VFGroup = new QButtonGroup(i18n("Voltage/Frequency"),page,"VFGroup");
+ QGridLayout *setVoltFreqLayout = new QGridLayout (VFGroup, 4 , 2,spacingHint () );
+
+ m_xfer = new QCheckBox (i18n("&Use High-Low XFER"),VFGroup,"m_xfer");
+
+ QLabel *initSettingLabel1 = new QLabel(i18n("Number of columns :"),dataBox,"label1");
+ m_numberOfColumns = new QSpinBox(knc::MinCols,knc::MaxCols,1,dataBox);
+
+ QLabel *initSettingLabel2 = new QLabel(i18n("Use custom background color"),dataBox,"label2");
+ m_checkBoxCbc = new QCheckBox ("",dataBox,"checboxcbc");
+
+
+ m_mainBackgroundColorLabel = new QLabel(i18n("Color of background :"),dataBox,"label3");
+ m_BGButton = new KColorButton (dataBox);
+ m_BGButton->setColor (m_settingData->mainBackgroundColor);
+
+ QLabel *initSettingLabel4 = new QLabel(i18n("Use dialog \"Are you sure\""),dataBox,"m_areYouSureLabel");
+ m_checkBoxAys = new QCheckBox ("",dataBox,"checboxays");
+
+ QLabel *initSettingLabel5 = new QLabel(i18n("Use Main window when program is started"),dataBox,"initSettingLabel5");
+// m_checkBoxMW = new QCheckBox ("",dataBox,"checboxmv");
+
+ QLabel *initSettingLabel6 = new QLabel(i18n("Show message window, when program reports error"),dataBox,"initSettingLabel6");
+ m_checkBoxMesW = new QCheckBox ("",dataBox,"checboxer");
+ m_comboBoxMainWindow = new KComboBox (dataBox);
+ m_comboBoxMainWindow->insertItem (i18n("Yes"));
+ m_comboBoxMainWindow->insertItem (i18n("No"));
+ m_comboBoxMainWindow->insertItem (i18n("Auto"));
+
+
+
+ m_voltageGroup = new QButtonGroup(i18n("Nominal Input Voltage"),VFGroup,"voltageGroup");
+ QGridLayout *voltLayout = new QGridLayout (m_voltageGroup, 3 , 1,spacingHint () );
+
+ m_vRadioButton1 = new QRadioButton(i18n("&230 V"), m_voltageGroup, "vRadioButton1" );
+ m_vRadioButton2 = new QRadioButton(i18n("&120 V"), m_voltageGroup, "vRadioButton2" );
+
+ m_frequencyGroup = new QButtonGroup(i18n("Nominal Input Frequency"),VFGroup,"frequencyGroup");
+ QGridLayout *freqLayout = new QGridLayout (m_frequencyGroup, 3 , 1,spacingHint () );
+
+ m_fRadioButton1 = new QRadioButton(i18n("&50 Hz"), m_frequencyGroup, "fRadioButton1" );
+ m_fRadioButton2 = new QRadioButton(i18n("&60 Hz"), m_frequencyGroup, "fRadioButton2" );
+
+ dataLayout->addWidget (initSettingLabel1,0,0);
+ dataLayout->addWidget (m_numberOfColumns,0,1);
+
+ dataLayout->addWidget (initSettingLabel2,1,0);
+ dataLayout->addWidget (m_checkBoxCbc,1,1);
+
+ dataLayout->addWidget (m_mainBackgroundColorLabel,2,0);
+ dataLayout->addWidget (m_BGButton,2,1);
+
+ dataLayout->addWidget (initSettingLabel4,3,0);
+ dataLayout->addWidget (m_checkBoxAys,3,1);
+
+ dataLayout->addWidget (initSettingLabel5,4,0);
+ dataLayout->addWidget (m_comboBoxMainWindow,4,1);
+
+ dataLayout->addWidget (initSettingLabel6,5,0);
+ dataLayout->addWidget (m_checkBoxMesW,5,1);
+
+ dataLayout->setColStretch(1,5);
+
+ voltLayout->addRowSpacing (0 ,fontMetrics().lineSpacing() );
+ voltLayout->addWidget ( m_vRadioButton1,1,0 );
+ voltLayout->addWidget ( m_vRadioButton2,2,0 );
+
+ freqLayout->addRowSpacing (0 ,fontMetrics().lineSpacing() );
+ freqLayout->addWidget ( m_fRadioButton1,1,0 );
+ freqLayout->addWidget ( m_fRadioButton2,2,0 );
+
+ setTopLayout->addWidget (VFGroup,10);
+ setVoltFreqLayout->addRowSpacing (0 ,fontMetrics().lineSpacing() );
+ setVoltFreqLayout->addWidget ( m_voltageGroup,1,0 );
+ setVoltFreqLayout->addWidget ( m_frequencyGroup,1,1 );
+ setVoltFreqLayout->addWidget ( m_xfer,2,0 );
+ setVoltFreqLayout->addRowSpacing (3 ,fontMetrics().lineSpacing() );
+
+ setTopLayout->addStretch( 20 );
+
+ //sets value
+ m_numberOfColumns->setValue(m_settingData->countCols);
+ m_BGButton->setColor(m_settingData->mainBackgroundColor); // sets color of backgound
+ m_checkBoxAys->setChecked(m_settingData->areYouSure);
+ m_checkBoxMesW->setChecked(m_settingData->useMessageWindow);
+ m_comboBoxMainWindow->setCurrentItem(m_settingData->useMainWindow);
+
+ if (m_settingData->inputVoltage == 230)
+ m_vRadioButton1->setChecked( true );
+ else
+ m_vRadioButton2->setChecked( true );
+ if (m_settingData->inputFrequency == 50)
+ m_fRadioButton1->setChecked( true );
+ else
+ m_fRadioButton2->setChecked( true );
+
+ m_xfer->setChecked(m_settingData->lowHighXfer);
+ m_voltageGroup->setEnabled(!m_settingData->lowHighXfer);
+ m_frequencyGroup->setEnabled(!m_settingData->lowHighXfer);
+ connect (m_xfer,SIGNAL(toggled(bool)),this,SLOT(slotEnableVoltage(bool)));
+ connect (m_xfer,SIGNAL(toggled(bool)),this,SLOT(slotEnableFrequency(bool)));
+
+
+ m_checkBoxCbc->setChecked(m_settingData->customBColor);
+ m_BGButton->setColor(m_settingData->mainBackgroundColor);
+ m_BGButton->setEnabled(m_settingData->customBColor);
+ m_mainBackgroundColorLabel->setEnabled(m_settingData->customBColor);
+ connect (m_checkBoxCbc,SIGNAL(toggled(bool)),this,SLOT(slotUseCustomBColor(bool)));
+ }
+
+void KNutPrefDlg::initUps () {
+ m_upsesPix = UserIcon ("knc_upses");
+ QFrame *page = addPage( i18n("UPS"),i18n("UPS Setting"),m_upsesPix);
+ QHBoxLayout *upsTopLayout = new QHBoxLayout( page, 0, spacingHint (),"upsTopLayout" );
+
+ // makes box for names of UPS's / Vytvorime box pro jmena UPS-ek
+ m_listBox2 = new KListBox( page, "ListBox2" );
+ m_listBox2->setSizePolicy( QSizePolicy( (QSizePolicy::SizeType)5, (QSizePolicy::SizeType)5, m_listBox2->sizePolicy().hasHeightForWidth() ) );
+ m_listBox2->setFrameShape( QListBox::StyledPanel );
+ m_listBox2->setFrameShadow( QListBox::Sunken );
+ m_listBox2->setMinimumSize (100,100);
+
+ // sets listbox
+ for (int i=0; i < m_myUpsData->getCount (); i++) m_listBox2->insertItem (m_myUpsData->getName(i));
+ //includes listbox into horizontal layout on the first place
+ upsTopLayout->addWidget( m_listBox2, 20 );
+ // makes vertical layout and includes it in horizontal layout into the second place
+ QVBoxLayout *upsLayout = new QVBoxLayout( upsTopLayout, spacingHint (),"upsLayout" );
+
+ // vytvorime tlacitka
+ KPushButton *newButton = new KPushButton (i18n("&Add"),page);
+ KPushButton *editButton = new KPushButton (i18n("&Edit"),page);
+ KPushButton *deleteButton = new KPushButton (i18n("&Delete"),page);
+
+ // includes buttons into layout / vlozime tlacitka do layoutu
+ upsLayout->addWidget( newButton );
+ upsLayout->addWidget( editButton );
+ upsLayout->addWidget( deleteButton );
+
+ upsLayout->addStretch( 10 );
+
+ connect (newButton,SIGNAL(clicked()),this,SLOT(slotNewUps()));
+ connect (editButton,SIGNAL(clicked()),this,SLOT(slotEditUps()));
+ connect (deleteButton,SIGNAL(clicked()),this,SLOT(slotDeleteUps()));
+ connect (m_listBox2,SIGNAL(doubleClicked(QListBoxItem*, const QPoint&)),this,SLOT(slotEditUps()));
+
+ }
+
+void KNutPrefDlg::initDock () {
+
+ m_dockPix = UserIcon ("knc_dock");
+ QFrame *page = addPage( i18n("Dock bar"),i18n("Docking Setting"),m_dockPix);
+
+ QVBoxLayout *setTopLayout = new QVBoxLayout( page, 10, spacingHint (), "setTopLayout" );
+
+ QButtonGroup *typeGroup = new QButtonGroup(i18n("Type of dock's showing"),page,"typeGroup");
+ QGridLayout *typeLayout = new QGridLayout (typeGroup,2,2,spacingHint());
+ setTopLayout->addWidget(typeGroup);
+
+
+ QGroupBox *infoBox = new QGroupBox (i18n("Items of tooltip"),page ,"infoBox");
+ QGridLayout *infoLayout = new QGridLayout (infoBox,8,1,spacingHint());
+ setTopLayout->addWidget(infoBox);
+
+ QGridLayout *colorLayout = new QGridLayout (10,1,spacingHint(),"colorLayout");
+ setTopLayout->addLayout(colorLayout);
+
+
+ m_iconRadioButton1 = new QRadioButton(i18n("&Picture"), typeGroup, "iconRadioButton1" );
+ m_iconRadioButton2 = new QRadioButton(i18n("&General"), typeGroup, "iconRadioButton2" );
+
+
+ m_checkBoxTTMFR = new QCheckBox (i18n("M&anufacturer"),infoBox);
+ m_checkBoxTTMFR->setChecked((m_settingData->toolTipFlags) & KNutDock::TTMFR);
+
+ m_checkBoxTTModel = new QCheckBox (i18n("M&odel"),infoBox);
+ m_checkBoxTTModel->setChecked((m_settingData->toolTipFlags) & KNutDock::TTModel);
+
+ m_checkBoxTTSerial = new QCheckBox (i18n("&Serial"),infoBox);
+ m_checkBoxTTSerial->setChecked((m_settingData->toolTipFlags) & KNutDock::TTSerial);
+
+ m_checkBoxTTFirm = new QCheckBox (i18n("&Firm. rev."),infoBox);
+ m_checkBoxTTFirm->setChecked((m_settingData->toolTipFlags) & KNutDock::TTFirm);
+
+ m_checkBoxTTRun = new QCheckBox (i18n("&Runtime"),infoBox);
+ m_checkBoxTTRun->setChecked((m_settingData->toolTipFlags) & KNutDock::TTRun);
+
+ m_checkBoxTTCharge = new QCheckBox (i18n("&Battery Charge"),infoBox);
+ m_checkBoxTTCharge->setChecked((m_settingData->toolTipFlags) & KNutDock::TTCharge);
+
+ m_checkBoxTTLoad = new QCheckBox (i18n("&UPS Load"),infoBox);
+ m_checkBoxTTLoad->setChecked((m_settingData->toolTipFlags) & KNutDock::TTLoad);
+
+
+ m_iconDockLabel = new QLabel(i18n("Use custom icon's background color"),page,"label1");
+ m_checkBoxCbi = new QCheckBox ("",page,"checboxcbpc");
+
+ m_dockBackgroundColorLabel = new QLabel(i18n("Color of icon's background :"),page,"label12");
+ m_BGIButton = new KColorButton (page);
+
+ typeLayout->addRowSpacing (0 ,fontMetrics().lineSpacing() );
+ typeLayout->addWidget ( m_iconRadioButton1,1,0 );
+ typeLayout->addWidget ( m_iconRadioButton2,2,0 );
+
+ if (m_settingData->typeOfKIcon == KNutDock::pictureKI)
+ m_iconRadioButton1->setChecked( true );
+ if (m_settingData->typeOfKIcon == KNutDock::generalKI)
+ m_iconRadioButton2->setChecked( true );
+
+ infoLayout->addRowSpacing (0 ,fontMetrics().lineSpacing() );
+ infoLayout->addWidget ( m_checkBoxTTMFR ,1,0);
+ infoLayout->addWidget ( m_checkBoxTTModel ,2,0);
+ infoLayout->addWidget ( m_checkBoxTTSerial ,3,0);
+ infoLayout->addWidget ( m_checkBoxTTFirm ,4,0);
+ infoLayout->addWidget ( m_checkBoxTTRun ,5,0);
+ infoLayout->addWidget ( m_checkBoxTTCharge ,6,0);
+ infoLayout->addWidget ( m_checkBoxTTLoad ,7,0);
+
+ colorLayout->addWidget (m_iconDockLabel,0,0);
+ colorLayout->addWidget (m_checkBoxCbi,0,1);
+ colorLayout->addWidget (m_dockBackgroundColorLabel,1,0);
+ colorLayout->addWidget (m_BGIButton,1,1);
+
+ m_checkBoxCbi->setChecked(m_settingData->customKIconColor);
+ m_BGIButton->setColor(m_settingData->kIconBackgroundColor);
+// m_BGIButton->setEnabled(m_prefData->customKIconColor);
+// m_dockBackgroundColorLabel->setEnabled(m_prefData->customKIconColor);
+
+ if (m_iconRadioButton1->isChecked()) {
+ m_iconDockLabel->setEnabled(false);
+ m_checkBoxCbi->setEnabled(false);
+ m_BGIButton->setEnabled(false);
+ m_dockBackgroundColorLabel->setEnabled(false);
+ }
+ else {
+ m_iconDockLabel->setEnabled(true);
+ m_BGIButton->setEnabled(m_settingData->customKIconColor);
+ m_dockBackgroundColorLabel->setEnabled(m_settingData->customKIconColor);
+ }
+
+ setTopLayout->addStretch( 20 );
+
+ connect (m_checkBoxCbi,SIGNAL(toggled(bool)),this,SLOT(slotUseCustomBIconColor(bool)));
+ connect (m_iconRadioButton1,SIGNAL(toggled(bool)),this,SLOT(slotSetPictureKI(bool)));
+
+ }
+
+
+void KNutPrefDlg::initPanel () {
+
+ m_panelPix = UserIcon ("knc_panel");
+
+// QFrame *page = addPage( i18n("Panel"),i18n("Panel Setting"),DesktopIcon("panel_settings"));
+ QFrame *page = addPage( i18n("Panel"),i18n("Panel Setting"),m_panelPix);
+
+ QVBoxLayout *setTopLayout = new QVBoxLayout( page, 10, spacingHint (), "setTopLayout" );
+
+
+ QGroupBox *infoBox = new QGroupBox (page ,"infoBox");
+ QGridLayout *infoLayout = new QGridLayout (infoBox,10,1,spacingHint());
+ setTopLayout->addWidget(infoBox);
+
+ QGridLayout *colorLayout = new QGridLayout (10,1,spacingHint(),"colorLayout");
+ setTopLayout->addLayout(colorLayout);
+
+
+ // vytvorime widgety - Nazev Zatrhavaci box
+ //makes widgets - name checkbox
+ m_checkBoxOver = new QCheckBox (i18n("UPS &Overload"),infoBox);
+ m_checkBoxOver->setChecked((m_settingData->panelFlags) & KNutFrontPanel::PBOver);
+
+ m_checkBoxBL = new QCheckBox (i18n("UPS &Battery low"),infoBox);
+ m_checkBoxBL->setChecked((m_settingData->panelFlags) & KNutFrontPanel::PBBattLow);
+
+ m_checkBoxRB = new QCheckBox (i18n("R&eplace battery"),infoBox);
+ m_checkBoxRB->setChecked((m_settingData->panelFlags) & KNutFrontPanel::PBRepBatt);
+
+ m_checkBoxCal = new QCheckBox (i18n("Ups &calibration"),infoBox);
+ m_checkBoxCal->setChecked((m_settingData->panelFlags) & KNutFrontPanel::PBCal);
+
+ m_checkBoxMFRM = new QCheckBox (i18n("&Manufac. + Model"),infoBox);
+ m_checkBoxMFRM->setChecked((m_settingData->panelFlags) & KNutFrontPanel::PBMFRMod);
+
+ m_checkBoxMFR = new QCheckBox (i18n("M&anufacturer"),infoBox);
+ m_checkBoxMFR->setChecked((m_settingData->panelFlags) & KNutFrontPanel::PBMFR);
+
+ m_checkBoxModel = new QCheckBox (i18n("M&odel"),infoBox);
+ m_checkBoxModel->setChecked((m_settingData->panelFlags) & KNutFrontPanel::PBModel);
+
+ m_checkBoxSerial = new QCheckBox (i18n("&Serial"),infoBox);
+ m_checkBoxSerial->setChecked((m_settingData->panelFlags) & KNutFrontPanel::PBSerial);
+
+ m_checkBoxFirm = new QCheckBox (i18n("&Firm. rev."),infoBox);
+ m_checkBoxFirm->setChecked((m_settingData->panelFlags) & KNutFrontPanel::PBFirm);
+
+ m_checkBoxRun = new QCheckBox (i18n("&Runtime"),infoBox);
+ m_checkBoxRun->setChecked((m_settingData->panelFlags) & KNutFrontPanel::PBRun);
+
+
+ QLabel *initPanelLabel1 = new QLabel(i18n("Use custom background color"),page,"label1");
+ m_checkBoxCbpc = new QCheckBox ("",page,"checboxcbpc");
+
+ m_panelBackgroundColorLabel = new QLabel(i18n("Color of background :"),page,"m_panelBackgroundColorLabel");
+ m_BGPButton = new KColorButton (page);
+
+ // includes widgets
+ infoLayout->addWidget ( m_checkBoxOver, 0,0);
+ infoLayout->addWidget ( m_checkBoxBL ,1,0);
+ infoLayout->addWidget ( m_checkBoxRB ,2,0);
+ infoLayout->addWidget ( m_checkBoxCal ,3,0);
+ infoLayout->addWidget ( m_checkBoxMFRM ,4,0);
+ infoLayout->addWidget ( m_checkBoxMFR ,5,0);
+ infoLayout->addWidget ( m_checkBoxModel ,6,0);
+ infoLayout->addWidget ( m_checkBoxSerial ,7,0);
+ infoLayout->addWidget ( m_checkBoxFirm ,8,0);
+ infoLayout->addWidget ( m_checkBoxRun ,9,0);
+
+ colorLayout->addWidget (initPanelLabel1,0,0);
+ colorLayout->addWidget (m_checkBoxCbpc,0,1);
+ colorLayout->addWidget (m_panelBackgroundColorLabel,1,0);
+ colorLayout->addWidget (m_BGPButton,1,1);
+
+ setTopLayout->addStretch( 20 );
+
+ m_checkBoxCbpc->setChecked(m_settingData->customBPanelColor);
+ m_BGPButton->setColor(m_settingData->mPanelBackgroundColor);
+ m_BGPButton->setEnabled(m_settingData->customBPanelColor);
+ m_panelBackgroundColorLabel->setEnabled(m_settingData->customBPanelColor);
+ m_panelBackgroundColorLabel->setEnabled(m_settingData->customBPanelColor);
+ connect (m_checkBoxCbpc,SIGNAL(toggled(bool)),this,SLOT(slotUseCustomBPanelColor(bool)));
+
+ }
+
+
+void KNutPrefDlg::initFonts () {
+ QFrame *page = addPage( i18n("Fonts"),i18n("Setting Fonts"),DesktopIcon("fonts"));
+
+ QVBoxLayout *setTopLayout = new QVBoxLayout( page, 10, spacingHint (), "setTopLayout" );
+ QHBoxLayout *setSysLayout = new QHBoxLayout( setTopLayout, spacingHint (), "setTypeLayout" );
+ QHBoxLayout *setTypeLayout = new QHBoxLayout( setTopLayout, spacingHint (), "setTypeLayout" );
+ QHBoxLayout *setFontLayout = new QHBoxLayout( setTopLayout, spacingHint (), "setFontLayout" );
+
+ m_customFont = new QCheckBox (i18n("&Use custom font"),page);
+ setSysLayout->addWidget ( m_customFont ,10);
+ setSysLayout->addStretch( 10 );
+
+ KComboBox *panelFonts = new KComboBox(page);
+ panelFonts->insertItem (i18n("Main panel"));
+ panelFonts->insertItem (i18n("Analog panels"));
+ setTypeLayout->addWidget ( panelFonts ,0);
+
+
+
+ m_fontWidget = new KFontChooser(page,"Font",false);
+ setFontLayout->addWidget (m_fontWidget ,0);
+
+ setTopLayout->addStretch( 20 );
+
+// init items
+ m_customFont->setChecked(m_settingData->customFont);
+ m_aPanelFont = m_settingData->aPanelFont;
+ m_mPanelFont = m_settingData->mPanelFont;
+ m_settingFont = MAIN_PANEL_FONT; // sets font for Main Panel / nastavujeme font pro Main Panel
+ m_fontWidget->setFont(m_mPanelFont);
+ m_fontWidget->setEnabled(m_settingData->customFont);
+ connect (panelFonts,SIGNAL(activated(int)),this,SLOT(slotChangeSettingFont(int)));
+ connect (m_customFont,SIGNAL(toggled(bool)),m_fontWidget,SLOT(setEnabled(bool)));
+ }
+
+void KNutPrefDlg::initAnalog () {
+ m_analogPix = UserIcon ("knc_analog");
+ QFrame *page = addPage( i18n("Analog"),i18n("Setting Analog panel"),m_analogPix);
+// QFrame *page = addPage( i18n("Analog"),i18n("Setting Analog panel"),DesktopIcon("ksysguard"));
+ QVBoxLayout *setTopLayout = new QVBoxLayout( page, 10, spacingHint (), "setTopLayout" );
+ QGridLayout *setColorLayout = new QGridLayout( 9,2, spacingHint(),"setColorLayout");
+ setTopLayout->addLayout(setColorLayout);
+ setTopLayout->addStretch( 20 );
+
+ QLabel *initAnalogLabel1 = new QLabel(i18n("Use custom background color"),page,"initAnalogLabel1");
+ m_checkBoxCbac = new QCheckBox ("",page,"checboxcbac");
+ m_analogBackgroundColorLabel = new QLabel(i18n("Color of background :"),page,"m_backgroundColorLabel");
+ m_BGAButton = new KColorButton (page);
+ QLabel *initAnalogLabel12 = new QLabel(i18n("Use custom other colors"),page,"label12");
+ m_checkBoxCoac = new QCheckBox ("",page,"checboxcoac");
+ m_analogPointerColorLabel = new QLabel(i18n("Color of pointer :"),page,"m_analogPointerColorLabel");
+ m_AFingerButton = new KColorButton (page);
+ m_analogOKColorLabel = new QLabel(i18n("Color of OK range :"),page,"label7");
+ m_AOKButton = new KColorButton (page);
+ m_analogWarningColorLabel = new QLabel(i18n("Color of warning range :"),page,"label8");
+ m_AWarnningButton = new KColorButton (page);
+ m_analogErrorColorLabel= new QLabel(i18n("Color of error range :"),page,"label9");
+ m_AErrorButton = new KColorButton (page);
+ m_analogScaleColorLabel = new QLabel(i18n("Color of scale :"),page,"label10");
+ m_AScaleButton = new KColorButton (page);
+ m_analogFontColorLabel = new QLabel(i18n("Color of font :"),page,"label11");
+ m_AFontButton = new KColorButton (page);
+
+ m_digitalProcessingLabel = new QLabel(i18n("Digital processing of pointers :"),page,"label12");
+ m_digitalProcesingOfPointers = new KComboBox (page);
+
+
+ setColorLayout->addWidget ( initAnalogLabel1, 0,0);
+ setColorLayout->addWidget ( m_checkBoxCbac ,0,1);
+ setColorLayout->addWidget ( m_analogBackgroundColorLabel, 1,0);
+ setColorLayout->addWidget ( m_BGAButton ,1,1);
+ setColorLayout->addWidget ( initAnalogLabel12, 2,0);
+ setColorLayout->addWidget ( m_checkBoxCoac ,2,1);
+ setColorLayout->addWidget ( m_analogPointerColorLabel, 3,0);
+ setColorLayout->addWidget ( m_AFingerButton ,3,1);
+ setColorLayout->addWidget ( m_analogOKColorLabel, 4,0);
+ setColorLayout->addWidget ( m_AOKButton ,4,1);
+ setColorLayout->addWidget ( m_analogWarningColorLabel, 5,0);
+ setColorLayout->addWidget ( m_AWarnningButton ,5,1);
+ setColorLayout->addWidget ( m_analogErrorColorLabel, 6,0);
+ setColorLayout->addWidget ( m_AErrorButton ,6,1);
+ setColorLayout->addWidget ( m_analogScaleColorLabel, 7,0);
+ setColorLayout->addWidget ( m_AScaleButton ,7,1);
+ setColorLayout->addWidget ( m_analogFontColorLabel, 8,0);
+ setColorLayout->addWidget ( m_AFontButton ,8,1);
+ setColorLayout->addWidget ( m_digitalProcessingLabel, 9,0);
+ setColorLayout->addWidget ( m_digitalProcesingOfPointers, 9,1);
+
+
+ m_checkBoxCbac->setChecked(m_settingData->customBAnalogColor);
+ m_checkBoxCoac->setChecked(m_settingData->customOAnalogColor);
+ m_BGAButton->setColor(m_settingData->aPanelBackgroundColor);
+ m_BGAButton->setEnabled(m_settingData->customBAnalogColor);
+ m_AFingerButton->setColor(m_settingData->analogFingerColor);
+ m_AFingerButton->setEnabled(m_settingData->customOAnalogColor);
+ m_AOKButton->setColor(m_settingData->analogOKColor);
+ m_AOKButton->setEnabled(m_settingData->customOAnalogColor);
+ m_AWarnningButton->setColor(m_settingData->analogWarnningColor);
+ m_AWarnningButton->setEnabled(m_settingData->customOAnalogColor);
+ m_AErrorButton->setColor(m_settingData->analogErrorColor);
+ m_AErrorButton->setEnabled(m_settingData->customOAnalogColor);
+ m_AScaleButton->setColor(m_settingData->analogScaleColor);
+ m_AScaleButton->setEnabled(m_settingData->customOAnalogColor);
+ m_AFontButton->setColor(m_settingData->analogFontColor);
+ m_AFontButton->setEnabled(m_settingData->customOAnalogColor);
+ m_analogBackgroundColorLabel->setEnabled(m_settingData->customBAnalogColor);
+ m_analogPointerColorLabel->setEnabled(m_settingData->customOAnalogColor);
+ m_analogOKColorLabel->setEnabled(m_settingData->customOAnalogColor);
+ m_analogWarningColorLabel->setEnabled(m_settingData->customOAnalogColor);
+ m_analogErrorColorLabel->setEnabled(m_settingData->customOAnalogColor);
+ m_analogScaleColorLabel->setEnabled(m_settingData->customOAnalogColor);
+ m_analogFontColorLabel->setEnabled(m_settingData->customOAnalogColor);
+
+
+ m_digitalProcesingOfPointers->insertItem(i18n("Nothing processing"));
+ m_digitalProcesingOfPointers->insertItem(i18n("Fast antialiasing"));
+ m_digitalProcesingOfPointers->insertItem(i18n("Fine antialiasing"));
+ m_digitalProcesingOfPointers->insertItem(i18n("Fast antialiasing and blur motion"));
+ m_digitalProcesingOfPointers->insertItem(i18n("Fine antialiasing and blur motion"));
+
+ m_digitalProcesingOfPointers->setCurrentItem(m_settingData->typeDigitalProcessing);
+
+
+ connect (m_checkBoxCbac,SIGNAL(toggled(bool)),this,SLOT(slotUseCustomBAnalogColor(bool)));
+ connect (m_checkBoxCoac,SIGNAL(toggled(bool)),this,SLOT(slotUseCustomOAnalogColor(bool)));
+ }
+
+
+
+#include "knutprefdlg.moc"
diff --git a/src/knutprefdlg.h b/src/knutprefdlg.h
new file mode 100644
index 0000000..0628abd
--- /dev/null
+++ b/src/knutprefdlg.h
@@ -0,0 +1,359 @@
+/***************************************************************************
+ knutprefdlg.h - description
+ -------------------
+ begin : Tue Aug 21 2001
+ copyright : (C) 2001 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTPREFDLG_H
+#define KNUTPREFDLG_H
+
+#include "knutnewupsdlg.h"
+#include "knutupsdata.h"
+#include "knutvardata.h"
+#include "knutconst.h"
+
+
+#include <kdialogbase.h>
+#include <kpushbutton.h>
+#include <klistbox.h>
+#include <klocale.h>
+#include <kfontdialog.h>
+#include <kcolorbtn.h>
+#include <kcombobox.h>
+
+#include <qwidget.h>
+
+class QLabel;
+class QFont;
+class QCheckBox;
+class QRadioButton;
+class QSpinBox;
+
+
+/**
+ *@author Daniel Prynych
+ */
+
+/**
+ * This class makes configure dialog
+ * Tato trida je vytvari konfiguracni dialog.
+ * @author Daniel Prynych
+ * @short Konfiguracni dialog
+ * @version 0.8
+ */
+class KNutPrefDlg : public KDialogBase
+{
+ Q_OBJECT
+ public:
+
+enum changePref {
+ ChangeCountCols = 0x1, //1,
+ ChangeCustomBColor = 0x2, //2,
+ ChangeMBColor = 0x4, //4,
+ ChangeVoltage = 0x8, // 8,
+ ChangeFrequency = 0x10, // 16,
+ ChangeXFer = 0x20, // 32,
+
+ ChangeUpsSetting = 0x40, // 64,
+ ChangeUpsCount = 0x80, // 128,
+
+ ChangeMainPanelSetting = 0x100, // 256,
+ ChangeCustomMPanelBColor = 0x200, // 512,
+ ChangeMPBColor = 0x400, // 1024,
+
+ ChangeAnalogFont = 0x800, // 2048,
+ ChangePanelFont = 0x1000, // 4096,
+
+ ChangeCustomAPanelBColor = 0x2000, // 8192,
+ ChangeAPBColor = 0x4000, // 16384,
+
+ ChangeCustomAPanelOColor = 0x8000, // 32768,
+ ChangeAPOColor = 0x10000, // 65536,
+
+ ChangeCustomKIconColor = 0x20000, // 131072,
+ ChangeKIconBColor = 0x40000, // 262144,
+
+ ChangeToolTip = 0x80000, // 524288,
+
+ ChangeTypeOfKIcon = 0x100000, // 1048576
+
+ ChangeTypeOfDigProcessing = 0x200000, // 1048576 *2
+
+ ChangeSomeThing = 0x400000 // 1048576 *4
+
+
+ };
+
+
+
+
+/**
+ * Constructor makes configure dialog.
+ * Konstruktor vytvori konfiguracni dialog.
+ *
+ * @param upsData Is pointer on instance of class of KNutUpsData, which manage informations about UPSes.
+ * @param analogData Is pointer on instance of class of KNutVarData, which manages data about analog panels.
+ * @param settingData Is pointer on struct, which contain values is setted in dialog.
+ * @param upsName Is name of active UPS.
+ *
+ * @param upsData Je odkaz na instanci tridy KNutUpsData, ktera spravuje informace o UPS-kach.
+ * @param analogData Je odkaz na na instanci tridy KNutVarData, ktera spravuje data o analogovych panelech.
+ * @param settingData Je odkaz na strukturu ktera obsahuje hodnoty nastavovane v dialogu.
+ * @param upsName Je jmeno aktivni UPS-ky.
+ *
+ * @since 0.5
+ **/
+ KNutPrefDlg(KNutUpsData* const upsData, KNutVarData* const analogData, KNutVarData::SettingDataDef* const settingData, const QString upsName, QWidget* parent = 0, const char* name = 0, const bool modal = true);
+
+/**
+ * @since 0.3
+ **/
+ ~KNutPrefDlg();
+
+ signals:
+
+/**
+ * Signal is emited when statement is changed same pages.
+ * Signal je aktivovan pokud je zmenen udaj na kterekoliv strance.
+ *
+ * @param changeSetting Declare, what item was changed.
+ * @param changeSetting Udava, ktery prvek byl zmenen.
+ *
+ * @since 0.2
+ **/
+ void signalChangeConfig (unsigned int changeSetting );
+
+
+
+ private slots:
+
+/**
+ * @internal
+ */
+ virtual void slotDefault();
+
+/**
+ * @internal
+ */
+ virtual void slotApply();
+
+/**
+ * @internal
+ */
+ virtual void slotOk();
+
+/**
+ * @internal
+ */
+ void slotChangeSettingFont(int index);
+
+/**
+ * @internal
+ */
+ void slotSetPictureKI (bool on);
+
+
+/**
+ * @internal
+ */
+ void slotEnableVoltage(bool enable);
+
+
+/**
+ * @internal
+ */
+ void slotEnableFrequency(bool enable);
+
+
+/**
+ * @internal
+ */
+ void slotUseCustomBColor(bool enable);
+
+/**
+ * @internal
+ */
+ void slotUseCustomBPanelColor(bool enable);
+
+/**
+ * @internal
+ */
+void slotUseCustomBAnalogColor(bool enable);
+
+
+/**
+ * @internal
+ */
+void slotUseCustomOAnalogColor(bool enable);
+
+/**
+ * @internal
+ */
+void slotUseCustomBIconColor(bool enable);
+
+
+/**
+ * @internal
+ */
+ void slotNewUps();
+
+/**
+ * @internal
+ */
+ void slotEditUps();
+
+/**
+ * @internal
+ */
+ void slotDeleteUps();
+
+
+ private:
+
+ enum Page {
+ mainSettingPage =0,
+ upsSettingPage,
+ panelSettingPage,
+ fontSettingPage,
+ analogSettingPage,
+ kickerSettingPage
+ };
+
+/**
+ * @internal
+ */
+ void initSetting();
+
+/**
+ * @internal
+ */
+ void initUps();
+
+/**
+ * @internal
+ */
+ void initPanel();
+
+/**
+ * @internal
+ */
+ void initFonts();
+
+/**
+ * @internal
+ */
+ void initAnalog ();
+
+/**
+ * @internal
+ */
+ void initDock ();
+
+
+
+// Private values
+ QString m_activeUpsName; // name of UPS which is active
+ KNutUpsData* m_myUpsData;
+ KNutVarData* m_myAnalogData;
+ KNutVarData::SettingDataDef* m_settingData;
+ KNutNewUpsDlg* newUpsDlg;
+
+ KListBox* m_listBox2; // uses in part UPS, contain name of UPS
+
+ bool m_checked; //it's settted when, definition(parameters) of UPS were chaged // nastaveno kdyz doslo k zmene v definici UPS
+ bool m_checkedActiveUps; //it's setted when, parameters of active UPS were changed // nastaveno pokud doslo ke zmene na aktivni UPS
+
+ QSpinBox *m_numberOfColumns;
+ KColorButton *m_BGButton;
+ QCheckBox *m_checkBoxCbc;
+ QCheckBox *m_checkBoxAys;
+// QCheckBox *m_checkBoxMW;
+ QCheckBox *m_checkBoxMesW;
+ KComboBox *m_comboBoxMainWindow;
+ QCheckBox *m_xfer;
+
+ QCheckBox *m_checkBoxOver;
+ QCheckBox *m_checkBoxBL;
+ QCheckBox *m_checkBoxRB;
+ QCheckBox *m_checkBoxCal;
+ QCheckBox *m_checkBoxMFRM;
+ QCheckBox *m_checkBoxMFR;
+ QCheckBox *m_checkBoxModel;
+ QCheckBox *m_checkBoxSerial;
+ QCheckBox *m_checkBoxFirm;
+ QCheckBox *m_checkBoxRun;
+ QCheckBox *m_checkBoxCbpc;
+ QCheckBox* m_checkBoxCbac;
+ QCheckBox* m_checkBoxCoac;
+ QCheckBox *m_checkBoxCbi;
+ QCheckBox *m_checkBoxTTMFR;
+ QCheckBox *m_checkBoxTTModel;
+ QCheckBox *m_checkBoxTTSerial;
+ QCheckBox *m_checkBoxTTFirm;
+ QCheckBox *m_checkBoxTTRun;
+ QCheckBox *m_checkBoxTTCharge;
+ QCheckBox *m_checkBoxTTLoad;
+
+ QLabel *m_panelBackgroundColorLabel;
+ QLabel *m_mainBackgroundColorLabel;
+ QLabel *m_analogBackgroundColorLabel;
+ QLabel *m_dockBackgroundColorLabel;
+ QLabel *m_analogPointerColorLabel;
+ QLabel *m_analogOKColorLabel;
+ QLabel *m_analogWarningColorLabel;
+ QLabel *m_analogErrorColorLabel;
+ QLabel *m_analogScaleColorLabel;
+ QLabel *m_analogFontColorLabel;
+ QLabel *m_digitalProcessingLabel;
+ QLabel *m_iconDockLabel;
+
+ QRadioButton *m_vRadioButton1;
+ QRadioButton *m_vRadioButton2;
+ QRadioButton *m_fRadioButton1;
+ QRadioButton *m_fRadioButton2;
+ QRadioButton *m_iconRadioButton1;
+ QRadioButton *m_iconRadioButton2;
+
+ KColorButton *m_BGPButton;
+ KColorButton* m_BGAButton;
+ KColorButton* m_AFingerButton;
+ KColorButton* m_AOKButton;
+ KColorButton* m_AWarnningButton;
+ KColorButton* m_AErrorButton;
+ KColorButton* m_AScaleButton;
+ KColorButton* m_AFontButton;
+ KColorButton *m_BGIButton;
+
+ KComboBox* m_digitalProcesingOfPointers;
+
+ QButtonGroup *m_voltageGroup;
+ QButtonGroup *m_frequencyGroup;
+
+ QCheckBox* m_customFont; // User's font
+ KFontChooser *m_fontWidget;
+
+ QFont m_aPanelFont; // Analog panel font
+ QFont m_mPanelFont; // Main panel font
+
+ int m_settingFont; // which font is setted (selected)
+
+ QPixmap m_panelPix;
+ QPixmap m_mSetPix;
+ QPixmap m_upsesPix;
+ QPixmap m_analogPix;
+ QPixmap m_dockPix;
+
+};
+
+#endif
diff --git a/src/knutprintupsvar.cpp b/src/knutprintupsvar.cpp
new file mode 100644
index 0000000..bfd09e4
--- /dev/null
+++ b/src/knutprintupsvar.cpp
@@ -0,0 +1,210 @@
+/***************************************************************************
+ knutprintupsvar.cpp - description
+ -------------------
+ begin : St cec 3 2002
+ copyright : (C) 2002 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#include "knutprintupsvar.h"
+#include "knutvardata.h"
+
+#include <kmessagebox.h>
+#include <kglobal.h>
+#include <kiconloader.h>
+
+#include <qgroupbox.h>
+#include <qscrollview.h>
+#include <qtooltip.h>
+#include <qlabel.h>
+#include <qframe.h>
+#include <qpixmap.h>
+#include <qstring.h>
+
+
+
+//#include <iostream>
+
+
+// od verze 0.6.0 nebudeme vytvaret vlastni spojeni
+
+KNutPrintUpsVar::KNutPrintUpsVar(KNutNet* const upsNet, const bool useDescription, QWidget* parent, const char* name, const bool modal )
+: KDialogBase(Plain, i18n("Variables"),User1|Cancel,Ok, parent, name, modal, true), myUpsNet(upsNet){
+
+ upsVarDef upsVar;
+ upsICommDef upsIComm;
+ dataVar pointerVar;
+ dataList.clear();
+
+ if (!upsNet) return;
+
+ setButtonText(User1,i18n("Reload Vars"));
+ setName( "knutprintupsvar" );
+ setCaption( i18n("UPS variables") );
+
+ //int error;
+ if (myUpsNet->getState() != KNutNet::Connected) {
+ KNutVarData::showError (KNutNet::NotConnection);
+ upsConnectOk = false;
+ page=0;
+ }
+ else {
+ upsConnectOk = true;
+ countVars=myUpsNet->readNumberVars(KNutNet::AllVars);
+ countRWVars=myUpsNet->readNumberVars(KNutNet::RWVars);
+ countIComms=myUpsNet->readNumberComms();
+
+ KIconLoader *loader = KGlobal::iconLoader();
+ dirPixmap=loader->loadIcon ("folder_open",KIcon::Small,16);
+
+ page = plainPage();
+ QHBoxLayout* upsVarsMainLayout = new QHBoxLayout(page);
+
+ table = new KListView(page);
+ table->setRootIsDecorated(true);
+
+ table->setAllColumnsShowFocus( TRUE );
+ table->setFullWidth ( true );
+
+ table->addColumn( i18n("Name") );
+ table->addColumn( i18n("Value") );
+ if (useDescription)
+ table->addColumn( i18n("Description") );
+ table->setSorting (-1);
+
+ upsVarsMainLayout->addWidget(table);
+
+
+ KListViewItem* myListItem;
+ if (countIComms) {
+
+ ICommList = new KListViewItem( table, i18n("Instant Commands"));
+ ICommList->setOpen(true);
+
+ for (int i=0; i<countIComms; i++) {
+ myUpsNet->readIComm(i+1,upsIComm);
+
+ myListItem = addListItem( ICommList,upsIComm.upsCommName,"");
+ if ((!upsVar.upsDescription.isEmpty()) && useDescription)
+ myListItem->setText(2,upsIComm.upsDescription);
+ }
+ }
+
+ if (countRWVars) {
+ RWVarsList = new KListViewItem( table, i18n("Read/Write Variables"));
+ RWVarsList->setOpen(true);
+ for (int i=0; i<countVars; i++) {
+ myUpsNet->readVars(i+1,upsVar);
+
+ if (!upsVar.upsVarType) {
+ pointerVar.myName=upsVar.upsVarName;
+ pointerVar.myValue = addListItem( RWVarsList,upsVar.upsVarName,upsVar.upsValue);
+
+ if ((!upsVar.upsDescription.isEmpty()) && useDescription)
+ pointerVar.myValue->setText(2,upsVar.upsDescription);
+
+ dataList.push_back(pointerVar);
+ }
+ }
+ }
+
+
+ ROVarsList = new KListViewItem( table, i18n("Read Only Variables"));
+ ROVarsList->setOpen(true);
+
+ for (int i=0; i<countVars; i++) {
+ myUpsNet->readVars(i+1,upsVar);
+ if (upsVar.upsVarType) {
+
+ pointerVar.myName=upsVar.upsVarName;
+ pointerVar.myValue = addListItem( ROVarsList,upsVar.upsVarName,upsVar.upsValue);
+
+ if ((!upsVar.upsDescription.isEmpty()) && useDescription)
+ pointerVar.myValue->setText(2,upsVar.upsDescription);
+
+ dataList.push_back(pointerVar);
+ }
+ }
+
+ connect (this,SIGNAL(user1Clicked()),this,SLOT(slotReloadVars()));
+ } // end else
+ }
+
+
+
+KNutPrintUpsVar::~KNutPrintUpsVar(){
+
+ dataList.clear();
+ if (page) delete page;
+ }
+
+
+void KNutPrintUpsVar::slotReloadVars (void) {
+ upsVarDef upsVar;
+
+ if (myUpsNet->getUpsValues(true) !=0)
+ KNutVarData::showError (myUpsNet->getError());
+ else {
+
+ QValueVector<dataVar>::const_iterator it;
+ for (it = dataList.begin(); it != dataList.end(); it++) {
+ myUpsNet->readVars((*it).myName, upsVar);
+ (*it).myValue->setText (1, upsVar.upsValue);
+ }
+ }
+ }
+
+ KListViewItem* KNutPrintUpsVar::addListItem (KListViewItem* table, QString varName, QString value) {
+ KListViewItem* myListItem;
+ KListViewItem* helpListItem;
+ QString left;
+ int n;
+
+ myListItem = table;
+ do {
+ n = varName.find(".");
+ if (n > 0) {
+ left = varName.left(n);
+ varName = varName.mid(n+1);
+ if (!(helpListItem = existListItem( myListItem,left))) {
+ myListItem = new KListViewItem( myListItem, left);
+ myListItem->setOpen(true);
+ }
+ else myListItem = helpListItem;
+ if (!myListItem->pixmap(0)) myListItem->setPixmap(0,dirPixmap);
+ }
+ else { // end part
+ helpListItem = new KListViewItem( myListItem, varName, value);
+ helpListItem->setOpen(true);
+ return helpListItem;
+ }
+ } while (n > -1);
+ return 0; // for compiler only
+ }
+
+
+ KListViewItem* KNutPrintUpsVar::existListItem (KListViewItem* listItem, QString name) {
+ KListViewItem* myItem;
+
+ if (!(myItem = (KListViewItem *)listItem->firstChild())) return 0l;
+ while (myItem) {
+ if (myItem->text(0) == name) return myItem;
+ myItem = (KListViewItem *)myItem->nextSibling();
+ }
+ return 0l;
+ }
+
+bool KNutPrintUpsVar::upsOk (void) { return upsConnectOk; }
+
+
+#include "knutprintupsvar.moc"
+
diff --git a/src/knutprintupsvar.h b/src/knutprintupsvar.h
new file mode 100755
index 0000000..bded7ac
--- /dev/null
+++ b/src/knutprintupsvar.h
@@ -0,0 +1,160 @@
+/***************************************************************************
+ knutprintupsvar.h - description
+ -------------------
+ begin : St cec 3 2002
+ copyright : (C) 2002 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTPRINTUPSVAR_H
+#define KNUTPRINTUPSVAR_H
+
+//Od verze 3 je kapp jen odkaz na kapplication
+//#include <kapplication.h>
+#include <kapp.h>
+#include "knutupsdata.h"
+#include "knutnet.h"
+
+#include <kdialogbase.h>
+#include <kcombobox.h>
+#include <kpushbutton.h>
+#include <klistview.h>
+
+
+#include <qvariant.h>
+#include <qlayout.h>
+#include <qvaluelist.h>
+
+
+#include <qvaluevector.h>
+
+class QLabel;
+class QPixmap;
+class QFramel;
+class QString;
+
+/**
+ *@author Daniel Prynych
+ */
+
+/**
+ * Tato trida zajistuje zobrazeni vsech promenych,
+ * ktere podporuje prislusny ovladac/driver/model (ovladac) NUTu
+ * pro urcenou UPS-ku
+ * @author Daniel Prynych
+ * @short NUT show UPS vars
+ * @version 0.3.2
+*/
+class KNutPrintUpsVar : public KDialogBase {
+
+ Q_OBJECT
+
+public:
+/**
+ * Constructor - makes window, reads values of variables
+ * and will write names and values of variables
+ * Konstruktor - vytvori okno, nacte hodnoty promennych,
+ * a vypise jmena a hodnoty promenych.
+ * @param upsnet Je odkaz na instanci KNutNet - obsahuje hodnoty promennych systemu NUT.
+ * @param useDescription Urcuje zda pouzit pro promenne a prikazy taky popis.
+ * pokud data o UPS-kach neexistuji vraci funkce upsOk vzdy false.
+ *
+ * since 0.3.1
+ **/
+ KNutPrintUpsVar(KNutNet* const upsNet, const bool useDescription, QWidget* parent = 0, const char* name = 0, const bool modal = true);
+
+/**
+ * @since 0.1
+ **/
+ ~KNutPrintUpsVar();
+
+
+
+
+/**
+ * Vrati zda se povedlo pripojit na server NUT-u a nacist udaje.
+ *
+ * @since 0.1
+ **/
+ bool upsOk (void);
+
+
+protected:
+
+/****** protected vars ************/
+
+ int countVars;
+ int countIComms;
+ int countRWVars;
+
+ KNutNet* myUpsNet;
+
+ KPushButton* reloadButton;
+
+ struct dataVar {
+ QString myName;
+ KListViewItem* myValue;
+ };
+ QValueVector<dataVar> dataList;
+ KListViewItem* ROVarsList;
+ KListViewItem* RWVarsList;
+ KListViewItem* ICommList;
+
+ QFrame *page;
+ KListView* table;
+
+ QPixmap dirPixmap;
+
+
+ bool upsConnectOk;
+
+/********** protected functions ****************/
+
+/**
+ * @internal
+ * adds name into part of tree
+ * Prida jmeno do casti stromu.
+ * @param table is top of tree's part
+ * @param varName is text which is addes into tree on the first column
+ * @param varName is text which is addes into tree on the second column
+ * @param table je vrchol casti stromu.
+ * @param varName je text ktere se prida do stromu na prvni sloupec.
+ * @param value je text ktere se prida do stromu na druhy sloupec.
+ *
+ * @since 0.2.1
+ **/
+ KListViewItem* addListItem (KListViewItem* table, QString varName, QString value);
+
+/**
+ * @internal
+ * Zjisti existenci jmena ve vetvi stromu
+ *
+ * listItem je vrcholovy prvek vetve.
+ * @param name je jmeno ktere se hleda ve strome.
+ *
+ * @since 0.2
+ **/
+ KListViewItem* existListItem (KListViewItem* listItem, QString name);
+
+protected slots:
+
+/**
+ * @internal
+ * Nacte a prepise hodnoty promenych
+ *
+ * @since 0.3
+ **/
+ void slotReloadVars (void);
+
+};
+
+#endif
diff --git a/src/knutrwvar.cpp b/src/knutrwvar.cpp
new file mode 100755
index 0000000..20e45bc
--- /dev/null
+++ b/src/knutrwvar.cpp
@@ -0,0 +1,217 @@
+/***************************************************************************
+ knutrwvar.cpp - description
+ -------------------
+ begin : So ríj 26 2002
+ copyright : (C) 2002 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+
+#include "knutrwvar.h"
+#include "knutvardata.h"
+#include "knutprintupsvar.h"
+
+//Od verze 3 je kapp jen odkaz na kapplication
+//#include <kapplication.h>
+#include <kapp.h>
+#include <kcombobox.h>
+#include <kmessagebox.h>
+#include <klocale.h>
+
+
+#include <qframe.h>
+#include <qlabel.h>
+#include <qstring.h>
+#include <qlayout.h>
+
+
+//#include <iostream>
+
+KNutRWVar::KNutRWVar(QString* userName, QString* userPassword, const QString uName, const QString password, KNutNet* const initUpsNet, QWidget* parent, const char* name, const bool modal)
+: KDialogBase(Plain, i18n("RW variables"),Ok|Cancel|Default,Ok, parent, name, modal, true), m_upsNet(initUpsNet){
+ upsVarDef upsVar;
+
+// int error;
+
+ if (m_upsNet->getState() != KNutNet::Connected) {
+ KNutVarData::showError (KNutNet::NotConnection);
+ m_upsConnectOk = false;
+ }
+ else {
+ m_oldUserName = userName;
+ m_oldUserPassword = userPassword;
+
+ m_upsConnectOk = true;
+ QFrame *page = plainPage();
+ QVBoxLayout *topLayout = new QVBoxLayout( page, 0, spacingHint() );
+ QLabel *label1 = new QLabel (i18n("SET RW VARIABLE"),page,"label1");
+ label1->setAlignment(Qt::AlignHCenter);
+ topLayout->addWidget(label1);
+
+
+ QLabel *label2 = new QLabel (i18n("Variable:"),page,"label2");
+ m_rWVarBox = new KComboBox(page,"rwvarbox");
+
+ QLabel *label3 = new QLabel (i18n("Value:"),page,"label2");
+ m_valueVarBox = new KComboBox(page,"valuevarbox");
+ m_valueVarLine = new KLineEdit(page,"valuevarLine");
+ m_valueVarLine->hide();
+
+ m_passLayout = new QGridLayout (4,2,5,"passLayout");
+ QLabel *labelName = new QLabel (i18n("User name:"),page,"labelName");
+ QLabel *labelPassword = new QLabel (i18n("Password:"),page,"labelPassword");
+ m_lineEditName = new KLineEdit( page, "LineEditName" );
+ m_lineEditPassword = new KLineEdit( page, "LineEditName" );
+
+
+ if (((*m_oldUserName) == "") && ((*m_oldUserPassword) == "")) {
+ m_lineEditName->setText(uName);
+ m_lineEditPassword->setText(password);
+ }
+ else {
+ m_lineEditName->setText(*m_oldUserName);
+ m_lineEditPassword->setText(*m_oldUserPassword);
+ }
+
+ if (!((*m_oldUserName) == "") || !((*m_oldUserPassword) == "")) {
+ m_lineEditName->setDisabled(true);
+ m_lineEditPassword->setDisabled(true);
+ }
+
+ m_lineEditPassword->setEchoMode(QLineEdit::Password);
+
+ topLayout->addLayout(m_passLayout);
+
+ m_passLayout->addWidget(label2,0,0);
+ m_passLayout->addWidget(m_rWVarBox,0,1);
+ m_passLayout->addWidget(label3,1,0);
+ m_passLayout->addWidget(labelName,2,0);
+ m_passLayout->addWidget(labelPassword,3,0);
+ m_passLayout->addWidget(m_lineEditName,2,1);
+ m_passLayout->addWidget(m_lineEditPassword,3,1);
+
+ topLayout->addStretch(10);
+ //loads ComboBox
+ int n;
+ if (( n = (m_upsNet->readNumberVars( KNutNet::RWVars )+1)) > 1 ) { // zvetsime si pocet o 1
+ for (int i =1; i < n ; i++) {
+ if (!m_upsNet->readVars(i, upsVar,KNutNet::RWVars))
+ m_rWVarBox->insertItem(upsVar.upsVarName);
+ }
+ slotChangeVar(0);
+ }
+ else {
+ m_passLayout->addWidget(m_valueVarLine,1,1);
+ m_valueVarLine->setMaxLength(upsVar.upsVarMax);
+ m_valueVarBox->hide();
+ m_valueVarLine->show();
+ m_upsValueType=true;
+ }
+ connect (m_rWVarBox,SIGNAL(activated(int)),this,SLOT(slotChangeVar(int)));
+ }
+ }
+
+int KNutRWVar::findItem(const KComboBox *myBox, const QString text) {
+ int n;
+
+ if ((n=myBox->count())) {
+ for (int i =0; i < n; i++)
+ if (text == myBox->text(i)) return i;
+ }
+ return myBox->currentItem();
+ }
+
+
+void KNutRWVar::slotDefault () {
+ upsVarDef upsVar;
+ int error;
+
+ QString varName = m_rWVarBox->currentText();
+ if (!( error = m_upsNet->readVars(varName,upsVar))) {
+ if (upsVar.upsValueType) m_valueVarLine->setText(upsVar.upsValue);
+ else m_valueVarBox->setCurrentItem(upsVar.upsValue);
+ }
+ else KNutVarData::showError (error);
+ }
+
+
+void KNutRWVar::slotChangeVar(int item) {
+ upsVarDef upsVar;
+
+ QString varName = m_rWVarBox->text(item);
+ int error = m_upsNet->readVars(varName,upsVar);
+ m_upsValueType=upsVar.upsValueType;
+ if (error || (upsVar.upsValueType)) {
+ // char
+ m_valueVarBox->hide();
+ m_valueVarLine->show();
+ m_passLayout->addWidget(m_valueVarLine,1,1);
+ m_valueVarLine->setText(upsVar.upsValue);
+ }
+ else {
+ //enum
+ m_valueVarLine->hide();
+ m_valueVarBox->show();
+ m_passLayout->addWidget(m_valueVarBox,1,1);
+ m_valueVarBox->clear();
+ if (upsVar.upsVarMax) {
+ for (int i = 0 ; i < upsVar.upsVarMax; i++)
+ m_valueVarBox->insertItem(m_upsNet->readEnumValueVar(upsVar.upsVarName,i+1));
+ }
+ m_valueVarBox->setCurrentItem(upsVar.upsValue);
+ }
+ }
+
+
+
+KNutRWVar::~KNutRWVar(){
+}
+
+bool KNutRWVar::upsOk (void) { return m_upsConnectOk; }
+
+
+void KNutRWVar::slotOk() {
+ QString value;
+ int error =0;
+ if (m_upsValueType) value=m_valueVarLine->text();
+ else value=m_valueVarBox->currentText();
+
+ if (((*m_oldUserName) == "") && ((*m_oldUserPassword) == "")) {
+ //the first connection sets name and password
+ //prvni propojeni nastavime jmeno a heslo
+ if (!(error = m_upsNet->setVariable(m_rWVarBox->currentText(), value, m_lineEditName->text(),m_lineEditPassword->text(),false))) {
+ // vzhledem k asynchronimu spracovani asi zbytecne
+// myUpsNet->getUpsValues(true);
+ emit signalChangeRWVars(m_rWVarBox->currentText());//emits command for loading of variable and repaint of panel
+
+ (*m_oldUserName) = m_lineEditName->text();
+ (*m_oldUserPassword) = m_lineEditPassword->text();
+ accept();
+ }
+ }
+ else {
+ if (((*m_oldUserName) == m_lineEditName->text()) && ((*m_oldUserPassword) == m_lineEditPassword->text())) {
+ if (!(error = m_upsNet->setVariable(m_rWVarBox->currentText(), value, m_lineEditName->text(),m_lineEditPassword->text(),true))) {
+ // next line isn't needed, maybe
+ // vzhledem k asynchronimu spracovani asi zbytecne
+// myUpsNet->getUpsValues(true);
+ emit signalChangeRWVars(m_rWVarBox->currentText()); //emits command for loading of variable and repaint of panel
+ accept();
+ }
+ }
+ }
+ //Nahlasime chybu
+ // sends information about error
+ if (error) KNutVarData::showError (error);
+ }
+
+#include "knutrwvar.moc"
diff --git a/src/knutrwvar.h b/src/knutrwvar.h
new file mode 100755
index 0000000..4cef64c
--- /dev/null
+++ b/src/knutrwvar.h
@@ -0,0 +1,140 @@
+/***************************************************************************
+ knutrwvar.h - description
+ -------------------
+ begin : So ríj 26 2002
+ copyright : (C) 2002 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTRWVAR_H
+#define KNUTRWVAR_H
+
+#include "knutnet.h"
+
+#include <kdialogbase.h>
+#include <klineedit.h>
+#include <klocale.h>
+#include <kcombobox.h>
+
+
+class QString;
+class QGridLayout;
+
+/**
+ * This class is graphics interface for changes of RW variables.
+ * Tato trida je graficke rozhrani pro zmenu RW promennych.
+ *
+ * @author Daniel Prynych
+ * @short RW promenne
+ * @version 0.2
+*/
+class KNutRWVar : public KDialogBase {
+ Q_OBJECT
+ public:
+/**
+ * Constructor - makes window for change of RW variable.
+ * Konstruktor - vytvori okno pro zmenu RW promene.
+ *
+
+ * @param uName Describes user name.
+ * @param password Describes password.
+ * @param initUpsNet is pointer of intance of class KNutNet.
+ * @param userName Urcuje uzivatelske jmeno.
+ * @param userPassword Urcuje heslo.
+ * @param uName Urcuje uzivatelske jmeno.
+ * @param password Urcuje heslo.
+ * @param initUpsNet Je odkaz na instanci tridy KNutNet.
+ * @since 0.2
+ **/
+ KNutRWVar(QString* userName, QString* userPassword, const QString uName, const QString password, KNutNet* const initUpsNet, QWidget* parent = 0, const char* name = 0, const bool modal = TRUE);
+
+/**
+ * Destructor
+ *
+ * @since 0.2
+ **/
+ ~KNutRWVar();
+
+/**
+ * Vraci true pokud existuje pripojeni na server a vytvorilo se
+ * ovladaci okno pro nastaveni promennych.
+ *
+ * @since 0.3
+ **/
+ bool upsOk (void);
+
+
+ private slots:
+
+/**
+ * @internal
+ *
+ * Nastavi hodnotu a zpusob vyberu hodnoty promenne.
+ */
+ void slotChangeVar(int item);
+
+/**
+ * @internal
+ *
+ * Sets value of variable on default value
+ * Nastavi hodnotu promenne na puvodni hodnotu.
+ */
+ virtual void slotDefault ();
+
+/**
+ * @internal
+ *
+ * Provede akci
+ */
+ virtual void slotOk();
+
+
+
+/**
+ * @internal
+ *
+ * Find asked item in box
+ * Since at version 3.0.0 is not needed.
+ * Najde pozadovanou polozku v boxu.
+ * Ve verzi qt > 3.0.0 neni potreba.
+ */
+int findItem(const KComboBox *myBox ,const QString text);
+
+ signals:
+/**
+ * Signal je aktivovam pokud je zmenen udaj na kterekoliv strance.
+ *
+ * @param changeSetting Udava co bylo zmeneno.
+ *
+ * @since 0.1
+ **/
+ void signalChangeRWVars (QString varName);
+
+
+ private:
+ KNutNet* m_upsNet;
+ KLineEdit *m_lineEditName;
+ KLineEdit *m_lineEditPassword;
+ KComboBox *m_rWVarBox;
+ KComboBox *m_valueVarBox;
+ KLineEdit *m_valueVarLine;
+ QGridLayout *m_passLayout;
+ bool m_upsValueType;
+ bool m_upsConnectOk;
+
+ QString* m_oldUserName;
+ QString* m_oldUserPassword;
+
+
+ };
+
+#endif
diff --git a/src/knutupsdata.cpp b/src/knutupsdata.cpp
new file mode 100644
index 0000000..9a4a0b5
--- /dev/null
+++ b/src/knutupsdata.cpp
@@ -0,0 +1,78 @@
+/***************************************************************************
+ knutupsdata.cpp - description
+ -------------------
+ begin : Tue Aug 21 2001
+ copyright : (C) 2001 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#include "knutupsdata.h"
+#include "knutvardata.h"
+
+#include <qstring.h>
+
+
+KNutUpsData::KNutUpsData() {
+// vytvori seznam UPS
+ m_listRecords.clear();
+ m_countUpsRecords = 0;
+ }
+
+KNutUpsData::~KNutUpsData() { m_listRecords.clear(); }
+
+void KNutUpsData::add (const upsRecordDef upsRecord) {
+// vlozime ups na konec
+ m_countUpsRecords++;
+ m_listRecords.append(upsRecord);
+ }
+
+
+void KNutUpsData::put (const int index, const upsRecordDef upsRecord ) {
+ if ((index > -1 ) && (index < m_countUpsRecords)) {
+ m_listRecords[index] = (upsRecord);
+ }
+ }
+
+
+void KNutUpsData::get (const int index, upsRecordDef& upsRecord ) {
+ if ((index > -1 ) && (index < m_countUpsRecords)) upsRecord=m_listRecords[index];
+ }
+
+QString KNutUpsData::getName (const int index) {
+ if ((index > -1 ) && (index < m_countUpsRecords)) return m_listRecords[index].name;
+ else return 0L;
+ }
+
+
+void KNutUpsData::deleteName (const int index) {
+ if ((index > -1 ) && (index < m_countUpsRecords)) {
+ QValueList<upsRecordDef>::Iterator it = m_listRecords.begin();
+ for (int i =0; i < index; i++) it++;
+ m_listRecords.remove(it);
+ m_countUpsRecords--;
+ }
+}
+
+
+int KNutUpsData::getCount ( void ) { return m_countUpsRecords; }
+
+
+KNutUpsData::upsRecordDef* KNutUpsData::findName (const QString name) {
+ QValueList<upsRecordDef>::Iterator it;
+ for (it = m_listRecords.begin(); it != m_listRecords.end(); it++) {
+ if ((*it).name == name) {
+ return &(*it); // vratime adresu
+ }
+ }
+ return 0l;
+ }
+
diff --git a/src/knutupsdata.h b/src/knutupsdata.h
new file mode 100644
index 0000000..e258227
--- /dev/null
+++ b/src/knutupsdata.h
@@ -0,0 +1,161 @@
+/***************************************************************************
+ knutupsdata.h - description
+ -------------------
+ begin : Tue Aug 21 2001
+ copyright : (C) 2001 by Daniel Prynych
+ email : Daniel@prynych.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTUPSDATA_H
+#define KNUTUPSDATA_H
+
+#include "knutconst.h"
+#include "knutanalog.h"
+
+#include <qstring.h>
+#include <qvaluelist.h>
+
+class QString;
+
+/**
+ *@author Daniel Prynych
+ */
+
+
+
+ /**
+ * Trida obsahuje data o UPS-kach,
+ * nazev, adresu port, protokol, promenne atd.
+ * Class includes data about UPSes like name. address, port, protocol, variables ...
+ *
+ * @author Daniel Prynych
+ * @short Information about UPS
+ * @version 0.4
+ **/
+class KNutUpsData {
+
+
+public:
+
+
+struct upsRecordDef { //include information about one UPS
+ QString name; // name
+ QString upsName; // name of UPSky <> mojeups
+ QString upsAddress; // address of UPS <> muj.pc.cz
+ long delay; // time between read date from UPS
+ unsigned short port; // port for connecting server
+ QString userName;
+ QString password;
+ bool savePassword; //save password into configuration
+ int upsVarCode[knc::NumberOfVars];
+ };
+
+
+
+ /**
+ * Konstruktor
+ *
+ * @since 0.3
+ **/
+ KNutUpsData();
+
+ /**
+ * Destruktor
+ *
+ * @since 0.3
+ **/
+ ~KNutUpsData();
+
+ /**
+ * Adds record
+ * Prida zaznam.
+ *
+ * @param upsRecord are data of record in structure of upsRecordStruct.
+ * @param upsRecord jsou data zaznamu ve strukture upsRecordStruct.
+ * @since 0.4
+ **/
+ void add (const upsRecordDef upsRecord);
+
+ /**
+ * Rewrites record
+ * Prepise zaznam.
+ *
+ * @param index Describes order number od record.
+ * @param index Udava poradove cislo zaznamu..
+ * @param upsRecord are data of record in structure of upsRecordStruct.
+ * @param upsRecord jsou data zaznamu ve strukture upsRecordStruct.
+ * @since 0.4
+ **/
+ void put (const int index, const upsRecordDef upsRecord );
+
+ /**
+ * Returns record.
+ * Vrati zaznam.
+ *
+ * @param index Describes order number od record.
+ * @param index Udava poradove cislo zaznamu.
+ * @param upsRecord are data of record in structure upsRecordStruct.
+ * @param upsRecord jsou data zaznamu ve strukture upsRecordStruct.
+ *
+ * @since 0.4
+ **/
+ void get (const int index, upsRecordDef& upsRecord );
+
+ /**
+ * Returns name of record.
+ * Vrati jmeno zaznamu.
+ *
+ * @param index Describes order number od record.
+ * @param index Udava poradove cislo zaznamu.
+ * @since 0.3
+ **/
+ QString getName (const int index);
+
+ /**
+ * Deletes record;
+ * Zrusi zaznam.
+ *
+ * @param index Describes order number od record.
+ * @param index Udava poradove cislo zaznamu.
+ *
+ * @since 0.3
+ **/
+ void deleteName (const int index);
+
+ /**
+ * Returns count of records
+ * Vrati pocet zaznamu.
+ *
+ * @since 0.3
+ **/
+ int getCount ( void );
+
+ /**
+ * Returns pointer on record, when record is not existed returns 0
+ * Vrati ukazatel na zaznam, pokud zaznam neexistuje vrati 0.
+ *
+ * @param name Is name of list.
+ * @param name Je jmeno zaznamu.
+ * @since 0.3
+ **/
+ upsRecordDef* findName (const QString name);
+
+
+
+private:
+ int m_countUpsRecords;
+
+ QValueList<upsRecordDef> m_listRecords;
+};
+
+
+#endif
diff --git a/src/knutvardata.cpp b/src/knutvardata.cpp
new file mode 100755
index 0000000..86650bd
--- /dev/null
+++ b/src/knutvardata.cpp
@@ -0,0 +1,242 @@
+/***************************************************************************
+ knutvardata.cpp - description
+ -------------------
+ begin : Tue Aug 21 2001
+ copyright : (C) 2001 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#include "knutvardata.h"
+#include "knutnet.h"
+
+#include <klocale.h>
+#include <kmessagebox.h>
+
+#include <qcolor.h>
+
+//#include <iostream>
+
+ const char *nameUpsVars1[] = {
+ "NONE", "UTILITY", "BATTPCT", "UPSTEMP", "ACFREQ", "LOADPCT", "AMBTEMP", "AMBHUMID","BATTVOLT","OUTVOLT","CURRENT","NONE","BATT_TEMP","BATT_CURRENT"};
+
+ const char *nameUpsVars2[] = {
+ "none", "input.voltage", "battery.charge", "ups.temperature", "input.frequency", "ups.load", "ambient.temperature", "ambient.humidity","battery.voltage","output.voltage","output.current","output.frequency","battery.temperature","battery.current"};
+
+/*
+ * Nic,Vstupni Napeti,Baterie,Teplota UPSky,
+ * Vstupni frekvence,Zatizeni,Vnejsi teplota,
+ * Vnejsi vlhkost,Napeti baterie, Vystupni napeti
+ * Vystupni proud, Teplota baterie, Proud baterie
+*/
+
+KNutVarData::KNutVarData(){
+
+ m_upsVarNameAnalog[0] = i18n("None");
+ m_upsVarNameAnalog[1] = i18n("Input Voltage");
+ m_upsVarNameAnalog[2] = i18n("Battery Charge");
+ m_upsVarNameAnalog[3] = i18n("UPS Temperature");
+ m_upsVarNameAnalog[4] = i18n("Input Frequency");
+ m_upsVarNameAnalog[5] = i18n("UPS Load");
+ m_upsVarNameAnalog[6] = i18n("Outside Temperature");
+ m_upsVarNameAnalog[7] = i18n("Outside Humidity");
+ m_upsVarNameAnalog[8] = i18n("Battery Voltage");
+ m_upsVarNameAnalog[9] = i18n("Output Voltage");
+ m_upsVarNameAnalog[10] = i18n("Output Current");
+ m_upsVarNameAnalog[11] = i18n("Output Frequency");
+ m_upsVarNameAnalog[12] = i18n("Battery Temperature");
+ m_upsVarNameAnalog[13] = i18n("Battery Current");
+
+ static const QString upsVarNameUnit[] = {"", "V", "%", "C", "Hz", "%", "C", "%", "V", "V", "A","Hz","C", "A"};
+ static const int upsVarType[] = {0,3,2,1,1,2,1,1,3,3,2,1,1,2}; //typ panelu
+ static const int upsVarItem[] = {5,4,5,5,6,6,5,5,5,4,5,6,5,5}; // pocet velkych policek na stupnici
+ static const int upsVarInItem[] = {0,3,0,0,4,0,0,0,0,3,5,4,0,5}; // pocet malych policek ve velkem policku na stupnici
+ static const int upsVarStart[] = {0,170,0,-10,20,0,-10,0,0,170,0,20,-10,-15};
+ static const int upsVarEnd[] = {0,290,100,90,80,120,70,100,10,290,5,80,90,10};
+ static const int upsVarScaleStart[ knc::NumberOfTypes ][5] = {{0,0,0,0,0},{0,210,0,0,0},{50,0,40,0,0},{-100,50,0,0,0},{0,40,45,0,0},{0,80,100,0,0},{-100,50,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{210,0,250,0,0},{0,0,0,0,0},{0,40,45,0,0},{-100,50,0,0,0},{0,0,0,0,0}};
+ static const int upsVarScaleEnd[ knc::NumberOfTypes ][5] = {{0,0,0,0,0},{400,250,0,0,0},{120,40,50,0,0},{50,100,0,0,0},{90,60,55,0,0},{80,100,120,0,0},{50,70,0,0,0},{0,0,0,0,0},{0,0,0,0,0},{250,210,400,0,0},{0,0,0,0,0},{90,60,55,0,0},{50,100,0,0,0},{0,0,0,0,0}};
+
+
+
+ int upsVarScaleColor[ knc::NumberOfTypes ][5] = {{aRegWhite,aRegWhite,aRegWhite,aRegWhite,aRegWhite},
+ {aRegRed,aRegGreen,aRegWhite,aRegWhite,aRegWhite},
+ {aRegGreen,aRegRed,aRegYellow,aRegWhite,aRegWhite},
+ {aRegGreen,aRegRed,aRegWhite,aRegWhite,aRegWhite},
+ {aRegRed,aRegYellow,aRegGreen,aRegWhite,aRegWhite},
+ {aRegGreen,aRegYellow,aRegRed,aRegWhite,aRegWhite},
+ {aRegGreen,aRegRed,aRegWhite,aRegWhite,aRegWhite},
+ {aRegWhite,aRegWhite,aRegWhite,aRegWhite,aRegWhite},
+ {aRegGreen,aRegRed,aRegRed,aRegWhite,aRegWhite},
+ {aRegGreen,aRegRed,aRegRed,aRegWhite,aRegWhite},
+ {aRegWhite,aRegWhite,aRegWhite,aRegWhite,aRegWhite},
+ {aRegRed,aRegYellow,aRegGreen,aRegWhite,aRegWhite},
+ {aRegGreen,aRegRed,aRegWhite,aRegWhite,aRegWhite},
+ {aRegWhite,aRegWhite,aRegWhite,aRegWhite,aRegWhite}};
+
+
+ for (int i=0;i < knc::NumberOfTypes; i++) {
+ m_dataVar[i].nameAnalog = m_upsVarNameAnalog[i];
+ m_dataVar[i].nameUnit = upsVarNameUnit[i];
+ m_dataVar[i].typeAnalog = upsVarType[i];
+ m_dataVar[i].numberItem = upsVarItem[i];
+ m_dataVar[i].numberInItem = upsVarInItem[i];
+ m_dataVar[i].start = upsVarStart[i];
+ m_dataVar[i].end = upsVarEnd[i];
+ for (int j=0; j< 5; j++) {
+ m_dataVar[i].scaleStruct[j].start=upsVarScaleStart[i][j];
+ m_dataVar[i].scaleStruct[j].end=upsVarScaleEnd[i][j];
+ m_dataVar[i].scaleStruct[j].scaleColor=upsVarScaleColor[i][j];
+ }
+ }
+
+ m_dataVarVoltage[U230V]=m_dataVar[knc::VarUtility];
+ m_dataVarVoltage[U120V]=m_dataVar[knc::VarUtility];
+ m_dataVarVoltage[U120V].start=90;
+ m_dataVarVoltage[U120V].end=150;
+ m_dataVarVoltage[U120V].scaleStruct[0].start=0;
+ m_dataVarVoltage[U120V].scaleStruct[1].start=110;
+ m_dataVarVoltage[U120V].scaleStruct[0].end=200;
+ m_dataVarVoltage[U120V].scaleStruct[1].end=130;
+
+ m_dataVarFrequence[F50HZ]=m_dataVar[knc::VarAcfreq];
+ m_dataVarFrequence[F60HZ]=m_dataVar[knc::VarAcfreq];
+ m_dataVarFrequence[F60HZ].start=30;
+ m_dataVarFrequence[F60HZ].end=90;
+ m_dataVarFrequence[F60HZ].scaleStruct[0].start=0;
+ m_dataVarFrequence[F60HZ].scaleStruct[1].start=50;
+ m_dataVarFrequence[F60HZ].scaleStruct[2].start=55;
+ m_dataVarFrequence[F60HZ].scaleStruct[0].end=100;
+ m_dataVarFrequence[F60HZ].scaleStruct[1].end=70;
+ m_dataVarFrequence[F60HZ].scaleStruct[2].end=65;
+ }
+
+KNutVarData::~KNutVarData(){
+}
+
+
+KNutVarData::VarStrucDef KNutVarData::getData (const int seqNumber) const {
+ int i = seqNumber;
+
+ if (i < 1) i = 1;
+ else {if (i > (knc::NumberOfTypes-1)) i = knc::NumberOfTypes - 1;};
+ return m_dataVar[i];
+ }
+
+
+
+QString KNutVarData::getNameAnalogData (const int seqNumber) {
+ if ((seqNumber >= 0) && (seqNumber < knc::NumberOfTypes))
+ return m_upsVarNameAnalog[seqNumber];
+ else
+ return "";
+ }
+
+
+void KNutVarData::putData (const int seqNumber, VarStrucDef& varStruc) {
+ if (seqNumber > 0 && seqNumber < knc::NumberOfTypes) m_dataVar[seqNumber] = varStruc;
+ }
+
+void KNutVarData::setVoltage (const int typeVoltage) {
+ if (typeVoltage == 230) {
+ m_dataVar[knc::VarUtility] = m_dataVarVoltage[U230V];
+ m_dataVar[knc::VarOutVolt] = m_dataVarVoltage[U230V];
+// m_dataVar[knc::VarOutVolt].nameAnalog = upsVarNameAnalog[knc::VarOutVolt]; // je nutno nastavit nazev
+ }
+ if (typeVoltage == 120) {
+ m_dataVar[knc::VarUtility] = m_dataVarVoltage[U120V];
+ m_dataVar[knc::VarOutVolt] = m_dataVarVoltage[U120V];
+// dataVar[knc::VarOutVolt].nameAnalog = upsVarNameAnalog[knc::VarOutVolt]; // je nutno nastavit nazev
+ }
+ m_dataVar[knc::VarOutVolt].nameAnalog = m_upsVarNameAnalog[knc::VarOutVolt]; // je nutno nastavit nazev
+ }
+
+void KNutVarData::setFrequency (const int typeFrequence) {
+ if (typeFrequence == 50) {
+ m_dataVar[knc::VarAcfreq] = m_dataVarFrequence[F50HZ];
+ m_dataVar[knc::VarOutFreq] = m_dataVarFrequence[F50HZ];
+ }
+ if (typeFrequence == 60) {
+ m_dataVar[knc::VarAcfreq] = m_dataVarFrequence[F60HZ];
+ m_dataVar[knc::VarOutFreq] = m_dataVarFrequence[F60HZ];
+ }
+ m_dataVar[knc::VarOutFreq].nameAnalog = m_upsVarNameAnalog[knc::VarOutFreq]; // je nutno nastavit nazev
+ }
+
+void KNutVarData::setXfer (const float lowXfer, const float highXfer) {
+ m_dataVar[knc::VarUtility].scaleStruct[1].start=(int)lowXfer;
+ m_dataVar[knc::VarUtility].scaleStruct[1].end=(int)highXfer;
+ m_dataVar[knc::VarOutVolt].scaleStruct[1].start=(int)lowXfer;
+ m_dataVar[knc::VarOutVolt].scaleStruct[1].end=(int)highXfer;
+ }
+
+
+const QString KNutVarData::errorToText (const int error) {
+
+ switch (error) {
+
+ // knutclient error
+ case KNutNet::LowMem: return i18n("No memory.");
+ case KNutNet::NullAddress: return i18n("No address.");
+ case KNutNet::NoSuchHost: return i18n("Unknown address.");
+ case KNutNet::SocketReadErr: // socket
+ case KNutNet::ConnectErr: // connect
+ return i18n("Error of connection.");
+
+ case KNutNet::CantConnect:
+ return i18n("No connection with server.");
+
+ case KNutNet::NutProtocolVarErr: return i18n("Server-client protocol or variables of NUT are unknown.");
+ case KNutNet::NoUpsHere: return i18n("No UPS on this address.");
+ case KNutNet::ConnectionRefused: return i18n("Connection was refused by server.");
+
+ case KNutNet::SendErr: return i18n("Server doesn't receive data.");
+ case KNutNet::RecvErr: return i18n("Server doesn't send data.");
+ case KNutNet::NoServerData: return i18n("Server doesn't answer.");
+
+ case KNutNet::UnknownFormat: return i18n("Server returns data with unknown format.");
+ case KNutNet::UnknownAnswer: return i18n("Server returns unknown data.");
+ case KNutNet::UnknownFormatVer: return i18n("Command VER returns data with unknown format.");
+
+ case KNutNet::NoData: return i18n("No data.");
+ case KNutNet::NotConnection: return i18n("Connection doesn't exist.");
+
+// server error
+ case KNutNet::AccessDenied: return i18n("Access denied. Failed password ?");
+ case KNutNet::DataStale: return i18n("UPS doesn't sent data to server (Data Stale).");
+ case KNutNet::UnknownCommand: return i18n("Server doesn't know this command.");
+
+// driver error
+ case KNutNet::DriverNotConnected: return i18n("UPS's driver isn't connected.");
+
+ case KNutNet::PasswordRequired: return i18n("Server required password.");
+ case KNutNet::PasswordIncorrect: return i18n("Incorrect password.");
+ case KNutNet::NoResponse: return i18n("UPS doesn't response.");
+ case KNutNet::CommandFailed: return i18n("Command failed.");
+ case KNutNet::UnknownInstCmd: return i18n("UPS doesn't know this instant command.");
+ case KNutNet::CmdNotSupported: return i18n("UPS doesn't support this instant command.");
+ case KNutNet::VarUnknown: return i18n("UPS doesn't known this variable.");
+ case KNutNet::VarNotSupported: return i18n("UPS doesn't support this variable.");
+ case KNutNet::InvalidValue: return i18n("UPS doesn't support this value in this variable.");
+ case KNutNet::UnknownUps: return i18n("Name of UPS is unknown.");
+
+ case KNutNet::AlreadySetUsername: return i18n("Username has been already entered.");
+ case KNutNet::AlreadySetPassword: return i18n("Password has been already entered.");
+
+ case KNutNet::NoListVars: return i18n("Server doesn't send list of variables.");
+
+//default
+ default: return i18n("Unknown error.");
+ }
+ }
+
+void KNutVarData::showError (const int error) {
+ KMessageBox::sorry (0,errorToText(error));
+ }
diff --git a/src/knutvardata.h b/src/knutvardata.h
new file mode 100755
index 0000000..6f112d5
--- /dev/null
+++ b/src/knutvardata.h
@@ -0,0 +1,261 @@
+/***************************************************************************
+ knutvardata.h - description
+ -------------------
+ begin : Tue Aug 21 2001
+ copyright : (C) 2001 by Daniel Prynych
+ email : Daniel@prynych.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#ifndef KNUTVARDATA_H
+#define KNUTVARDATA_H
+
+
+/*******************************/
+/* GLOBAL DEFINE */
+/*******************************/
+
+#define DEFAULT_BG_COLOR Qt::lightGray
+#define DEFAULT_FINGER_COLOR Qt::black
+#define DEFAULT_OK_COLOR Qt::green
+#define DEFAULT_WARNNING_COLOR Qt::yellow
+#define DEFAULT_ERROR_COLOR Qt::red
+#define DEFAULT_SCALE_COLOR Qt::black
+#define DEFAULT_FONT_COLOR Qt::black
+#define DEFAULT_KICON_COLOR Qt::white
+
+#include <klocale.h>
+
+#include "knutnet.h"
+#include "knutupsdata.h"
+#include "knutconst.h"
+
+#include <qcolor.h>
+#include <qfont.h>
+#include <qstring.h>
+
+
+// const char *nameUpsVars1[] = {
+// "NONE", "UTILITY", "BATTPCT", "UPSTEMP", "ACFREQ", "LOADPCT", "AMBTEMP", "AMBHUMID","BATTVOLT","OUTVOLT","CURRENT","BATT_TEMP","BATT_CURRENT"};
+
+// const char *nameUpsVars2[] = {
+// "none", "input.voltage", "battery.charge", "ups.temperature", "input.frequency", "ups.load", "ambient.temperature", "ambient.humidity","battery.voltage","output.voltage","output.current","battery.temperature","battery.current"};
+
+
+/**
+ *@author Daniel Prynych
+ */
+
+
+ /**
+ * Class contain data about analog panels,
+ * name, ..
+ * Describes view of panel.
+ * Trida obsahuje data o analogovych panelech,
+ * nazev, atd.
+ * Popisuje jak ma prislusny panel vypadat
+ *
+ * @author Daniel Prynych
+ * @short Information about analog panels
+ * @version 0.4
+ **/
+
+class QString;
+class QColor;
+class QFont;
+
+class KNutVarData {
+
+public:
+
+ enum mainWindowStartVariant{
+ mw_yes=0,
+ mw_no,
+ mw_auto
+ };
+
+struct ScaleStructDef {
+ int start;
+ int end;
+ int scaleColor;
+ };
+
+struct SettingDataDef {
+ int countCols;
+ int x;
+ int y;
+ int width;
+ int height;
+ QColor mainBackgroundColor;
+ QColor mPanelBackgroundColor;
+ QColor aPanelBackgroundColor;
+ QColor analogFingerColor;
+ QColor analogOKColor;
+ QColor analogWarnningColor;
+ QColor analogErrorColor;
+ QColor analogScaleColor;
+ QColor analogFontColor;
+ unsigned int panelFlags;
+ int inputVoltage;
+ int inputFrequency;
+ bool lowHighXfer;
+ bool areYouSure;
+ mainWindowStartVariant useMainWindow;
+ int useMessageWindow;
+ bool customBColor;
+ bool customBPanelColor;
+ bool customBAnalogColor;
+ bool customOAnalogColor;
+ QFont mPanelFont; // main panel font
+ QFont aPanelFont; // analog panel font
+ QFont systemFont; // system font
+ bool customFont; // use custom font
+ bool useDescription;
+ unsigned int toolTipFlags;
+ bool customKIconColor;
+ QColor kIconBackgroundColor;
+ int typeOfKIcon;
+ int typeDigitalProcessing;
+ bool activatedMainWindow;
+ };
+
+struct upsInfoDef{ //include generally informations about active (selected) UPS
+ KNutNet *upsNet; // pointer to instance of KNutNet
+ KNutUpsData::upsRecordDef record; // include information about information of ups (name, address, login, password ...)
+ int netError; // kod chyby pri spojeni // kode if error of conection
+ bool errorUpsData;
+ // state of connection to usbd, this isn't state of knutnet
+ knc::upsDriverConnection upsDriverState; // defined in knutconst.h
+ int oldState; // code of lost state of UPS kod posledniho stavu UPS
+ QString name;
+ QString password;
+ int nutVariables;
+ int nutProtocol;
+ QString runtimeVar;
+ QString lowxferVar;
+ QString highxferVar;
+ QString statusVar;
+ QString upsLoadVar;
+ bool reconnecting; // is true when program is in reconnecting stage
+ int reconnectCount;
+ };
+
+struct VarStrucDef {
+ QString nameAnalog; // jmeno promene v meraku napr. UPS Load
+ QString nameUnit; // merna jednotka napr %
+ int typeAnalog; //typ meraku
+ int numberItem; //pocet casti stupnice neni v souvislosti barvou
+ int numberInItem; //pocet casti stupnice uvnitr dilku stupnice
+ int start; // pocatecni hodnota v meraku
+ int end; // konecna hodnota v meraku
+ struct ScaleStructDef scaleStruct[5];
+ };
+
+
+ KNutVarData();
+ ~KNutVarData();
+
+ /**
+ * Gets data of analog measure panel, type of measure panel,
+ * Vrati data analogoveho mericiho panelu.
+ * typ meraku, pocet dilku stupnice, merici jedntotku atd
+ * data je mozno take nastavovat
+ * @param seqNumber Kod typu meraky.
+ * @return Data pro zadany typ panelu.
+ * @since 0.1
+ **/
+VarStrucDef getData (const int seqNumber) const;
+
+
+ /**
+ * Puts data of analog measure panel
+ * Nastavi data analogoveho mericiho panelu.
+ *
+ * @param seqNumber Kod typu meraky.
+ * @param data Data pro zadany typ panelu.
+ *
+ * @since 0.1
+ **/
+void putData (const int seqNumber, VarStrucDef& varStruc);
+
+ /**
+ * Sets data of analog measure panel for input and output voltage
+ * Nastavi data analogoveho mericiho panelu pro vstupni a vystupni napeti.
+ *
+ * @param typeVoltage Typ vstupniho napeti 230/120.
+ *
+ * @since 0.1
+ **/
+void setVoltage (const int typeVoltage);
+
+ /**
+ * Sets data of analog measure panel for input frequence
+ * Nastavi data analogoveho mericiho panelu pro vstupni frekvence.
+ *
+ * @param typeFrequence Typ vstupni frekvence 50/60.
+ *
+ * @since 0.1
+ **/
+void setFrequency (const int typeFrequence);
+
+ /**
+ * Nastavi vnitrni cast vybarveni podle low/high xfer,
+ * low/high-XFER udava rozpeti pri kterem UPS zpracovava napeti ze site.
+ *
+ * @param lowXfer Pocatecni hodnota.
+ * @param highXfer Konecna hodnota.
+ * @since 0.1
+ **/
+void setXfer (const float lowXfer, const float highXfer);
+
+ /**
+ * Vrati dlouhy nazev analogoveho panelu,
+ * je to jmeno merene veliciny
+ *
+ * @param seqNumber Kod typu merakuss.
+ * @since 0.1
+ **/
+QString getNameAnalogData (const int seqNumber);
+
+
+/**
+ * Prevede kod chyby na jeho textovou reprezentaci
+ *
+ * @since 0.2
+ **/
+ static const QString errorToText (const int error);
+
+
+/**
+ * Zobrazi jmeno chyby na zaklade jeho cisla.
+ *
+ * @since 0.1.2
+ **/
+ static void showError (const int error);
+
+
+private:
+
+ enum {aRegWhite,aRegGreen,aRegYellow,aRegRed,aRegBlue,aRegCyan,aRegMagenta,aRegBlack};
+
+ VarStrucDef m_dataVar[ knc::NumberOfTypes ]; /* udrzuje popis Anagovych meraku pro danou promenou jmeno zabarveni typ meraky */
+ VarStrucDef m_dataVarVoltage[2];
+ VarStrucDef m_dataVarFrequence[2];
+
+ static const int U230V = 0;
+ static const int U120V = 1;
+ static const int F50HZ = 0;
+ static const int F60HZ = 1;
+
+ QString m_upsVarNameAnalog[ knc::NumberOfTypes ];//array of strings - includes name of analog meters
+};
+
+#endif
diff --git a/src/lo16-app-knutclient.png b/src/lo16-app-knutclient.png
new file mode 100644
index 0000000..8b8d655
--- /dev/null
+++ b/src/lo16-app-knutclient.png
Binary files differ
diff --git a/src/lo16-app-knutclientconn.png b/src/lo16-app-knutclientconn.png
new file mode 100644
index 0000000..a9901e1
--- /dev/null
+++ b/src/lo16-app-knutclientconn.png
Binary files differ
diff --git a/src/lo16-app-knutclienterr.png b/src/lo16-app-knutclienterr.png
new file mode 100644
index 0000000..114fc95
--- /dev/null
+++ b/src/lo16-app-knutclienterr.png
Binary files differ
diff --git a/src/lo32-app-knutclient.png b/src/lo32-app-knutclient.png
new file mode 100644
index 0000000..2c6d538
--- /dev/null
+++ b/src/lo32-app-knutclient.png
Binary files differ
diff --git a/src/main.cpp b/src/main.cpp
new file mode 100644
index 0000000..d3dabec
--- /dev/null
+++ b/src/main.cpp
@@ -0,0 +1,78 @@
+/***************************************************************************
+ main.cpp - description
+ -------------------
+ begin : Út srp 21 19:12:20 CEST 2001
+ copyright : (C) 2001 by Daniel Prynych
+ email : Daniel.Prynych@alo.cz
+ ***************************************************************************/
+
+/***************************************************************************
+ * *
+ * This program is free software; you can redistribute it and/or modify *
+ * it under the terms of the GNU General Public License as published by *
+ * the Free Software Foundation; either version 2 of the License, or *
+ * (at your option) any later version. *
+ * *
+ ***************************************************************************/
+
+#include <kcmdlineargs.h>
+#include <kaboutdata.h>
+#include <kcmdlineargs.h>
+#include <klocale.h>
+#include <kapp.h>
+#include <kuniqueapplication.h>
+
+#include "knutclient.h"
+
+#include <stdio.h>
+#include <stdlib.h>
+
+static const char *description =
+ I18N_NOOP("Client for Network UPS Tool");
+// INSERT A DESCRIPTION FOR YOUR APPLICATION HERE
+
+
+static KCmdLineOptions options[] =
+{
+ {"nodock",I18N_NOOP("Don't dock in Kicker"),0},
+ { 0, 0, 0 }
+ // INSERT YOUR COMMANDLINE OPTIONS HERE
+};
+
+
+
+int main(int argc, char *argv[])
+{
+
+ KAboutData aboutData( "knutclient", I18N_NOOP("KNutClient"),
+ VERSION, description, KAboutData::License_GPL,
+ "(c) 2002 - 2009 Daniel Prynych", "Zajecov, Czech Republic", 0, "Daniel@prynych.cz");
+ aboutData.addAuthor("Daniel Prynych",0, "Daniel@prynych.cz","http://www.knut.noveradsl.cz/knutclient/");
+ aboutData.addCredit("Arnaud Quette",0,"arnaud.quette@free.fr","http://www.networkupstools.org/");
+ aboutData.addCredit("MGE",0,0,"http://opensource.mgeups.com");
+
+ KCmdLineArgs::init( argc, argv, &aboutData );
+ KCmdLineArgs::addCmdLineOptions( options ); // Add our own options.
+ KUniqueApplication::addCmdLineOptions();
+
+ KCmdLineArgs* args = KCmdLineArgs::parsedArgs();
+ bool noDock = args->isSet("dock");
+ args->clear();
+
+ // main KUApp this is remark
+ if (!KUniqueApplication::start()) {
+ fprintf(stderr,"Sorry : KNutClient is already running!\n");
+ exit(0);
+ }
+ KUniqueApplication a;
+
+// next line is for testing only.
+// I don't debug KUniqueApplication
+
+// KApplication a;
+//
+ KNutClient *knutclient = new KNutClient(!noDock);
+ int returnCode = a.exec();
+ delete knutclient;
+ return returnCode;
+}