Jump to content

WaitforBattery script


Briandr
 Share

Recommended Posts

Hi, 

I found a really cool script from:

https://github.com/jpuskar/SCCM-Public-Scripts/blob/master/Laptop%20Power/WaitForBattery.au3

What I need from the script is just to check if an A/C Adapter is connected and then once it is the script ends. I am not really concerned about the 2nd half of the script that checks and waits until the battery charge is at a certain percent before exiting the script. I am just wondering if any of you guys have seen this script and what are your thoughts concerning this? Feedback is welcome and I'd be neglectful if I did not give kudos to the creator of the script jpuskar.

By the way could someone tell me a way to include an image with the pop ups? 

Thanks again guys.

;WaitForBattery
;John Puskar 01/16/2013
;johnpuskar@gmail.com
;windowsmasher.wordpress.com

Dim $batterystatus, $objwmiservice_, $status, $battPercentage
Dim $oBattery, $batteryInfo, $acPower
Local $objwmiservice = ObjGet ('winmgmts:\\localhost\root\CIMV2')
Local $objwmiservice2 = ObjGet ('winmgmts:\\localhost\root\wmi')

ProgressOn("AC Adapter", "Checking to see if AC Adapter is Connected...", "Please wait.")
Dim $sysRoot
$sysRoot = EnvGet ( "systemroot" )
RunWait(@comspec & " /c drvload %systemroot%\inf\battery.inf")
Dim $i
For $i = 0 To 100 Step 1
    Sleep(75)
    ProgressSet($i, $i & " percent")
Next
ProgressOff()

;Power adapter
Dim $i
$i = 0
While 1
    $oBattery = $objWMIService2.ExecQuery("SELECT * FROM BatteryStatus WHERE Voltage > 0")
    If IsObj($oBattery) Then
        SetError(0)

        Dim $errorCode
        Dim $batteryInfo
        Dim $acPower
        For $batteryInfo in $oBattery
            $acPower = $batteryInfo.PowerOnline
        Next
        $errorCode = @Error

        ;Dim $msg
        ;$msg = "i: " & $i & " | acpower: " & $acPower & " | error: " & $errorCode
        ;msgbox(1,"AC Power",$msg)

        If $errorCode <> 0 Then
            ExitLoop
        ElseIf $acPower <> True Then
            If $i = 0 Then
                ProgressOn("AC Adapter", "Waiting for AC Adapter.", "Please plug in the laptop and wait 10 seconds...",600,200)
            EndIf
            Sleep(1000)
        Else
            ExitLoop
        EndIf
    Else
        ExitLoop
    EndIf
    $i = $i + 1
Wend
ProgressOff()
Edited by Briandr
Link to comment
Share on other sites

;WaitForBattery
;John Puskar 01/16/2013
;johnpuskar@gmail.com
;windowsmasher.wordpress.com

Local $objwmiservice2 = ObjGet ('winmgmts:\\localhost\root\wmi')

$i = 0
While 1

    Sleep(20)

    local $oBattery = $objWMIService2.ExecQuery("SELECT * FROM BatteryStatus WHERE Voltage > 0")
    If IsObj($oBattery) Then
        SetError(0)

        Dim $errorCode
        Dim $batteryInfo
        Dim $acPower
        For $batteryInfo in $oBattery
            $acPower = $batteryInfo.PowerOnline
        Next
        $errorCode = @Error


        If $errorCode <> 0 Then
            ExitLoop
        ElseIf $acPower <> True Then
            If $i = 0 Then
                tooltip("AC UNPLUGGED  =|)----x")
            EndIf

        Else
            tooltip("AC Plugged In  u====D----O:")
        EndIf
    Else
        ExitLoop
    EndIf
Wend

Edited by boththose

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

Hi,

Thanks for replying, but I already decided what I want to use as shown in the code window above. I do have a question and forgive my ignorance, but if this was run on a desktop, nothing should pop up as the desktop is always going to be on A/C power. Makes sense, but what I thought was do I need to add a function to detect chasis type so this only runs on laptops?

Just was hoping some could give a quick thought on this?

Thanks.

Edited by Briandr
Link to comment
Share on other sites

you decided you want to have unnecessary declarations, artifacts, and wait times?  My mistake.

*And my ASCII art as a reply to your request for images with the popups, is hilarious.

Edited by boththose

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

Hello,

Not sure how to read into reply. Maybe you thought I wanted you or someone else to create the code. I am keenly aware most members like to help, but don't expect them to do the work for you. I may need to remind myself that once in a while. Perhaps I should have told you I already had something in mind. Either way I like this forum and the code samples I find here in general help and the free examples helps alot. That being said I think I got this looking good as seen below, but I am having trouble with progresson truncating characters. Ideas?

#include <File.au3>
#include <Constants.au3>

$LogDirectory = @ScriptDir
$ModuleName = @ScriptName
$ModuleName = StringSplit($ModuleName, ".")
$ModuleName = $ModuleName[1]
$Log = $LogDirectory & "\" & $ModuleName & ".log"
$wbemFlagReturnImmediately = 0x10
$wbemFlagForwardOnly = 0x20
$colItems = ""
$StrComputer = "localhost"

Dim $batterystatus, $objwmiservice_, $status, $battPercentage
Dim $oBattery, $batteryInfo, $acPower
Dim $InstallCmd, $ChassisType
Local $objwmiservice = ObjGet ('winmgmts:\\localhost\root\CIMV2')
Local $objwmiservice2 = ObjGet ('winmgmts:\\localhost\root\wmi')

If FileExists($Log) Then FileDelete($Log)

_FileWriteLog($Log, $ModuleName & " module called.")

If ProcessExists("KACEEngine.exe") Then ;check if called during imaging
    _FileWriteLog($Log, "KACEEngine.exe is running, imaging process, install running as task.")
    _GetChassisType() ;Check to see if computer is laptop
    If $ChassisType = "LT" Then ;install on all laptops by default
        ;will be installed
        _FileWriteLog($Log, "PC is laptop, check to see if laptop AC Adapter is Connected")
    Else
        ;PC is not laptop, do not install exit script
        _FileWriteLog($Log, "KACEEngine.exe is running, PC is desktop, nothing to do. Exiting Script")
        Exit
    EndIf
EndIf

ProgressOn("AC Adapter", "Checking to see if AC Adapter is Connected...", "Please wait.")
Dim $sysRoot
$sysRoot = EnvGet ( "systemroot" )
RunWait(@comspec & " /c drvload %systemroot%\inf\battery.inf")
Dim $i
For $i = 0 To 100 Step 1
    Sleep(75)
    ProgressSet($i, $i & " percent")
Next
ProgressOff()

;Power adapter
Dim $i
$i = 0
While 1
    $oBattery = $objWMIService2.ExecQuery("SELECT * FROM BatteryStatus WHERE Voltage > 0")
    If IsObj($oBattery) Then
        SetError(0)

        Dim $errorCode
        Dim $batteryInfo
        Dim $acPower
        For $batteryInfo in $oBattery
            $acPower = $batteryInfo.PowerOnline
        Next
        $errorCode = @Error

        ;Dim $msg
        ;$msg = "i: " & $i & " | acpower: " & $acPower & " | error: " & $errorCode
        ;msgbox(1,"AC Power",$msg)

        If $errorCode <> 0 Then
            ExitLoop
        ElseIf $acPower <> True Then
            If $i = 0 Then
                ProgressOn("AC Adapter", "Waiting for AC Adapter.", "Please plug in the laptop and wait 10 seconds...",600,200)
            EndIf
            Sleep(1000)
        Else
            ExitLoop
        EndIf
    Else
        ExitLoop
    EndIf
    $i = $i + 1
Wend
ProgressOff()

Func _GetChassisType();Get Chassis Type and make it available as Global Variable
    _FileWriteLog($Log, "Getting system chassis type")
    Dim $IsLaptop
    $objWMIService = ObjGet("winmgmts:\\" & $StrComputer & "\root\CIMV2")
    $colItems = $objWMIService.ExecQuery("SELECT * FROM Win32_SystemEnclosure", "WQL", _
            $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
    If IsObj($colItems) Then
        For $objItem In $colItems
            $strChassisTypes = $objItem.ChassisTypes(0)
            Select
                Case ($strChassisTypes = "8" Or $strChassisTypes = "9" Or $strChassisTypes = "10" Or $strChassisTypes = "12" Or $strChassisTypes = "14" Or $strChassisTypes = "16" Or $strChassisTypes = "21")
                    $IsLaptop = "True"
            EndSelect
        Next
        If $IsLaptop = "True" Then
            $ChassisType = "LT"
        EndIf
        _FileWriteLog($Log, "Chassis type is: " & $ChassisType)
    EndIf
EndFunc   ;==>_GetChassisType

Thank you folks kindly.

Edited by Briandr
Link to comment
Share on other sites

Sure, but if you ask for thoughts on a script, in a scripting forum, expect those thoughts to be in script.

And then when someone gives those thoughts dont reply, "I already decided what I want to use as shown in the code window above".  Because then there is no point in soliciting information, and you get snarky replies, like mine.

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

I am not a programmer (AutoIT is still new to me, even after being on the forums 4 years) and just because a program compiles cleanly doesn't mean it will  behave correctly. I hack stuff together at times. Take this code and merge it with that code to try and get what I need all the while still trying to learn as I go.

That is why I came to the forums to ask for feedback and I try to show modesty. The original programmer was given his just kudos. So I am doing what I think is right. But if your asking me to re-phrase my questions on the forum fair enough. Will remember that next time I need assistance

Edited by Briandr
Link to comment
Share on other sites

nah, maybe i should ask questions rather than offer suggestions.

Why tell the user to wait 10 seconds, then do 7.5 seconds worth of useless activity (as it pertains to detection of A/C), to ultimately act on information you had in literally milliseconds with the wmi call?

Why would you have a full second pause in your loop? that is 980ms too long, imho.  If you can have near immediacy why would you not take it?

Edited by boththose

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

Agreed on all points and I was just taking the programmer's defaults as a starting point. Certainly room for tweaking. For all intents and purposes the intended audience should only get a pop up if the code detects an A/C adapter is not plugged into  and the device is a laptop. Techs (I am guilty of this too) start an imaging process leave and go home. Next morning the image failed because the battery ran out. So thus the need to offer a friendly reminder to plug in the A/C adapter. I am more convinced the first progresson is only adding confusion.......I removed it.

Edited by Briandr
Link to comment
Share on other sites

I been wrestling with this line and I finally got the Progresson to display correctly on my W7 laptop. Now in a Windows PE environment I am having same issue as before, the progresson window is going all the way to the right of the screen. I have to believe the display settings would influence the placement of the window? I was up last night trying to figure out how to use WinMove with Progesson and not having alot of luck

 

ProgressOn("AC Adapter", "Waiting for AC Adapter.", "Please plug in the laptop and wait 10 seconds...",600,200) 

Edited by Briandr
Link to comment
Share on other sites

You should look at the Splash screen with progress function I have linked in my signature. It will return a handle that you could use with WinMove, although WinMove should also work with the title of the ProgressOn window. You should probably use the @DesktopWidth and @DesktopHeight macros to find how big the screen is so you aren't hard coding the position in the script.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

For all intents and purposes the intended audience should only get a pop up if the code detects an A/C adapter is not plugged into  and the device is a laptop.

 

 

Then what are you displaying the progress of?  If all you want is a GUI to splash text, then please look at Brewman's splashscreen, or Melba's toast UDF.

*in addition to a splash you might want to blockinput(1) until they plug an AC adapter in, that's a not so gentle reminder.

Edited by boththose

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

I been looking at Brewman's SplashGUI w/Progress bar. Positioning on the screen seems to be better handled than ProgressOn. I do have multiple laptop models with different size screens so I will need to test primarily in a Windows PE environment. I incorporated his UDF into mine and I did not really change much expect one line. The more I think about this I am convinced I just need a pop up that will go away when A/C power adapter is plugged in. Can I get rid of the progress bar that does nothing using Brewman's SplashGUI?

Thanks.

#include <File.au3>
#include <Constants.au3>
#include "_ProgressGUI.au3"

$LogDirectory = @ScriptDir
$ModuleName = @ScriptName
$ModuleName = StringSplit($ModuleName, ".")
$ModuleName = $ModuleName[1]
$Log = $LogDirectory & "\" & $ModuleName & ".log"
$wbemFlagReturnImmediately = 0x10
$wbemFlagForwardOnly = 0x20
$colItems = ""
$StrComputer = "localhost"

Dim $batterystatus, $objwmiservice_, $status, $battPercentage
Dim $oBattery, $batteryInfo, $acPower
Dim $InstallCmd, $ChassisType
Local $objwmiservice = ObjGet('winmgmts:\\localhost\root\CIMV2')
Local $objwmiservice2 = ObjGet('winmgmts:\\localhost\root\wmi')

If FileExists($Log) Then FileDelete($Log)

_FileWriteLog($Log, $ModuleName & " module called.")

If ProcessExists("KACEEngine.exe") Then ;check if called during imaging
    _FileWriteLog($Log, "KACEEngine.exe is running, imaging process, install running as task.")
    _GetChassisType() ;Check to see if computer is laptop
    If $ChassisType = "LT" Then ;install on all laptops by default
        ;will be installed
        _FileWriteLog($Log, "PC is laptop, check to see if laptop AC Adapter is Connected")
    Else
        ;PC is not laptop, do not install exit script
        _FileWriteLog($Log, "KACEEngine.exe is running, PC is desktop, nothing to do. Exiting Script")
        Exit
    EndIf
EndIf

Dim $sysRoot
$sysRoot = EnvGet("systemroot")
RunWait(@ComSpec & " /c drvload %systemroot%\inf\battery.inf", @TempDir, @SW_HIDE)
Dim $i
For $i = 0 To 100 Step 1
    Sleep(3)
    ProgressSet($i, $i & " percent")
Next

;Power adapter
Dim $i
$i = 0
While 1
    $oBattery = $objwmiservice2.ExecQuery("SELECT * FROM BatteryStatus WHERE Voltage > 0")
    If IsObj($oBattery) Then
        SetError(0)

        Dim $errorCode
        Dim $batteryInfo
        Dim $acPower
        For $batteryInfo In $oBattery
            $acPower = $batteryInfo.PowerOnline
        Next
        $errorCode = @error

        ;Dim $msg
        ;$msg = "i: " & $i & " | acpower: " & $acPower & " | error: " & $errorCode
        ;msgbox(1,"AC Power",$msg)

        If $errorCode <> 0 Then
            ExitLoop
        ElseIf $acPower <> True Then
            If $i = 0 Then
                $Return = _ProgressGUI("Please plug in A/C Adapter and wait 10 seconds...", 1, 20, "", 300, 200);, 4, 6)
            EndIf
            Sleep(1000)
        Else
            ExitLoop
        EndIf
    Else
        ExitLoop
    EndIf
    $i = $i + 1
Wend

Func _GetChassisType();Get Chassis Type and make it available as Global Variable
    _FileWriteLog($Log, "Getting system chassis type")
    Dim $IsLaptop
    $objwmiservice = ObjGet("winmgmts:\\" & $StrComputer & "\root\CIMV2")
    $colItems = $objwmiservice.ExecQuery("SELECT * FROM Win32_SystemEnclosure", "WQL", _
            $wbemFlagReturnImmediately + $wbemFlagForwardOnly)
    If IsObj($colItems) Then
        For $objItem In $colItems
            $strChassisTypes = $objItem.ChassisTypes(0)
            Select
                Case ($strChassisTypes = "8" Or $strChassisTypes = "9" Or $strChassisTypes = "10" Or $strChassisTypes = "12" Or $strChassisTypes = "14" Or $strChassisTypes = "16" Or $strChassisTypes = "21")
                    $IsLaptop = "True"
            EndSelect
        Next
        If $IsLaptop = "True" Then
            $ChassisType = "LT"
        EndIf
        _FileWriteLog($Log, "Chassis type is: " & $ChassisType)
    EndIf
EndFunc   ;==>_GetChassisType
Link to comment
Share on other sites

see the part in my first recommendation where it does exactly that with tooltips?  You should work from that one replacing those two tooltips with the desired null behavior when it is plugged in, and splash behavior when it is not.  Again, also consider Melba's  toast UDF as in a PE environment it drops down from the upper left by default and is super sexy.

Edited by boththose

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...