BatteryModel-Linux.m 16.9 KB
Newer Older
1 2 3
/*
   Project: batmon

4
   Copyright (C) 2006-2015 GNUstep Application Project
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

   Author: Riccardo Mottola 

   Created: 2013-07-23 Riccardo Mottola

   This application 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 application 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
   Library General Public License for more details.

   You should have received a copy of the GNU General Public
   License along with this library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA.
*/

25 26 27
#if defined(linux)

#import <Foundation/Foundation.h>
28 29 30 31
#import "BatteryModel.h"

@implementation BatteryModel (PlatformSpecific)

32 33 34 35 36 37 38 39 40 41 42 43 44 45
- (void)_readLine :(FILE *)f :(char *)l
{
  int ch;
    
  ch = fgetc(f);
  while (ch != EOF && ch != '\n')
    {
      *l = ch;
      l++;
      ch = fgetc(f);
    }
  *l = '\0';
}

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
- (void)initPlatformSpecific
{
  NSFileManager       *fm;
  NSArray             *dirNames;
  NSEnumerator        *en;
  NSString            *dirName;
  BOOL                done;
  FILE                *stateFile;
  char                presentStr[16];
  char                line[128];

  useACPIproc = NO;
  useACPIsys  = NO;
  useAPM      = NO;
  usePMU      = NO;

  /* look for a battery */
  fm = [NSFileManager defaultManager];
  dirNames = [fm directoryContentsAtPath:DEV_SYS_POWERSUPPLY];
  if (dirNames != nil && [dirNames count] > 0)
    {
      done = NO;
      en = [dirNames objectEnumerator];
      while (done == NO)
        {
          dirName = [en nextObject];
          if (dirName != nil)
            {
              NSString *presentFileName;
              FILE *presentFile;

              /* scan for the first present battery */
              presentFileName = [dirName stringByAppendingPathComponent:@"present"];

              [[DEV_SYS_POWERSUPPLY stringByAppendingPathComponent:presentFileName] getCString:batteryStatePath0];
              NSLog(@"/sys checking: %s", batteryStatePath0);
              presentFile = fopen(batteryStatePath0, "r");
              if (presentFile != NULL)
                {
                  [self _readLine :presentFile :line];
                  if (!strcmp(line, "1"))
                    {
                      done = YES;
                      NSLog(@"/sys: found it!: %@", [DEV_SYS_POWERSUPPLY stringByAppendingPathComponent:dirName]);
                      batterySysAcpiString = [[DEV_SYS_POWERSUPPLY stringByAppendingPathComponent:dirName] retain];
                    }
                  fclose(presentFile);
                  useACPIsys = YES;
                }           
            }
          else
            {
              done = YES;
            }
        }
    }
  else
    {
      NSLog(@"No /sys, trying /proc/acpi");
      dirNames = [fm directoryContentsAtPath:@"/proc/acpi/battery"];
      if (dirNames != nil && [dirNames count] > 0)
        {
          done = NO;
          en = [dirNames objectEnumerator];
          while (done == NO)
            {
              dirName = [en nextObject];
              if (dirName != nil)
                {
                  /* scan for the first present battery */
116
                  dirName = [@"/proc/acpi/battery" stringByAppendingPathComponent:dirName];
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
                  [dirName getCString:batteryStatePath0];
                  strcat(batteryStatePath0, "/state");
                  NSLog(@"checking: %s", batteryStatePath0);
                  stateFile = fopen(batteryStatePath0, "r");
                  if (stateFile != NULL)
                    {
                      [self _readLine :stateFile :line];
                      sscanf(line, "present: %s", presentStr);
                      if (!strcmp(presentStr, "yes"))
                        {
                          done = YES;
                          NSLog(@"/proc found it!: %@", dirName);
                          [dirName getCString:batteryInfoPath0];
                          strcat(batteryInfoPath0, "/info");
                        }
                      fclose(stateFile);
                      useACPIproc = YES;
                    }           
                }
	      else
                {
                  done = YES;
                }
            }
        }
      else
        {
          /* no acpi, but maybe apm */
          if([fm fileExistsAtPath:@"/proc/apm"] == YES)
            {
              NSLog(@"found apm");
              useAPM = YES;
              strcpy(apmPath, "/proc/apm");
            }
          else
            {
              dirNames = [fm directoryContentsAtPath:DEV_PROC_PMU];
              if (dirNames != nil && [dirNames count] > 0)
                {
                  NSLog(@"Found PMU");
                  usePMU = YES;
                  useWattHours = NO;
                }
            }
        }
    }
}

- (void)updatePlatformSpecific
{
  FILE *stateFile;
  FILE *infoFile;
  char line[128];
    
  char presentStr[16];
  char stateStr[16];
  char chStateStr[16];
  char rateStr[16];
  char capacityStr[16];
  char voltageStr[16];
  int  rateVal;
  int  capacityVal;
  int  voltageVal;
  NSString *chargeStateStr;

  char present2Str[16];
  char desCapStr[16];
  char lastCapStr[16];
  char batTypeStr[16];
  char warnCapStr[16];

  batteryState = 0;

  if (useACPIsys)
    {
      NSString *ueventFileName;
      NSMutableDictionary *ueventDict;
      NSString *lineStr;
      NSRange  sepRange;
      NSString *valueStr;
      NSString *keyStr;


      //	NSLog(@"reading %@", batterySysAcpiString);
      ueventFileName = [batterySysAcpiString stringByAppendingPathComponent:@"uevent"];

      [ueventFileName getCString:batteryStatePath0];
      stateFile = fopen(batteryStatePath0, "r");
      if (stateFile == NULL)
	{
	  batteryState = BMBStateMissing;
	  watts = 0;
	  amps = 0;
	  volts = 0;
	  chargePercent = 0;
	  currCap = 0;
	  timeRemaining = -1;
	  NSLog(@"acpi /sys state file is null");
	  return;
	}

      ueventDict = [[NSMutableDictionary alloc] initWithCapacity: 4];

      [self _readLine :stateFile :line];
      lineStr = [NSString stringWithCString: line];
      while ([lineStr length] > 0)
	{
	    
	  sepRange = [lineStr rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString:@"="]];
	  if (sepRange.location != NSNotFound)
	    {
	      keyStr = [lineStr substringToIndex: sepRange.location];
	      valueStr = [lineStr substringFromIndex: sepRange.location+1];
	      [ueventDict setObject: valueStr forKey: keyStr];
	    }
	  [self _readLine :stateFile :line];
	  lineStr = [NSString stringWithCString: line];
	}

//        NSLog(@"%@", ueventDict);
      
      amps = [[ueventDict objectForKey:@"POWER_SUPPLY_CURRENT_NOW"] floatValue] / 1000000;
      if (isnan(amps))
	amps = 0;
      volts = [[ueventDict objectForKey:@"POWER_SUPPLY_VOLTAGE_NOW"] floatValue] / 1000000;
      if ([ueventDict objectForKey:@"POWER_SUPPLY_POWER_NOW"] == nil)
	watts = volts*amps;
      else
	{
	  watts = [[ueventDict objectForKey:@"POWER_SUPPLY_POWER_NOW"] floatValue] / 1000000;
	  if (isnan(watts))
	    watts = 0;
	  if (volts > 0)
	    amps = watts / volts;
	}

      useWattHours = YES;
      if ([ueventDict objectForKey:@"POWER_SUPPLY_ENERGY_FULL_DESIGN"] != nil)
	{
	  desCap = [[ueventDict objectForKey:@"POWER_SUPPLY_ENERGY_FULL_DESIGN"] floatValue] / 1000000;
	  lastCap = [[ueventDict objectForKey:@"POWER_SUPPLY_ENERGY_FULL"] floatValue] / 1000000;
	  currCap = [[ueventDict objectForKey:@"POWER_SUPPLY_ENERGY_NOW"] floatValue] / 1000000;
	}
      else
	{
	  desCap = [[ueventDict objectForKey:@"POWER_SUPPLY_CHARGE_FULL_DESIGN"] floatValue] / 1000000;
	  lastCap = [[ueventDict objectForKey:@"POWER_SUPPLY_CHARGE_FULL"] floatValue] / 1000000;
	  currCap = [[ueventDict objectForKey:@"POWER_SUPPLY_CHARGE_NOW"] floatValue] / 1000000;
	  useWattHours = NO;
	}
      warnCap = 0; // FIXME

      chargeStateStr = (NSString *)[ueventDict objectForKey:@"POWER_SUPPLY_STATUS"];
      batteryType = (NSString *)[ueventDict objectForKey:@"POWER_SUPPLY_TECHNOLOGY"];
      batteryManufacturer = (NSString *)[ueventDict objectForKey:@"POWER_SUPPLY_MANUFACTURER"];

      isCharging = NO;
      if ([chargeStateStr isEqualToString:@"Charging"])
	{
	  if (useWattHours)
	    {
	      if (amps > 0)
		timeRemaining = (lastCap-currCap) / watts;
	      else
		timeRemaining = -1;
	    }
	  else
	    {
	      if (watts > 0)
		timeRemaining = (lastCap-currCap) / amps;
	      else
		timeRemaining = -1;
	    }
	  chargePercent = currCap/lastCap*100;
	  isCharging = YES;
	  batteryState = BMBStateCharging;
	}
      else if ([chargeStateStr isEqualToString:@"Discharging"])
	{
	  if (useWattHours)
	    {
	      if (amps > 0)
		timeRemaining = currCap / watts;
	      else
		timeRemaining = -1;
	    }
	  else
	    {
	      if (watts > 0)
		timeRemaining = currCap / amps;
	      else
		timeRemaining = -1;
	    }
	  chargePercent = currCap/lastCap*100;
	  batteryState = BMBStateDischarging;
	}
      else if ([chargeStateStr isEqualToString:@"Charged"] || [chargeStateStr isEqualToString:@"Full"])
	{
	  chargePercent = 100;
	  timeRemaining = 0;
	  isCharging = YES;
	  batteryState = BMBStateFull;
	}
      else if ([chargeStateStr isEqualToString:@"Unknown"])
	{
	  timeRemaining = 0;
	  if (amps == 0)
	    {
	      chargePercent = 100;
	      isCharging = YES;
	    }
	  batteryState = BMBStateUnknown;
	}
      fclose(stateFile);
    }
  else if (useACPIproc)
    {
      stateFile = fopen(batteryStatePath0, "r");
      if (stateFile == NULL)
	{
	  NSLog(@"acpi /proc state file null");
	  return;
	}

      [self _readLine :stateFile :line];
      sscanf(line, "present: %s", presentStr);
      [self _readLine :stateFile :line];
      sscanf(line, "capacity state: %s", stateStr);
      [self _readLine :stateFile :line];
      sscanf(line, "charging state: %s", chStateStr);
      [self _readLine :stateFile :line];
      sscanf(line, "present rate: %s mW", rateStr);
      [self _readLine :stateFile :line];
      sscanf(line, "remaining capacity: %s mWh", capacityStr);
      [self _readLine :stateFile :line];
      sscanf(line, "present voltage: %s mV", voltageStr);
      fclose(stateFile);

      rateVal = atoi(rateStr);
      capacityVal = atoi(capacityStr);
      voltageVal = atoi(voltageStr);

      infoFile = fopen(batteryInfoPath0, "r");
      NSAssert(infoFile != NULL, @"ACPI - /proc: info file shall not be NULL");

      [self _readLine :infoFile :line];
      sscanf(line, "present: %s", present2Str);
      [self _readLine :infoFile :line];
      sscanf(line, "design capacity: %s", desCapStr);
      [self _readLine :infoFile :line];
      sscanf(line, "last full capacity: %s", lastCapStr);
      [self _readLine :infoFile :line]; // battery technology
      [self _readLine :infoFile :line]; // design voltage
      [self _readLine :infoFile :line]; // design capacity warning
      sscanf(line, "design capacity warning: %s", warnCapStr);
      [self _readLine :infoFile :line];    
      [self _readLine :infoFile :line];
      [self _readLine :infoFile :line];
      [self _readLine :infoFile :line];
      [self _readLine :infoFile :line];
      [self _readLine :infoFile :line];
      sscanf(line, "battery type: %s", batTypeStr);
      if (batteryType != nil)
	[batteryType release];
      batteryType = [[NSString stringWithCString:batTypeStr] retain];

      fclose(infoFile);

      watts = (float)rateVal / 1000;

      // a sanity check, a laptop won't consume 1000W
      // necessary since sometimes ACPI returns bogus stuff
      if (isnan(watts))
	watts = 0;
      else if (watts > 1000)
	watts = 0;
      volts = (float)voltageVal / 1000;
      amps = watts / volts;

      desCap = (float)atoi(desCapStr)/1000;
      lastCap = (float)atoi(lastCapStr)/1000;
      currCap = capacityVal / 1000;
      warnCap = (float)atoi(warnCapStr)/1000;

      if (!strcmp(chStateStr, "charged"))
	{
	  chargePercent = 100;
	  timeRemaining = 0;
	  isCharging = YES;
	  batteryState = BMBStateFull;
	}
      else if (!strcmp(chStateStr, "charging"))
	{
	  if (watts > 0)
	    timeRemaining = (lastCap-currCap) / watts;
	  else
	    timeRemaining = -1;
	  chargePercent = currCap/lastCap*100;
	  isCharging = YES;
	  batteryState = BMBStateCharging;
	}
      else
	{
	  if (watts > 0)
	    timeRemaining = currCap / watts;
	  else
	    timeRemaining = -1;
	  chargePercent = currCap/lastCap*100;
	  isCharging = NO;
	  batteryState = BMBStateDischarging;
	}
      fclose(stateFile);
    }
  else if (useAPM)
    {
      char drvVersionStr[16];
      char apmBiosVersionStr[16];
      char apmBiosFlagsStr[16];
      char acLineStatusStr[16];
      char battStatusStr[16];
      int  battStatusInt;
      char battFlagsStr[16];
      char percentStr[16];
      char timeRemainingStr[16];
      char timeUnitStr[16];
      BOOL percentIsInvalid;

      percentIsInvalid = NO;
      stateFile = fopen(apmPath, "r");
      if (stateFile == NULL)
	{
448
	  NSLog(@"apm state file nil");
449 450 451 452 453 454 455 456
	  return;
	}


      [self _readLine :stateFile :line];
      //	NSLog(@"line: %s", line);
      sscanf(line, "%s %s %s %s %s %s %s %s %s", drvVersionStr, apmBiosVersionStr, apmBiosFlagsStr, acLineStatusStr, battStatusStr, battFlagsStr, percentStr, timeRemainingStr, timeUnitStr);

457
      if (strlen(percentStr) > 0)
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
	{
	  if (percentStr[strlen(percentStr)-1] == '%')
	    percentStr[strlen(percentStr)-1] = '\0';
	  NSLog(@"%s %s %s", drvVersionStr, apmBiosVersionStr, percentStr);
    
	  chargePercent = (float)atof(percentStr);
	  if (chargePercent > 100)
	    chargePercent = 100;
	  if (chargePercent < 0)
	    {
	      chargePercent = 0;
	      percentIsInvalid = YES;
	    }
	  //	    NSLog(@"percent %f", chargePercent);
	}

474
      if (strlen(battStatusStr) > 0)
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
	{
	  if (battStatusStr[3] == '0')
	    battStatusInt = 0;
	  else if (battStatusStr[3] == '1')
	    battStatusInt = 1;
	  else if (battStatusStr[3] == '2')
	    battStatusInt = 2;
	  else if (battStatusStr[3] == '3')
	    battStatusInt = 3;
	  else if (battStatusStr[3] == '4')
	    battStatusInt = 4;
	  else
	    battStatusInt = -1;

	  isCharging = NO;
          isCritical = NO;
	  if (battStatusInt == 0)
	    batteryState = BMBStateHigh;
	  else if (battStatusInt == 1)
	    batteryState = BMBStateLow;
	  else if (battStatusInt == 2)
	    {
	      batteryState = BMBStateDischarging;
	      isCritical = YES;
	    }
	  else if (battStatusInt == 3)
	    {
	      batteryState = BMBStateCharging;
	      isCharging = YES;
	    } 
	  else if (battStatusInt == 4)
	    batteryState = BMBStateMissing;
	  else
	    batteryState = BMBStateUnknown;


	  if (percentIsInvalid)
	    {
	      NSLog(@"Battery percent information is invalid.");

	      if (battStatusInt == 0)
		chargePercent = 75;
	      else if (battStatusInt == 1)
		chargePercent = 25;
	      else if (battStatusInt == 2)
		chargePercent = 5;
	      else if (battStatusInt == 3)
		chargePercent = 100;
	      else if (battStatusInt == 4)
		chargePercent = 0;
	      else
		chargePercent = 0;
	    }
	}
    
      fclose(stateFile);
    }
  else if (usePMU)
    {
      NSString *strPmuInfo;
      NSString *strPmuBat;
      NSArray *arrayOfLines;
      NSArray *lineArray;
      NSString *strValue;

      strPmuInfo = [NSString stringWithContentsOfFile: @"/proc/pmu/info"];
      arrayOfLines = [strPmuInfo componentsSeparatedByString: @"\n"];
      NSLog(@"info %@", arrayOfLines);
      lineArray = [[arrayOfLines objectAtIndex: 2] componentsSeparatedByString: @":"];
      strValue = [lineArray objectAtIndex: 1];
      if ([strValue intValue] == 1)
	{
	  isCharging = YES;
	  batteryState = BMBStateCharging;
	}
      else
	{
	  isCharging = NO;
	  batteryState = BMBStateDischarging;
	}

      strPmuBat = [NSString stringWithContentsOfFile: @"/proc/pmu/battery_0"];
      arrayOfLines = [strPmuBat componentsSeparatedByString: @"\n"];
      NSLog(@"battery0 %@", arrayOfLines);

      lineArray = [[arrayOfLines objectAtIndex: 2] componentsSeparatedByString: @":"];
      strValue = [lineArray objectAtIndex: 1];
      currCap = (float)([strValue doubleValue] / 1000);

      lineArray = [[arrayOfLines objectAtIndex: 3] componentsSeparatedByString: @":"];
      strValue = [lineArray objectAtIndex: 1];
      lastCap = (float)([strValue doubleValue] / 1000);

      lineArray = [[arrayOfLines objectAtIndex: 4] componentsSeparatedByString: @":"];
      strValue = [lineArray objectAtIndex: 1];
      amps = (float)([strValue doubleValue] / 1000);

      lineArray = [[arrayOfLines objectAtIndex: 5] componentsSeparatedByString: @":"];
      strValue = [lineArray objectAtIndex: 1];
      volts = (float)([strValue doubleValue] / 1000);

      lineArray = [[arrayOfLines objectAtIndex: 6] componentsSeparatedByString: @":"];
      strValue = [lineArray objectAtIndex: 1];
      timeRemaining = (float)[strValue intValue] / 3600;

      desCap = lastCap; /* we can't do better with PMU */
      chargePercent = currCap/lastCap*100;
      watts = amps * volts;
    }
}

@end
587 588

#endif