summaryrefslogtreecommitdiffstats
path: root/src/knutnet.cpp
blob: f049a5288c4de30fd7feb05cec7b793adb4d84c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
/***************************************************************************
                          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 <tqtextstream.h>
#include <tqstring.h>
#include <tqcstring.h>
#include <tqtimer.h>


#include <unistd.h>  // for function sleep

//#include <iostream>



/****** CONSTS ***********/

//const TQ_ULONG rBufferLen = 1024;



KNutNet::KNutNet (const TQString upsAddress, const TQString upsName, const unsigned short port, unsigned int countRepeat, const unsigned  int delay)
        : TQObject(), m_upsAddress(upsAddress), m_upsName(upsName), m_countRepeat(countRepeat), m_port(port), m_delay(delay)  {


//tqDebug ("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 TQTimer( this );
  connect( m_unConnectTimer, TQT_SIGNAL(timeout()), this, TQT_SLOT(slotTimerReconnect()) );

  m_error = NoError;

  m_commandSocket = new TQSocket( this );
  connect( m_commandSocket, TQT_SIGNAL( hostFound()),this, TQT_SLOT( slotHostFound()));
  connect( m_commandSocket, TQT_SIGNAL( connected()),this,TQT_SLOT( slotConnected()));
  connect( m_commandSocket, TQT_SIGNAL( connectionClosed()),this, TQT_SLOT( slotConnectionClosed()));
  connect( m_commandSocket, TQT_SIGNAL( error(int)),this, TQT_SLOT( slotConnectionError(int)));
  }


KNutNet::~KNutNet(){
  TQCString  inBuffer;
  TQString  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;
  TQCString  inBuffer;
  TQString  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() == TQSocket::Closing ) {
      connect( m_commandSocket, TQT_SIGNAL(delayedCloseFinished()),this,TQT_SLOT(slotClosed()) );
      }
    else {
      slotClosed();
      }
    }
  }

void KNutNet::slotClosed (void) {

  disconnect( m_commandSocket,TQT_SIGNAL(delayedCloseFinished()),this, TQT_SLOT(slotClosed()) );
  m_state = Idle;
  }


void KNutNet::open (void) {

  TQCString  inBuffer;
  TQString  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() != TQSocket::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 TQString upsAddress, const TQString 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 TQString command, const TQString userName, const TQString password, const bool onlyCommand) {
  m_error=0; // vynulujeme chyby

  if (m_state == Connected) {
    TQString 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 TQString variable, const TQString value, const TQString userName, const TQString password, const bool onlyVariable) {
  m_error=0; // vynulujeme chyby
  if (m_state == Connected) {
    TQString outBuffer;
    TQString 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 TQString name, struct upsVarDef& allVar) {
  m_error =0;
  if (m_state == Connected) {
      TQValueVector<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;
    TQValueVector<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;
  }


TQString KNutNet::readStringVar (const TQString name) {

  m_error =0;
  if (m_state == Connected) {
      TQValueVector<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;
}


TQString KNutNet::readEnumValueVar (const TQString name, const int valueNumber) {

  m_error =0;
  if (m_state == Connected) {
//    #if defined  (TDE_VERSION_MAJOR)
//      #if TDE_VERSION_MAJOR >= 3
        TQValueVector<upsVarDef>::const_iterator it;
//      #else
//        TQValueList<upsVar>::ConstIterator it;
//      #endif
//    #else
//      TQValueList<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 TQString name ) {
  return activate (name,true);
  }


int KNutNet::unSetActivate ( const TQString name ) {
  return activate (name,false);
  }


int KNutNet::unSetActivateAll ( void ) {
  return activateAll (false);
  }


int KNutNet::existName ( const TQString name ) {

  m_error =0;
  if (m_state == Connected) {
        TQValueVector<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) {
  TQCString  inBuffer;
  TQString  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) {
          TQString firstNumber= outBuffer.left(n);
          TQString 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 (TQString& firstUpsName) {
  TQCString  inBuffer;
  TQString  outBuffer;
  TQString  varOutBuffer;
  int lenString;

  m_error=0;
  inBuffer = "LIST UPS\n";
  if (!(m_error=getUpsData (inBuffer,outBuffer,"END LIST UPS"))) {

    TQString inLine, upsNameRet, varName, value;
    int key, typeValue;
    bool beginList = false;
    TQTextIStream 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 TQString line) {

  TQString 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;
  }

TQString KNutNet::parseValue (const TQString 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();
    TQString 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 (TQString line, int& lenString ) {
  int ret=0;
  TQString word;

  lenString = 0;
  if (line.isEmpty()) return 0;
  TQTextIStream 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(TQString& line, TQString& upsName ,TQString& varName, TQString& value, int& typeValue, int& lenString) {
  int posChar;
  TQString 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 TQCString  inBuffer, TQString& upsDescription) {
  TQString  outBuffer;

  if (!(m_error=getUpsData (inBuffer,outBuffer))) {
    outBuffer=outBuffer.stripWhiteSpace ();
    TQString 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) {
  TQ_ULONG rMaxLen; 
  TQCString  recvBuffer(rBufferLen);
  TQ_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 TQCString sBuffer, TQString& rBuffer, const TQCString endString) {

  //rbufferLen a sbufferLen are maximal value of buffers
  TQCString  recvBuffer(rBufferLen);
  TQ_LONG lengthInputData;
  TQ_ULONG dataAvailable;


  TQMutexLocker 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 TQ_LONG defined like _int64 and
    //for other environments is TQ_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.data()) == -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 TQString varName, const bool valueType, const int varMax, TQValueVector<TQString>* enumValues) {
      TQValueVector<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 TQString name, const TQString 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  (TDE_VERSION_MAJOR)
//    #if TDE_VERSION_MAJOR >= 3
      TQValueVector<upsVarDef>::iterator it;
//    #else
//      TQValueList<upsVar>::Iterator it;
//    #endif
//  #else
//    TQValueList<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 (TQString value) {
  m_upsStatusVar = 0;
  TQTextIStream inputStream(&value);
  TQString 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)) {
    TQCString  inBuffer;
    TQString  outBuffer;

     TQValueVector<upsVarDef>::iterator itv;
     TQValueVector<upsICommDef>::iterator itc;
     for (itv = m_listVars.begin(); itv != m_listVars.end(); itv++) {
      //nacteme promenou
      inBuffer = "VARDESC " + (*itv).upsVarName.local8Bit() + "\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.local8Bit()+"\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)) {
    TQCString  inBuffer;
    TQString  outBuffer;
    TQString upsNameRet;
    TQString varName;
    TQString value;
    int typeValue;
    int lenString;

     TQValueVector<upsVarDef>::iterator itv;
     TQValueVector<upsICommDef>::iterator itc;
     for (itv = m_listVars.begin(); itv != m_listVars.end(); itv++) {
      //nacteme promenou
      inBuffer = "GET DESC " + m_upsName.local8Bit() + " " + (*itv).upsVarName.local8Bit()+"\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.local8Bit() + " " + (*itc).upsCommName.local8Bit()+"\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
  TQCString  inBuffer;
  TQString  outBuffer;
  TQString  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.local8Bit());
    inBuffer.append("\n");
    }
  else inBuffer ="LISTVARS\n";

  if (!(m_error=getUpsData (inBuffer,outBuffer))) {
    outBuffer=outBuffer.stripWhiteSpace ();
    if (outBuffer.length() > 0) {
    // precteme data
      TQTextIStream inputStream(&outBuffer);
      TQString 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.local8Bit());
    inBuffer.append("\n");
    }
  else inBuffer ="LISTRW\n";

  if (!(m_error=getUpsData (inBuffer,outBuffer))) {
    outBuffer=outBuffer.stripWhiteSpace();
    if (!outBuffer.isEmpty()) {
    // precteme data
      TQTextIStream inputStream(&outBuffer);
      TQString 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.local8Bit());
          if (!m_upsName.isEmpty()) {
            inBuffer.append("@"); // pokud upsName neni je vzdy nastaveno na null
            inBuffer.append(m_upsName.local8Bit());
            }
          inBuffer.append("\n");
          if (!(m_error=getUpsData (inBuffer,varOutBuffer))) {
            varOutBuffer=varOutBuffer.stripWhiteSpace();
            if ( !outBuffer.isEmpty() ) {
              TQTextIStream varInputStream(&varOutBuffer);
              TQString 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 ******************

          TQValueVector<TQString>* enumString=0;
          if (!valueType) {
          // nacteme enum hodnoty
            inBuffer="ENUM ";
            inBuffer.append(word.local8Bit());
            // pokud existuje pridame jmeno UPS-ky
            if (!m_upsName.isEmpty()) {
              inBuffer.append("@");
              inBuffer.append(m_upsName.local8Bit());
              }
            inBuffer.append("\n");
            if (!(m_error=getUpsData (inBuffer,varOutBuffer,"END\n"))) {
//               varOutBuffer.stripWhiteSpace();  nemuze provest protoze bychom si odstranili konce radek
              if (!varOutBuffer.isEmpty()) {
                TQString inLine, word1, word2;
                TQTextIStream 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 TQValueVector<TQString>;
                      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.local8Bit());
    inBuffer.append("\n");
    }
  else inBuffer ="LISTINSTCMD\n";

  if (!(m_error=getUpsData (inBuffer,outBuffer))) {
    outBuffer=outBuffer.stripWhiteSpace ();
    if ( !outBuffer.isEmpty() ) {
      // precteme data
      TQTextIStream inputStream(&outBuffer);
      TQString 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) {
  TQCString  inBuffer;
  TQString  outBuffer;
  TQString  varOutBuffer;
  upsVarDef upsVar;
  upsICommDef upsIComm;
  int key;
  int typeValue;
  int lenString;
  int varMax=0;

  TQValueVector<TQString>* enumString=0;
  inBuffer = "LIST VAR " + m_upsName.local8Bit() + "\n";
  if (!(m_error=getUpsData (inBuffer,outBuffer,"END LIST VAR"))) {
    TQString inLine, upsNameRet, varName, varNameRet, value;
    bool beginList = false;
    TQTextIStream 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.local8Bit() + " " + varName.local8Bit() +"\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.local8Bit() + " " + varName.local8Bit() +"\n";
                    if (!(m_error=getUpsData (inBuffer,varOutBuffer,"END LIST ENUM"))) {
                      bool beginEnumList = false;
                      TQTextIStream 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 TQValueVector<TQString>;
                            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.local8Bit() + "\n";
  if (!(m_error=getUpsData (inBuffer,outBuffer,"END LIST CMD"))) {

    TQString inLine, upsNameRet, varName, value;
    int key, typeValue;
    bool beginList = false;
//std::cout << "CMD Buffer " << outBuffer  << std::endl;

    TQTextIStream 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
    TQString endChar;
    TQCString  inBuffer;
    TQString  outBuffer;
    TQValueVector<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.local8Bit());
        if (!m_upsName.isEmpty()) { // pokud upsName neni je vzdy nastaveno na null
          inBuffer.append("@");
          inBuffer.append(m_upsName.local8Bit());
          }
        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() ) {
            TQTextIStream inputStream(&outBuffer);
            TQString 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
  TQString varName;
  TQString upsNameRet;
  TQString value;
  int typeValue;
  int lenString;

  // reads value of variables
  TQCString  inBuffer;
  TQString  outBuffer;
  TQValueVector<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.local8Bit()+" "+(*it).upsVarName.local8Bit()+"\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 TQString command, const TQString arg1, const TQString arg2, const bool useUpsName) {
  int localError;
// nenastavi promenou error ale nenuluje ji
  TQCString inBuffer;
  TQString outBuffer;

  switch (m_nutProtocol) {
    case 1:
      inBuffer=command.local8Bit() + " " + arg1.local8Bit();
      if (useUpsName && (!m_upsName.isEmpty())) { // pokud upsName neni je vzdy prazdne
        inBuffer += "@"+m_upsName.local8Bit();
      }
      if (!arg2.isEmpty()) {
        inBuffer += " " + arg2.local8Bit();
      }
      break;
    case 2:
      inBuffer = command.local8Bit() + " ";
      if (useUpsName) {
        inBuffer += m_upsName.local8Bit() + " ";
      }
      inBuffer.append(arg1.local8Bit());
      if (!arg2.isEmpty()) {
        inBuffer += " \"" + arg2.local8Bit() +"\"";
      }
      break;
    }
  inBuffer.append("\n");

  if (!(localError=getUpsData (inBuffer,outBuffer))) {
    outBuffer=outBuffer.stripWhiteSpace();
    TQTextIStream inputStream(&outBuffer);
    TQString 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 TQString name, const bool setActivate  ) {
  m_error =0;
  if (m_state == Connected) {
    TQValueVector<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) {
    TQValueVector<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 TQString 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 TQString 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;
//tqDebug ("--KNutNet::slotConnectionError");

  m_state = ConnectError;
  m_unConnectTimer->stop();
  if (error == TQSocket::ErrHostNotFound) {
    error = NoSuchHost;
    emit connectionError(error);
    return;
    }
                        //connection was refused                                  //  no connection
  if ((error == TQSocket::ErrConnectionRefused) && (m_commandSocket->state()==TQSocket::Idle)) {
    if (m_firstConnect) {
      if (m_numberConnection < m_countRepeat) {
        m_numberConnection++;
//    tqDebug ("--KNutNet:: connect error - try connect on next time");
        m_unConnectTimer->start( m_delay, TRUE );
        }
      else  {
        // i don't connect server
        error=CantConnect;
//        tqDebug("--KNutNet::emit - connection error ");
        emit connectionError(error);
        return;
        }
      } // end of if (firstConnection)
    else {
      // connecting is down, try repeated connection

//    tqDebug ("--KNutNet::no first connect connection error ");
      m_unConnectTimer->start( m_delay, TRUE );
      }
    return;
    }
  if (error == TQSocket::ErrConnectionRefused) {
    error = ConnectionRefused;
//    std::cout << "--KNutNet::connection error ErrConnectionRefused " << TQSocket::Idle << " - " << error << std::endl;
    emit connectionError(error);
    return;
    }
  if (error ==   TQSocket::ErrSocketRead) {
    error = SocketReadErr;
//    std::cout << "--KNutNet::connection error TQSocket::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() == TQSocket::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() == TQSocket::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()==TQSocket::Idle) {
  //std::cout << "--KNutNet::slotTimerReconnect TQSOcket::Idle" << std::endl;
     emit tryRepeatFirstConnection(m_numberConnection);
   //  std::cout << "KNutNet::emit-tryRepeatFirstConnection" << std::endl;
    m_state=Connecting;
    if ( m_commandSocket->state() != TQSocket::Connecting )
      m_commandSocket->connectToHost(m_upsAddress,m_port);
    }
  }


#include "knutnet.moc"