0% found this document useful (0 votes)
510 views12 pages

Monsoon Power Tool Automation Quick Start Guide

The document provides a quickstart guide for programmatically controlling PowerTool automation through its .NET and COM interfaces. It includes an overview of the interface definition and properties, and discusses approaches for initialization and sample implementations in C# and C++. The guide assumes some familiarity with programming concepts and focuses on getting started with the first steps of installation and usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
510 views12 pages

Monsoon Power Tool Automation Quick Start Guide

The document provides a quickstart guide for programmatically controlling PowerTool automation through its .NET and COM interfaces. It includes an overview of the interface definition and properties, and discusses approaches for initialization and sample implementations in C# and C++. The guide assumes some familiarity with programming concepts and focuses on getting started with the first steps of installation and usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

PowerTool.

Automation
QuickStart Guide
LastUpdatedfor4.0.5.1

Contents
AboutthisGuide...........................................................................................................................................1
Introduction..................................................................................................................................................2
Installation....................................................................................................................................................2
InterfaceDefinition.......................................................................................................................................2
Usage.............................................................................................................................................................6
Approach1:.NET......................................................................................................................................6
Approach2:COM......................................................................................................................................7
1.

RegistertheassemblyandgenerateaTLBfile.............................................................................7

2.

RegistertheassemblywiththeGAC.............................................................................................7

3.

ImporttheTLBfileandinitializetheCOMobjects.......................................................................8

Overview...................................................................................................................................................9
SampleImplementations........................................................................................................................11
C#Samples..........................................................................................................................................11
C++Samples........................................................................................................................................11

About this Guide


ThePowerToolsoftwarehasabuiltin(OLE)Automationinterfacethatallowstheprogrammeror
engineertoprogrammaticallycontrolitsoperation.
WhatfollowsisabriefdescriptionofthePowerTool.Automationinterface,whatitis,howtoinstallit,
andhowtouseit.
Itisintendedtogivethereaderanacquaintanceinusingtheinterface,andguidehimorherintheir
firststeps.Itisnotintendedasacomprehensivereference.

Introduction
OnecanstartorstopmultiplePowerToolapplications,connecttovariousPowerMonitordevices,set
triggercodes,startandstopsampleruns,orsaveandloadfilesviaprogrammaticcontrol,muchlikean
interactiveusercandosittingathisorherconsole.
Thisdocumentassumesthatthereaderhasatleastsomefamiliaritywithprogrammingconceptsin
general,andCOMorthe.NETFrameworkinparticular.

Installation
First,installthePowerToolapplicationviaourstandardinstaller.Typically,youwillhavealreadydone
thatifyouhavegottentothispoint.TheAutomationsampleimplementationscanbefoundinthe
DeveloperExamplessubdirectorywhereyouinstalledtheMonsoonPowerToolapplications.
Executablesandsourcecodearebothdistributedfortheseexamples.AVisualStudiosolutionfileis
present,asareindividualprojectfilesforeachexample.Besuretoreadourusagenotesbeforebuilding
thesamples.Yournextstepswillvarydependingonwhetheryouareaccessingthelibraryvia.NET
awarelanguageslikeC#orviaCOMawarelanguageslikeC++.
Note,ifyouarebuildingthesolutionasawhole,youwillneedtofollowthestepsforCOMand.NETor
theC++exampleswillnotbuild.IfyouareonlybuildingspecificC#sampleprojects,thenyoucanskip
theCOMspecificsteps.

Interface Definition
Subjecttochange.Currentasof4.0.5.0.Note,theinterfacechangedin4.0.5.0!
[
Guid("B134840E-1BE3-4789-B04E-DBAD3BEE8E79"),
InterfaceType(ComInterfaceType.InterfaceIsDual),
ComVisible(true),
]
public interface IAutomation
{
#region IAutomation Properties
// Whether the PowerTool application is open
bool ApplicationIsOpen { get; }
// Whether a Power Monitor device is connected
bool DeviceIsConnected { get; }
// Whether a sample is currently running
bool SampleIsRunning { get; }
// Serial number of the connected device
ushort DeviceSerialNumber { get; }
// Whether the application has any data captured or loaded from file
bool HasData { get; }

PowerTool.AutomationQuickStartGuide

// Returns the summary statistics structure


SelectionData SelectionData { get; }
// Calibration status during sample run
// Values: OK, Warning, Failed
CalibrationStatus CalibrationStatus { get; }
// Program exit code
ExitCode ExitCode { get; }
// Data file name
string FileName { get; }
// Application status
PowerToolStatus PowerToolStatus { get; }
// Enable/disable throwing exceptions on errors
// (mostly during processing of properties)
bool ExceptionsAreEnabled { get; set; }
// Visibility state of the Power Tool application window
bool Visible { get; set; }
// Window state (min, max, normal)
WindowState WindowState { get; set; }
// Power-up time, in milliseconds.
// Allowable range: 0-255
byte PowerUpTime { get; set; }
// Current limits, in amps.
// Allowable range: 0-8
float PowerUpCurrentLimit { get; set; }
float RunTimeCurrentLimit { get; set; }
// USB passthrough mode.
// Allowable values: Auto, On, Off, Trigger, Sync
UsbPassthroughMode UsbPassthroughMode { get; set; }
// Directory for temporary files.
// The directory must exist
string TempDirectory { get; set; }
// Main and USB resistor offsets, in ohms.
// Allowable range: 0.0372-0.0627
float MainFineResistorOffset { get; set; }
float MainCoarseResistorOffset { get; set; }
float UsbFineResistorOffset { get; set; }
float UsbCoarseResistorOffset { get; set; }
// Aux resistor offsets, in ohms
// Allowable range: 0.0872-0.1127
float AuxFineResistorOffset { get; set; }
float AuxCoarseResistorOffset { get; set; }
// Trigger setting code.

PowerTool.AutomationQuickStartGuide

// Same code as used on the PowerTool command line


string TriggerSetting { get; set; }
// Real-time voltage channel selection
// Allowable values: Main, Aux. (USB not valid)
Channel VoltageChannel { get; set; }
// Enable/disable capture of currents
bool CaptureMainCurrent { get; set; }
bool CaptureUsbCurrent { get; set; }
bool CaptureAuxCurrent { get; set; }
// Set Main output voltage, in volts.
// Allowable range: 2.0f < setting <= 4.095f
float MainOutputVoltageSetting { get; set; }
// Whether Main output voltage is enabled
bool EnableMainOutputVoltage { get; set; }
// Battery size, in mAh
// Allowable range: 1-9000
uint BatterySize { get; set; }
// Number of devices available
uint DeviceCount { get; }
// Incremental wait time, in milliseconds
// Default = 1000
uint WaitInterval { get; set; }
// Version info
HardwareRevision HardwareRevision { get; }
byte FirmwareVersion { get; }
byte ProtocolVersion { get; }
SoftwareVersion SoftwareVersion { get; }
// Number of samples captured
ulong TotalSampleCount { get; }
ulong MissingSampleCount { get; }
// Capture date of sample
DateTime CaptureDate { get; }
// Sample rate (always 5000, but provided for completeness)
uint SampleRate { get; }
// Form position and size, in pixels
int Height { get; set; }
int Width { get; set; }
int Left { get; set; }
int Top { get; set; }
// Log file name. Empty or null string means no logging
string LogFileName { get; set; }
#endregion IAutomation Properties
#region IAutomation Methods

PowerTool.AutomationQuickStartGuide

// Enumerate the Power Monitors which are available for connection.


// Outputs array of device serial numbers found, or null if none.
// Returns the number of devices found (zero if none).
uint EnumerateDevices(out ushort[] serialNumbers);
// Gets the serial number associated with a particular
// device instance. (See DeviceCount property).
// Argument must be in the range 0..(DeviceCount-1)
// Returns 0 if invalid.
ushort GetSerialNumber(uint deviceNumber);
// Open/close the Power Tool application window, with optional wait.
// Wait times are specified in multiplea of the WaitInterval
// property, listed above
bool OpenApplication(bool readIniFile, bool waitFlag);
bool OpenApplication(bool readIniFile, uint waitLimit);
bool CloseApplication(bool writeIniFile, bool waitFlag);
bool CloseApplication(bool writeIniFile, uint waitLimit);
// Connect/disconnect a Power Monitor device
bool ConnectDevice(ushort serialNumber);
bool DisconnectDevice();
// Refresh the application display
bool RefreshDisplay();
// Start/stop sampling
bool StartSampling(bool waitFlag;
bool StartSampling(uint waitLimit); // in multiples of WaitInterval
bool StopSampling(bool waitFlag);
bool StopSampling(uint waitLimit); // see above
// Load a previously-captured file
bool LoadFile(string fileName);
// Save captured data to a file
bool SaveFile( string fileName,
bool overwriteFile,
bool createDirectory);
bool ExportCSV( ulong lowIndex,
ulong highIndex,
string fileName,
uint granularity,

bool overwriteFile,
bool createDirectory);

// File name
// Overwrite file?
// Create directory?
// 0..(TotalSampleCount-1)
// 0..(TotalSampleCount-1)
// File name
// 1,10,100,1000,10000 the
//modulus used to determine
//which samples to export
// Overwrite file?
// Create directory?

// Sample retrieval
bool GetSample( ulong sampleIndex,
out Sample sample);

// 0..(TotalSampleCount-1)
// A Sample structure

bool GetSamples(ulong startIndex,


uint sampleCount,
out Sample[] samples);

// 0..(TotalSampleCount-1)
// Number of samples desired
// Array of Sample structures

PowerTool.AutomationQuickStartGuide

//Resets the connection to the currently connected power monitor


//device and disables VOut.
bool ResetPowerMonitor();
#endregion IAutomation Methods
}

Usage
Approach 1: .NET
.Net4.5isspecificallyrequiredforversion4.0.5.0.
Asof4.0.5.0,allincludedprojectsarebuiltunderVisualStudio2015.IfyouwishtobuildunderVisual
Studio2012andareonlyusingC#,disabletheCPPClientproject.Otherwise,youmustsetyour
PlatformToolsettoVisualStudio2012fortheCPPClientprojectoryouwillhavebuilderrorswhenyou
buildfromtheSolutionasawhole.
.Net4.0isspecificallyrequiredforversion4.0.4.11.
.NET3.5isspecificallyrequiredforversions4.0.4.04.0.4.10.
Assumingthatyouarewritingyourcodeina.NETcompatiblelanguage,suchasC#,yousimplyneedto
fixthereferencetoPowerTool.exeinyourprojecttopointtowhereveritwasinstalledonyour
computer.
ThesimplestwaytodothisisremovePowerTool.exefromyourprojectreferences,andthenreaddit.

PowerTool.AutomationQuickStartGuide

Noadditionalassemblyregistrationorstepsarenecessary.Ifyoudidregisteranearlierassemblyinthe
GAC,.NETwillpullthatassemblyfirst,andyoumustunregisterittocompileagainstthenewassembly.

Approach 2: COM
Alternatively,ifyouwanttodoittheoldfashionedway(COMstyle)withalanguagesuchasC++,follow
thefollowingsteps.YouwillneedtoredothesestepsanytimethereisanewversionofthePowerTool
executableoraninterfacechange.
Note,COMsupportrequiresversion4.0.4.9orlaterofthePowerToolapplication.Alsonotethatthe
COMAPIisnotasfullfeaturedasthe.NETAPIanddoesnotexposeallofthesamefunctionality.
Asof4.0.5.0,allincludedprojectsarebuiltunderVisualStudio2013.IfyouwishtobuildunderVisual
Studio2012,youmustsetyourPlatformToolsettoVisualStudio2012fortheCPPClientprojectoryouwill
havebuilderrors.
1. Register the assembly and generate a TLB file.
Thissteprequiresthatyouhaveinstalledthefree.NET3.5(orhigher)SDKfromMicrosoft.
Openacommandpromptasanadministratorandchangetothe.NETdirectorywhereregasmis
installed(forexample:c:\Windows\Microsoft.NET\Framework\v4.0.30319).Runthefollowing
command:
RegAsm.exe[pathtopowertool.exe]/tlb:PowerTool.tlb

Forexample,withthedefaultPowerToolinstalllocation,youwouldrun
RegAsm.exeC:\ProgramFiles(x86)\MonsoonSolutionsInc\PowerMonitor\PowerTool.exe
/tlb:PowerTool.tlb

Theabovecommand,oncecompletedsuccessfully,registersthePowerTool.exeapplicationasthe
serverforthePowerTool.Automationobjectandgeneratesthetlbfileyouwillneedtoimportinyour
code.
Youshouldseeanoutputalongthelinesof:
Typesregisteredsuccessfully
Assemblyexportedto'c:\ProgramFiles(x86)\MonsoonSolutionsInc\PowerMonitor\PowerTool.tlb',andthetype
librarywasregisteredsuccessfully

2. Register the assembly with the GAC.


ThissteprequiresthatyouhaveinstalledeitherVisualStudio(2010orlater)orthefreeWindows
SDK(version6orlater)fromMicrosoft.
OpenaVisualStudioCommandPromptasadministratororaWindowsSDKCommandPromptas
administrator.IfyouhavepreviouslyregisteredaPowerToolassemblybesuretounregisterfirstand
thenregisterthenewassembly.
PowerTool.AutomationQuickStartGuide

IfyouneedtouninstalltheassemblyfromtheGAC,youcanissuethecommand:

gacutil/uPowerTool

Registeryournewassembly:
gacutil/iC:\ProgramFiles(x86)\MonsoonSolutionsInc\PowerMonitor\PowerTool.exe

Youshouldseeanoutputalongthelinesof:
Assemblysuccessfullyaddedtothecache.

YoucanquerytheGACtoseethePowerToolassemblyisinstalledwiththefollowingcommand.Make
surethePowerToolassemblyversionshownistheoneyouexpect.

gacutil/lPowerTool

3. Import the TLB file and initialize the COM objects


ThefollowingsamplecallsarewritteninC++.Toseeareferencesampleimplementation,lookatour
C++samples.
CreateaC++projecttypeofyourchoice,forexample,acommandlineproject.
Specifyyourincludesandimports,includingthetlbfile
ThisexampleusestheATLCOMlibraries
#include<atlbase.h>
#include<atlsafe.h>

IMPORTANT!Fixthispathtomatchyourcurrentlocation!
#import"C:\ProgramFiles(x86)\MonsoonSolutionsInc\PowerMonitor\PowerTool.tlb"
Specifythenamespace
usingnamespacePowerTool;

InitializetheCOMlibrary
::CoInitialize(NULL);

Getthepowertoolinstance
IAutomation*pAutomation=NULL;
CComPtr<IAutomation>autoPtr;
HRESULThr=autoPtr.CoCreateInstance(_T("PowerTool.Automation"));

Dowhateveryouwanttodoherewiththeinterface.
PowerTool.AutomationQuickStartGuide

Cleanup
if(pAutomation)
pAutomation>Release();
CoUninitialize();

Overview
ThefollowingsamplecallsarewritteninC#.Toseeacompleteimplementation,lookatoursamples.
Startoutwith:
PowerTool.AutomationmyPowerTool=newPowerTool.Automation();
Ifyougetanonnullresult,youarenowinprogrammaticcontrolofthePowerTool.Youcanopenmore
thanonePowerToolifyouwish.Eachisrepresentedinyourspacebytheobjectyouinstantiated,as
above.
So,nowthatyouhaveaPowerToolinstance,whatcanyoudowithit?Youmightstartoutbyrunningit:

boolpowerToolRunning=myPowerTool.OpenApplication(false,30);

The30specifiesthenumberofwaitintervalswerewillingtowaitfortheapptostartup.Thedefault
intervalis1000milliseconds,sointheabovecall,wesaidwerewillingtowait30intervals,or30
seconds.ThefalsetellsitnottoreaditsINIfile,welltakethedefaults.
OncethePowerToolappisrunning,itmightbeconvenienttoknowwhatPowerMonitordevicesare
attachedtothehostcomputer:
ushort[]serialNumbers=newushort[1];
//justtemporarygetsreplacedshortly
uintdeviceCount=myPowerTool.EnumerateDevices(outserialNumbers);
IftherearenoPowerMonitors,theEnumerateDevicescallreturnszero,andnullsouttheoutputarray.
Otherwise,itgivesusanewarrayofserialnumbers,andreturnsthecountofdevices.
Ifweseeadevicewelike,wecanconnecttoitbyspecifyingitsserialnumber.So,say
EnumerateDevices()reportedbackatleastonedevice.Wecanthenissuethefollowingcalltoconnect
tothefirstdevice:

booldeviceConnected=myPowerTool.ConnectDevice(serialNumbers[0]);

Nowthatwereconnected,thedeviceisoursandwillstaythatwayuntilwedisconnect,orsomeone
pullstheplug.
Howaboutwetakesomesamples?

PowerTool.AutomationQuickStartGuide

myPowerTool.Visible=true;

//Letswatchitrun
myPowerTool.MainOutputVoltageSetting=3.7;
//Ourdevicelikes3.7volts
myPowerTool.EnableMainOutputVoltage=true;
//Giveitthejuice
boolstarted=myPowerTool.StartSampling(10);
//Sametimingrulesasabove
//
//Wedootherstuffwhilesamplingoccursonabackgroundthread,andthen
//
boolstopped=myPowerTool.StopSampling(10);
//Stopsamplingsametimingrules
myPowerTool.EnableMainOutputVoltage=false;
//Leavethedevicepoweredoff
Okay,nowwehavesampledatasittinginPowerToolsworkingmemory.Exactly5,000datapointsfor
eachsecondthatthesamplewasrunning.Whatdowedowiththisdata?Well,wecouldsaveitina
file
booldataSaved=myPowerTool.SaveFile(C:\\MyFolder\\MyFile.pt4,true,true);
Thetruevaluesmerelytellittooverwriteanylikenamedfileitmayfindinthatfolder,andtocreate
thefolderifitdoesntalreadyexist.
Nowthatourdataissaved,letscleanup
myPowerTool.DisconnectDevice();

myPowerTool.CloseApplication(false,true);
myPowerTool=null;

//Disconnect
//DontwriteINIfile,waitforclosure
//Disposeoftheinterface

Theaboveisintendedasasimplereferenceandisnotacompleteguide.Seethesample
implementationsthatareincludedforadditionalexamples.

PowerTool.AutomationQuickStartGuide

10

Sample Implementations
AVisualStudioSolutionfileisprovidedforyourconvenience.DeveloperTools.slncontainstheprojects
referencedbelow.
C# Samples
IMPORTANTNOTE:Tobuildanyoftheseprojects,changetheprojectreferencetoPowerTool.exeto
reflectitsinstalledlocationonyoursystem.
ConsoleExamples
Severalsimpleexamplesareprovidedtodemonstratedifferentcapabilities.
SimpleSamplingExampleshowshowtoconnecttoadevice,sample,accessrealtimesamplingdata,
andexportdatatoCSVandPT4files.
IterativeCallingExampletakesthefunctionalityofSimpleSamplingExample,butrunsititeratively,
showinghowtoproperlyshutdownandstartupyourconnectionseachtime.
ResetExampleshowshowtousethenewto4.0.5.0ResetPowerToolmethodtocyclethepowertothe
connectedPowerMonitordevice.
IniTriggerExampleshowshowtousetheAutomationinterfacetoworkwithtriggercodesininifiles.
PT4Readershowshowtoreadinapt4filetoextractthestoreddata.
PT5Readershowshowtoreadinapt5filetoextractthestoreddata.
RecalibrateExampleshowshowtoprogrammaticallyrecalibratethePowerMonitor.
WindowsApplicationExample
AsampleapplicationAutoDemoisincluded,bothasanexecutableandwithfullsourcecode.It
containsafullfeaturedWindowsGUIappthatdemonstratesamoreinvolvedimplementationofthe
PowerTool.Automationinterface.
Whenyouruntheexecutable,clickOPENtoconnecttoanavailablePowerTooldevice.Thiswillrefresh
thelistofdevicesavailabletoconnectviatheAutoDemoapplication.Makesureyourdesireddeviceis
selected,andthenclickCONNECTtoactivatecontrolofthePowerToolinstanceviatheAutoDemo
application.
C++ Samples
IMPORTANTNOTE:BesureyouhavefullyfollowedthedirectionslistedforusingCOM,beforeusing
thesesamples.Also,besuretoeditthepathtoyourTLBfileinyourcode.
ConsoleExample

PowerTool.AutomationQuickStartGuide

11

AsimpleapplicationCPPClientisincluded,bothasanexecutableandwithfullsourcecode.Itcontains
aconsoleapplicationthatusestheCOMinterface.ItdemonstratesconnectingtothePowerTool
applicationandtoaspecificPowerMonitordevice,takingashortsample,andwritingtheoutputtoa
pt4file.

PowerTool.AutomationQuickStartGuide

12

You might also like