summaryrefslogtreecommitdiff
path: root/demo/netware/nutconnection.pp
blob: 3730c924caa4189884e9d6d3d1de5f6e72e87b2d (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
unit nutconnection;
{
    This file is part of nutmon for netware
    Copyright (c) 2004 armin diehl (armin@freepascal.org)

    Simple class to connect to the nut upsd, see
    http://www.networkupstools.org for details about the
    protocol

    Tested with nut 2.0.1pre4

    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.

 **********************************************************************}
{$mode objfpc}

interface

uses sysutils, ssockets;

Const
  NutDefaultPort = 3493;
  NutLineEnd    = #10;
  NutDataStale = 'ERR DATA-STALE';

type
  TNutException = class (Exception);
  TUpsStat   = (UPS_disconnected,UPS_stale,UPS_online,UPS_onBatt,UPS_lowBatt,UPS_FSD);
  TUpsStatus = set of TUpsStat;
  TNutConnection = class (TObject)
    private
     fSock : TInetSocket;
     fHost : string;
     fPort : word;
     fUpsName,fUserName,fPassword : string;
     fLogin : boolean;
     fDebug : boolean;
     fLastResponse : string;

      function isConnected : boolean;
      procedure doConnect (c : boolean);
      procedure setHost (s : string);
      procedure setPort (w : word);
      procedure sendCommand (s : string);
      function getOneLine : string;
      function getVersion : string;
      procedure setUpsName (s : string);
      procedure checkConnected;
      function getValue (name : string) : string;
      function getUpsLoad : string;
      function getUpsMfr : string;
      function getUpsModel : string;
      function getUpsRuntime : string;
      function getUpsCharge : string;
      function getUpsChargeInt : integer;
      function getUpsTemperature : string;
      function getInputFrequency : string;
      function getInputVoltage : string;
      function getOutputVoltage : string;
      function getUpsStatus : TUpsStatus;
      procedure setUserName (user : string);
      procedure setPassword (pwd : string);
      procedure doLogin (login : boolean);
      function getNumLogins : string;
    public
      property connected : boolean read isConnected write doConnect;
      property host : string read fHost write setHost;
      property port : word read fPort write setPort;
      property version : string read getVersion;
      property upsName : string read fUpsName write setUpsName;
      property upsload : string read getUpsLoad;
      property upsMfr : string read getUpsMfr;
      property upsModel : string read getUpsModel;
      property upsRuntime : string read getUpsRuntime;
      property upsCharge : string read getUpsCharge;
      property upsChargeInt : integer read getUpsChargeInt;
      property upsTemperature : string read getUpsTemperature;
      property upsInputFrequency : string read getInputFrequency;
      property upsInputVoltage : string read getInputVoltage;
      property upsOutputVoltage : string read getOutputVoltage;
      property upsStatus : TUpsStatus read getUpsStatus;
      property Username : string read fUsername write setUsername;
      property Password : string read fPassword write setPassword;
      // in case login is set to true (and username,password are ok)
      // upsd knows that this system gets power from the ups and
      // will switch off only after login was set to false
      property Login : boolean read fLogin write doLogin;
      property Debug : boolean read fDebug write fDebug;
      property LastResult : string read fLastResponse;
      property numLogins : string read getNumLogins;
  end;

function UpsStatus2Txt (status : TUpsStatus) : string;

implementation

function TNutConnection.isConnected : boolean;
begin
  result := (fSock <> nil);
end;

procedure TNutConnection.doConnect (c : boolean);
begin
  if fSock <> nil then
  begin
    fSock.Free;
    fSock := nil;
    fLogin := false;
  end;
  if c then
    fSock := TInetSocket.Create (fHost, fPort);
end;


procedure TNutConnection.setHost (s : string);
begin
  if fHost <> s then
  begin
    fHost := s;
    doConnect (isConnected);
  end;
end;

procedure TNutConnection.setPort (w : word);
begin
  if w <> fPort then
  begin
    fPort := w;
    doConnect (isConnected);
  end;
end;

procedure TNutConnection.checkConnected;
begin
  if not isConnected then
    raise (TNutException.Create ('not connected'));
end;

procedure TNutConnection.sendCommand (s : string);
var len : longint;
begin
  checkConnected;
  if fDebug then
    writeln (stderr,'S: "'+s+'"');
  s := s + NutLineEnd;
  len := fSock.Write (s[1],length(s));
  if (len <> length(s)) then
  begin
    if fDebug then
      writeln (stderr,'send error');
    doConnect (false);
    raise (TNutException.Create ('send failed, disconnected from upsd'));
  end;
end;

function TNutConnection.getOneLine : string;
var c : char;
begin
  checkConnected;
  fLastResponse := '';
  result := '';
  while (fSock.read (c,1) = 1) do
  begin
    if c = NutLineEnd then
    begin
      if fDebug then
        writeln (stderr,'R: "'+result+'"');
      fLastResponse := result;
      exit;
    end;
    result := result + c;
  end;
end;

function TNutConnection.getVersion : string;
begin
  sendCommand ('VER');
  result := getOneLine;
end;


procedure TNutConnection.setUpsName (s : string);
var res : string;
begin
  fUpsName := '';
  sendCommand ('GET NUMLOGINS '+s);
  res := getOneLine;
  if copy (res,1,10) <> 'NUMLOGINS ' then
    Raise (TNutException.Create ('setUpsName, unknown response from upsd'));
  fUpsName := s;
end;

function TNutConnection.getValue (name : string) : string;
var s : string;
begin
  if fUpsName = '' then
    raise (TNutException.Create ('upsName not set'));
  sendCommand ('GET VAR '+fUpsName+' '+name);
  s := getOneLine;
  if s = 'ERR DATA-STALE' then
  begin
    result := s;
    exit;
  end;
  if copy (s,1,4) <> 'VAR ' then
    raise (TNutException.Create ('result from GET VAR invalid, does not begin with "VAR "'));
  delete (s,1,4);
  if ansiUpperCase (copy (s,1,length(fUpsName))) <> ansiUpperCase (fUpsName) then
    raise (TNutException.Create ('result from GET VAR invalid, second param was not upsName'));
  delete (s,1,length(fUpsName)+1);
  delete (s,1,length(name)+1);
  if copy (s,1,1) = '"' then delete (s,1,1);
  if copy (s,length(s),1) = '"' then delete (s,length(s),1);
  result := s;
end;

function TNutConnection.getUpsLoad : string;
begin
  result := getValue ('ups.load');
end;

function TNutConnection.getUpsMfr : string;
begin
  result := getValue ('ups.mfr');
end;

function TNutConnection.getUpsModel : string;
begin
  result := getValue ('ups.model');
end;

function TNutConnection.getUpsRuntime : string;
begin
  result := getValue ('battery.runtime');
end;

function TNutConnection.getUpsCharge : string;
begin
  result := getValue ('battery.charge');
end;


function TNutConnection.getUpsChargeInt : integer;
var s : string;
    p : integer;
begin
  try
    s := getUpsCharge;
    p := Pos ('.',s);
    if p > 0 then
      delete (s,p,255);
    result := StrToInt (s);
  except
    result := 100;
  end;
end;

function TNutConnection.getUpsTemperature : string;
begin
  result := getValue ('ups.temperature');
end;

function TNutConnection.getInputFrequency : string;
begin
  result := getValue ('input.frequency');
end;

function TNutConnection.getInputVoltage : string;
begin
  result := getValue ('input.voltage');
end;

function TNutConnection.getOutputVoltage : string;
begin
  result := getValue ('output.voltage');
end;

function TNutConnection.getNumLogins : string;
var res : string;
    p : integer;
begin
  if fUpsName = '' then
    Raise (TNutException.Create ('getNumLogins, upsName not set'));
  sendCommand ('GET NUMLOGINS '+fUpsName);
  res := getOneLine;
  if copy (res,1,10) <> 'NUMLOGINS ' then
    Raise (TNutException.Create ('setUpsName, unknown response from upsd'));
  delete (res,1,10);
  p := pos (' ',res);
  if p > 0 then
    delete (res,1,p);
  result :=res;
end;

function TNutConnection.getUpsStatus : TUpsStatus;
var s,value : string;
    i : integer;
begin
  try
    s := getValue ('ups.status');
    result := [];
    if s = NutDataStale then
      result := [UPS_stale]
    else
    repeat
      i := pos (' ',s);
      if (i > 0) then
      begin
        value := trim(ansiuppercase(copy(s,1,i-1)));
        delete (s,1,i); s:=trim(s);
      end else
      begin
        value := trim(ansiuppercase(s));
        s := '';
      end;
      if value = 'OL' then
        result := result + [UPS_online]
      else if value = 'OB' then
        result := result + [UPS_onBatt]
      else if value = 'LB' then
        result := result + [UPS_LowBatt]
      else if value = 'FSD' then
        result := result + [UPS_FSD];
    until s = '';
  except
    result := [UPS_disconnected];
  end;
end;


procedure TNutConnection.setUserName (user : string);
var res : string;
begin
  fUserName := user;
  if fUserName <> '' then
  begin
    sendCommand ('USERNAME '+user);
    res := getOneLine;
    if res <> 'OK' then
      raise (TNutException.Create (format ('username failed (%s)',[res])));
  end;
end;

procedure TNutConnection.setPassword (pwd : string);
var res : string;
begin
  fPassword := pwd;
  if pwd <> '' then
  begin
    sendCommand ('PASSWORD '+pwd);
    res := getOneLine;
    if res <> 'OK' then
      raise (TNutException.Create (format ('password failed (%s)',[res])));
  end;
end;

procedure TNutConnection.doLogin (login : boolean);
var res : string;
begin
  if login then
  begin
    if fLogin then
      raise (TNutException.Create ('already logged in'));
    if (fUsername = '') or (fPassword = '') or (fUpsName = '') then
      raise (TNutException.Create ('Login requires UpsName, Username and Password'));
    sendCommand ('LOGIN '+fUpsName);
    res := getOneLine;
    if res <> 'OK' then
      raise (TNutException.Create (format ('login failed (%s)',[res])));
    fLogin := true;
  end else
  if fLogin then
  begin
    sendCommand ('LOGOUT');
    res := getOneLine;
    if (copy(res,1,2) <> 'OK') and (copy(res,1,6)<> 'Goodby') then
      raise (TNutException.Create (format('logout failed, got "%s"',[res])));
    fLogin := false;
    doConnect(false);
  end;
end;

function UpsStatus2Txt (status : TUpsStatus) : string;
begin
  result := '';
  if UPS_disconnected in status then result := result + 'disconnected ';
  if UPS_stale        in status then result := result + 'stale ';
  if UPS_online       in status then result := result + 'online ';
  if UPS_onBatt       in status then result := result + 'onBattery ';
  if UPS_lowBatt      in status then result := result + 'LowBattery ';
  if UPS_FSD          in status then result := result + 'ForeceShutdown ';
  result := trim(result);
end;


end.