Home
Yocto-Amp, User's guide
Contents
1. www yoctopuce com 193 21 High level API Reference module wait_async YModule Waits for all pending asynchronous commands on the module to complete and invoke the user provided callback function function wait_async callback context function wait_async callback context The callback function can therefore freely issue synchronous or asynchronous commands without risking to block the Javascript VM Parameters callback callback function that is invoked when all pending commands on the module are completed The callback function receives two arguments the caller specific context object and the receiving function object context caller specific object that is passed as is to the callback function Returns nothing 194 www yoctopuce com 21 High level API Reference 21 3 Current function interface The Yoctopuce application programming interface allows you to read an instant measure of the sensor as well as the minimal and maximal values observed In order to use the functions described here you should include lt script type text javascript src yocto_current js gt lt script gt var yoctolib require yoctolib var YCurrent yoctolio YCurrent require_once yocto_current php include yocto_current h import yocto_current h uses yocto_current yocto_current vb yocto_current cs import com yoctopuce YoctoAPI YCurrent from yocto_current import Globa
2. s64 upTime function get_upTime int64 v _ function get_upTime As Long long get_upTime long get_upTime def get_upTime YModule target get_upTime Returns an integer corresponding to the number of milliseconds spent since the module was powered on On failure throws an exception or returns Y_UPTIME_INVALID 176 www yoctopuce com 21 High level API Reference module get_usbBandwidth YModule module usbBandwidth Returns the number of USB interfaces used by the module function get_usbBandwidth function get_usbBandwidth function get_usbBandwidth Y_USBBANDWIDTH_enum get_usbBandwidth Y_USBBANDWIDTH_enum usbBandwidth function get_usbBandwidth Integer function get_usbBandwidth As Integer int get_usbBandwidth int get_usbBandwidth def get_usbBandwidth YModule target get_usbBandwidth Returns either Y_USBBANDWIDTH_SIMPLE or Y_USBBANDWIDTH_DOUBLE according to the number of USB interfaces used by the module On failure throws an exception or returns Y_USBBANDWIDTH_INVALID www yoctopuce com 177 21 High level API Reference module gt get_usbCurrent YModule module gt usbCurrent Returns the current consumed by the module on the USB bus in milli amps function get_usbCurrent function get_usbCurrent function get_usbCurrent int get_usbCurrent int usbCurrent pas function get_usbCu
3. currentRunIndex Current run number corresponding to the number of time the module was powered on with the dataLogger enabled at some point timeUTC Current UTC time in case it is desirable to bind an absolute time reference to the data stored by the data logger This time must be set up by software recording Activation state of the data logger The data logger can be enabled and disabled at will using this attribute but its state on power on is determined by the autoStart persistent attribute autoStart Automatic start of the data logger on power on Setting this attribute ensures that the data logger is always turned on when the device is powered up without need for a software command clearHistory Attribute that can be set to true to clear recorded data 7 6 What interface Native DLL or Service There are several methods to control you Yoctopuce module by software Native control In this case the software driving your project is compiled directly with a library which provides control of the modules Objectively it is the simplest and most elegant solution for the end user The end user then only needs to plug the USB cable and run your software for everything to work Unfortunately this method is not always available or even possible The application uses the native library to control the locally connected module Native control by DLL Here the main part of the code controlling the modules is located in a DL
4. datalogger forgetAllDataStreams Clears the data logger memory and discards all recorded data streams function forgetAllDataStreams function forgetAllDataStreams function forgetAllDataStreams int forgetAllDataStreams int forgetAllDataStreams function forgetAllDataStreams Longint function forgetAllDataStreams As Integer int forgetAllDataStreams int forgetAllDataStreams def forgetAllDataStreams YDataLogger target forgetAllDataStreams This method also resets the current run index to zero Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code YDataLogger www yoctopuce com 243 21 High level API Reference datalogger get_advertisedValue YDataLogger datalogger advertisedValue Returns the current value of the data logger no more than 6 characters function get_advertisedValue function get_advertisedValue function get_advertisedValue string get_advertisedValue NSString advertisedValue function get_advertisedValue string function get_advertisedValue As String string get_advertisedValue String get_advertisedValue def get_advertisedValue Y DataLogger target get_advertisedValue Returns a string corresponding to the current value of the data logger no more than 6 characters On failure throws an exception or returns Y_ADVERTISEDVALUE_INVALID 2
5. WCwISMe Ele encor Weise Sime q Nalinelewuecine Sorel ap Veen Sime p try TextView view TextView findViewById R id acfield VLEN SEETI Sein peO mM cen a Hao Su MCCS ONS Oren eis CULa me mitayiaal en iy ae Sensor Cerewimaltc x CHCl QAR Tee tom G i e printStackTrace handler postDelayed this 1000 18 6 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon package com yoctopuce doc_ examples import android app Activity import android os Bundle import android util Log import android view View import android widget AdapterView import android widget AdapterView OnItemSelectedListener import android widget ArrayAdapter import android widget Spinner import android widget Switch import android widget TextView import com yoctopuce YoctoAPI YAPI import com yoctopuce YoctoAPI YAPI Exception import com yoctopuce YoctoAPI YModule public class ModuleControl extends Activity implements OnItemSelectedListener private ArrayAdapter lt String gt aa private YModule module null Override public void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout modulecontrol 102 www yoctopuce com 18 Using the Yocto Amp with Android Spinner my spin
6. function describe function describe string describe NSString describe function describe string function describe As String string describe String describe def describe The text may include either the logical name or the serial number of the module YModule Returns a string that describes the module www yoctopuce com 155 21 High level API Reference module gt download YModule Downloads the specified built in file and returns a binary buffer with its content function download pathname function download pathname function download pathname string download string pathname NSData download NSString pathname function download pathname string TByteArray function download As Byte def download pathname YModule target download pathname Parameters pathname name of the new file to load Returns a binary buffer with the file content On failure throws an exception or returns an empty content 156 www yoctopuce com 21 High level API Reference module gt functionCount YModule Returns the number of functions beside the module interface available on the module function functionCount function functionCount function functionCount int functionCount int functionCount function functionCount integer function functionCount As Integer int functionCount def functionCount Returns
7. String get_functionld def get_functionld For example temperaturel Returns a string that identifies the function ex temperaturel 276 www yoctopuce com 21 High level API Reference dataset get_hardwareld YDataSet dataset hardwareld Returns the unique hardware identifier of the function who performed the measures in the form SERIAL FUNCTIONID function get_hardwareld function get_hardwareld function get_hardwareld string get_hardwareld NSString hardwareld function get_hardwareld string function get_hardwareld As String string get_hardwareld String get_hardwareld def get_hardwareld The unique hardware identifier is composed of the device serial number and of the hardware identifier of the function for example THRMCPL1 123456 temperaturel1 Returns a string that uniquely identifies the function ex THRMCPL1 123456 temperaturel On failure throws an exception or returns Y_HARDWAREID_INVALID www yoctopuce com 277 21 High level API Reference dataset get_measures YDataSet dataset measures Returns all measured values currently available for this DataSet as a list of YMeasure objects function get_measures function get_measures function get_measures vector lt YMeasure gt get_measures NSMutableArray measures function get_measures TYMeasureArray function get_measures As List List lt YM
8. lt TT gt lt php include yocto_api php yRegisterHub http 127 0 0 1 4444 Smodule yFirstModule while is_ null Smodule printi ss ss lt br gt Smodulle gt get iserralNumber i S module gt get_productName Smodule Smodule gt nextModule 2 gt lt eILS lt BODY gt lt HTML gt www yoctopuce com 45 10 Using Yocto Amp with PHP 10 4 HTTP callback API and NAT filters The PHP library is able to work in a specific mode called HTTP callback Yocto API With this mode you can control Yoctopuce devices installed behind a NAT filter such as a DSL router for example and this without needing to open a port The typical application is to control Yoctopuce devices located on a private network from a public web site The NAT filter advantages and disadvantages A DSL router which translates network addresses NAT works somewhat like a private phone switchboard a PBX internal extensions can call each other and call the outside but seen from the outside there is only one official phone number that of the switchboard itself You cannot reach the internal extensions from the outside www mysite com 192 168 0 1 64 136 20 37 BES 46 14 51 32 192 168 0 102 B Typical DSL configuration LAN machines are isolated from the outside by the DSL router Transposed to the network we have the following appliances connected to your home automation network can communica
9. the number of functions on the module On failure throws an exception or returns a negative error code www yoctopuce com 157 21 High level API Reference module functionld YModule Retrieves the hardware identifier of the nth function on the module function functionld functionIndex function functionld functionIndex function functionld functionIndex string functionld int functionIndex NSString functionld int functionIndex function functionld functionIndex integer string function functionld ByVal functionIndex As Integer As String string functionld int functionIndex def functionld functionIndex Parameters functionIndex the index of the function for which the information is desired starting at O for the first function Returns a string corresponding to the unambiguous hardware identifier of the requested module function On failure throws an exception or returns an empty string 158 www yoctopuce com 21 High level API Reference module functionName YModule Retrieves the logical name of the nth function on the module function functionName functionIndex function functionName functionIndex function functionName functionIndex string functionName int functionIndex NSString functionName int functionindex function functionName functionIndex integer string function functionName ByVal functionIndex As Integer As String string f
10. 21 High level API Reference current set_logFrequency current setLogFrequency Changes the datalogger recording frequency for this function function set_logFrequency newval function set_logFrequency newval function set_logFrequency newval int set_logFrequency const string amp newval int setLogFrequency NSString newval function set_logFrequency newval string integer function set_logFrequency ByVal newval As String As Integer int set_logFrequency string newval int set_logFrequency String newval def set_logFrequency newval YCurrent target set_logFrequency newval YCurrent The frequency can be specified as samples per second as sample per minute for instance 15 m or in samples per hour eg 4 h To disable recording for this function use the value OFF r Parameters Returns YAPI_SUCCESS if the call succeeds On failure throws an exception or returns a negative error code newval a string corresponding to the datalogger recording frequency for this function www yoctopuce com 231 21 High level API Reference current set_logicalName YCurrent current setLogicalName Changes the logical name of the current sensor function set_logicalName newval function set_logicalName newval function set_logicalName newval int set_logicalName const string amp newval int setLogicalName NSString newval function set_logicalName
11. As YRETCODE YRETCODE get_errorType int get_errorType def get_errorType This method is mostly useful when using the Yoctopuce library with exceptions disabled Returns a number corresponding to the code of the latest error that occured while using this module object www yoctopuce com 163 21 High level API Reference module gt get_firmwareRelease YModule module gt firmwareRelease Returns the version of the firmware embedded in the module function get_firmwareRelease function get_firmwareRelease function get_firmwareRelease string get_firmwareRelease NSString firmwareRelease function get_firmwareRelease string function get_firmwareRelease As String string get_firmwareRelease String get_firmwareRelease def get_firmwareRelease YModule target get_firmwareRelease Returns a string corresponding to the version of the firmware embedded in the module On failure throws an exception or returns Y_F TRMWARERELEASE_INVALID 164 www yoctopuce com 21 High level API Reference module get_hardwareld module gt hardwareld Returns the unique hardware identifier of the module function get_hardwareld function get_hardwareld function get_hardwareld string get_hardwareld NSString hardwareld function get_hardwareld As String string get_hardwareld String get_hardwareld def get_hardwareld YModule The
12. a floating point number corresponding to the minimal value observed On failure throws an exception or returns Y_LOWESTVALUE_INVALID YCurrent 214 www yoctopuce com 21 High level API Reference current get_module current gt module YCurrent Gets the YModule object for the device on which the function is located function get_module function get_module function get_module YModule get_module YModule module function get_module TYModule function get_module As YModule YModule get_module YModule get_module def get_module If the function cannot be located on any module the returned instance of YModu1e is not shown as on line Returns an instance of YModule www yoctopuce com 215 21 High level API Reference current get_module_async YCurrent current gt module_async Gets the YModule object for the device on which the function is located asynchronous version function get_module_async callback context function get_module_async callback context If the function cannot be located on any module the returned YModule object does not show as on line This asynchronous version exists only in Javascript It uses a callback instead of a return value in order to avoid blocking Firefox javascript VM that does not implement context switching during blocking I O calls See the documentation section on asynchronous Javascript calls for more
13. logicalName String modifiable advertisedValue String read only unit String read only currentValue Floating point number read only lowestValue Floating point number modifiable highestValue Floating point number modifiable currentRawValue Floating point number read only logFrequency Frequency modifiable reportFrequency Frequency modifiable calibrationParam 16 bit word array modifiable resolution Floating point number modifiable dataLogger DataLogger attribute type modifiable logicalName String modifiable advertisedValue String read only currentRuniIndex Integer read only timeUTC UTC time modifiable recording On Off modifiable autoStart On Off modifiable clearHistory Boolean modifiable 7 3 Module control interface This interface is identical for all Yoctopuce USB modules It can be used to control the module global parameters and to enumerate the functions provided by each module productName Character string containing the commercial name of the module as set by the factory serialNumber Character string containing the serial number unique and programmed at the factory For a Yocto Amp module this serial number always starts with YAMPMKO1 You can use the serial number to access a given module by software www yoctopuce com 21 7 Programming general concepts logicalName Character string containing the logical name of the module initially empty This attribute can be modified at will by the user O
14. s lt serial or logical name gt ON OFF n exe exit 1 int maan ink arger const cher angi ih NSError error autoreleasepool Setup the API to use local USB devices TE VAP eRe gwsitdersHub Gus Oe error e ArT SUCCESS mat NSLog RegisterHub error error localizedDescription return 1 Tiverge 2 usage argv 0 NSString serial or name NSString stringWithUTF8String argv 1 YModule module YModule FindModule serial or name use serial or logical name if module isOnline a0 large So 4 if stremp argv 2 ON 0 module setBeacon Y BEACON ON else module setBeacon Y BEACON OFF NSLog serial S n module serialNumber NSLog logical name n module logicalName NSLog luminosity Sd n module luminosity NSLog beacon Lee if module beacon Y_BEACON_ON www yoctopuce com 61 12 Using Yocto Amp with Objective C NSLog ON n else NSLog OFF n NSLog upTime d sec n module upTime 1000 NSLog USB current d mA n module usbCurrent NSLog logs n module get_lastLogs else NSLog not connected check identification and USB cable n serial or name Each property xxx of the module can be read thanks to a method of type get xxxx and properties which are not read only can be modified with the help of the set xxx method For more details regarding the used functions refer
15. string get_productName NSString productName function get_productName string function get_productName As String string get_productName String get_productName def get_productName YModule target get_productName Returns a string corresponding to the commercial name of the module as set by the factory On failure throws an exception or returns Y_PRODUCTNAME_INVALID 172 www yoctopuce com 21 High level API Reference module get_productRelease module gt productRelease Returns the hardware release version of the module function get_productRelease function get_productRelease function get_productRelease int get_productRelease int productRelease function get_productRelease LongInt function get_productRelease As Integer int get_productRelease int get_productRelease def get_productRelease YModule target get_productRelease Returns an integer corresponding to the hardware release version of the module On failure throws an exception or returns Y_PRODUCTRELEASE_INVALID YModule www yoctopuce com 173 21 High level API Reference module get_rebootCountdown YModule module rebootCountdown Returns the remaining number of seconds before the module restarts or zero when no reboot has been scheduled function get_rebootCountdown function get_rebootCountdown function get_rebootCountdown int get_rebootCou
16. 21 High level API Reference measure get_startTimeUTC YMeasure measure gt startTimeUTC Returns the start time of the measure relative to the Jan 1 1970 UTC Unix timestamp function get_startTimeUTC function get_startTimeUTC function get_startTimeUTC double get_startTimeUTC double startTimeUTC function get_startTimeUTC double function get_startTimeUTC As Double double get_startTimeUTC double get_startTimeUTC def get_startTimeUTC When the recording rate is higher then 1 sample per second the timestamp may have a fractional part Returns an floating point number corresponding to the number of seconds between the Jan 1 1970 UTC and the beginning of this measure www yoctopuce com 291 292 www yoctopuce com 22 Troubleshooting 22 1 Linux and USB To work correctly under Linux the the library needs to have write access to all the Yoctopuce USB peripherals However by default under Linux USB privileges of the non root users are limited to read access To avoid having to run the VirtualHub as root you need to create a new udev rule to authorize one or several users to have write access to the Yoctopuce peripherals To add a new udev rule to your installation you must add a file with a name following the arbitraryName rules format in the etc udev rules d directory When the system is starting udev reads all the files with a rules extension in this di
17. 29 33 41 51 59 65 71 79 85 91 97 yPreregisterHub 136 yRegisterDeviceArrivalCallback 137 yRegisterDeviceRemovalCallback 138 yRegisterHub 139 yRegisterHubDiscoveryCallback 140 yRegisterLogFunction 141 ySelectArchitecture 142 ySetDelegate 143 ySetTimeout 144 ySleep 145 yUnregisterHub 146 yUpdateDeviceList 147 yUpdateDeviceList_async 148
18. ByVal msValidity As Integer As YRETCODE YRETCODE load int msValidity int load long msValidity def load msValidity By default whenever accessing a device all function attributes are kept in cache for the standard duration 5 ms This method can be used to temporarily mark the cache as valid for a longer period in order to reduce network trafic for instance Parameters msValidity an integer corresponding to the validity attributed to the loaded function parameters in milliseconds Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code 224 www yoctopuce com 21 High level API Reference current loadCalibrationPoints YCurrent Retrieves error correction data points previously entered using the method calibrateFromPoints function loadCalibrationPoints rawValues refValues function loadCalibrationPoints rawValues refValues function loadCalibrationPoints amp rawValues amp refValues int loadCalibrationPoints vector lt double gt amp rawValues vector lt double gt amp refValues int loadCalibrationPoints NSMutableArray rawValues NSMutableArray refValues function loadCalibrationPoints var rawValues TDoubleArray var refValues TDoubleArray LongInt procedure loadCalibrationPoints int loadCalibrationPoints List lt double gt rawValues List lt double gt refValues int loadCalibrationPoints ArrayList lt Dou
19. HTTP 46 119 InitAPI YAPI 135 Installation 65 71 Installing 29 Integration 56 Interface 150 195 238 Introduction 1 isOnline YCurrent 221 isOnline YDataLogger 260 isOnline YModule 179 isOnline_async YCurrent 222 isOnline_async YDataLogger 261 isOnline_async YModule 180 J Java 91 Javascript 33 L Languages 119 Libraries 121 Library 56 85 124 Limitations 31 Linux 293 load YCurrent 223 load YDataLogger 262 load YModule 181 load_async YCurrent 225 load_async YDataLogger 263 load_async YModule 182 loadCalibrationPoints YCurrent 224 loadMore YDataSet 283 loadMore_async YDataSet 284 Localization 11 Logger 112 Measured 286 Module 11 20 21 30 35 43 53 61 68 74 81 87 93 102 150 N Native 24 97 NET 65 nextCurrent YCurrent 226 nextDataLogger YDataLogger 264 nextModule YModule 183 O Objective C 59 Optional 3 P Paradigm 19 Platforms 294 Port 98 Porting 124 Power 17 Preparation 79 PreregisterHub YAPI 136 Prerequisites 1 Presentation 5 Programming 19 26 109 Project 65 71 Python 85 R reboot YModule 184 Recorded 273 Reference 125 RegisterDeviceArrivalCallback YAPI 137 RegisterDeviceRemovalCallback YAPI 138 RegisterHub YAPI 139 RegisterHubDiscoveryCalloack YAPI 140 RegisterLogFunction YAPI 141 registerTimedReportCallback YCurrent 227 registerValueCallback YCurrent 228 registerValueCallback YDataLogger 265 revertFromFlash
20. Hot plug is easy just check that the device is online if current isOnline Use current get_currentValue EAN Let s look at these lines in more details YAPI RegisterHub The yAPI RegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for When used with the parameter usb it will use the modules locally connected to the computer running the library If the initialization does not succeed this function returns a value different from YAPI SUCCESS and errmsg contains the error message YCurrent FindCurrent The YCurrent FindCurrent function allows you to find a current sensor from the serial number of the module on which it resides and from its function name You can use logical names as well as long as you have initialized them Let us imagine a Yocto Amp module with serial number YAMPMK01 123456 which you have named MyModule and for which you have given the current1 function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once current YCurrent FindCurrent YAMPMK01 123456 current1 current YCurrent FindCurrent YAMPMK01 123456 MyFunction current YCurrent FindCurrent MyModule current1 current YCurrent FindCurrent MyModule MyFunction current YCurrent FindCurrent MyFunction YCurrent FindCurrent returns an object which you can then use at will to control the current sensor is
21. PON gt a Measures are instances of YMeasure They store simultaneously the minimal average and maximal value at a given time that you can retrieve using methods get_minValue get_averageValue and get_maxValue respectively Here is a small example that uses the functions above We will retrieve all measures without time limit parabe fdardce ni sens ora Gelemsne Corcded Dai Oj mO i First call to loadMore loads the summary preview dataset loadMore YMeasure summary dataset get_summary string timeFmt dd MMM yyyy hh mm ss fff string logFmt from 0 to 1 average 2 0 00 3 Console WriteLine String Format logFmt summary get_startTimeUTC_asDateTime ToString timeFmt summary get_endTimeUTC_asDateTime ToString timeFmt summary get_averageValue sensor get_unit 2The YMeasure objects used by the data logger are exactly the same kind as those passed as argument to the timed report callbacks www yoctopuce com 113 19 Advanced programming Next calls to loadMore will retrieve measures Console WriteLine loading details int progress dom Console Write progress dataset loadMore while progress lt 100 All measures have now been loaded Mot Meds Ure decease taseme mea Ur eS foreach YMeasure m in details Console WriteLine String Format logFmt m get_startTimeUTC_asDateTime ToString timeFmt m get_endTimeUTC_asDateTime ToStri
22. Spinner findViewById R id spinnerl my spin setOnItemSelectedListener this aa new ArrayAdapter lt String gt this android R layout simple spinner item aa setDropDownViewResource android R layout simple spinner dropdown item my spin setAdapter aa Override protected void onStart Ssuper onStart 7 try aa clear YAPI EnableUSBHost this YAPI RegisterHub usb YModule r YModule FirstModule while r null String hwid r get_hardwarelId aa add hwid r r nextModule je Cacch s VAPTEEXCGepiVonmc af e printStackTrace refresh Spinner with detected relay aa notifyDataSetChanged Override protected void onStop super onStop YAPI FreeAPI private void DisplayModuleInfo TextView field if module null ESM M try field TextView findViewById R id serialfield field setText module getSerialNumber field TextView findViewById R id logicalnamefield field setText module getLogicalName field TextView findViewById R id luminosityfield field setText String format Sd module getLuminosity field TextView findViewById R id uptimefield field setText module getUpTime 1000 sec field TextView findViewById R id usbcurrentfield field setText module getUsbCurrent mA Switch sw Switch findViewById R id beaconswitch Log d switch Wbedcon mod
23. The command line API is in fact made of a group of small executables which are easy to call Their output is also easy to analyze As most programming languages allow you to make system calls the issue is solved with a few lines of code However if the command line API is the easiest solution it is neither the fastest nor the most efficient For each call the executable must initialize its own API and make an inventory of USB connected modules This requires about one second per call 20 2 VirtualHub and HTTP GET The VirtualHub is available on almost all current platforms It is generally used as a gateway to provide access to Yoctopuce modules from languages which prevent direct access to hardware layers of a computer JavaScript PHP Java In fact the VirtualHub is a small web server able to route HTTP requests to Yoctopuce modules This means that if you can make an HTTP request from your programming language you can drive Yoctopuce modules even if this language is not officially supported REST interface At a low level the modules are driven through a REST API Thus to control a module you only need to perform appropriate requests on the Virtua Hub By default the VirtualHub HTTP port is 4444 An important advantage of this technique is that preliminary tests are very easy to implement You only need a VirtualHub and a simple web browser If you copy the following URL in your preferred browser while the Virtua Hub is r
24. This function does not require that the module is online at the time it is invoked The returned object is nevertheless valid Use the method YModule isOnline to test if the module is indeed online at a given time In case of ambiguity when looking for a module by logical name no error is notified the first instance found is returned The search is performed first by hardware name then by logical name Parameters func a string containing either the serial number or the logical name of the desired module Returns a YModule object allowing you to drive the module or get additional information on the module www yoctopuce com 153 21 High level API Reference YModule FirstModule YModule yFirstModule Starts the enumeration of modules currently accessible function yFirstModule nodejs function FirstModule function yFirstModule cpp _ YModule yFirstModule m YModule yFirstModule function yFirstModule TYModule function yFirstModule As YModule YModule FirstModule YModule FirstModule def FirstModule Use the method yModule nextModule to iterate on the next modules Returns a pointer to a YModule object corresponding to the first module currently online or a null pointer if there are none 154 www yoctopuce com 21 High level API Reference module describe Returns a descriptive text that identifies the module function describe
25. and this is not available to every web server This technique has a direct application in home automation a few Yoctopuce modules a PHP server and you can interact with your home from anywhere on the planet as long as you have an internet connection PHP is one of those languages which do not allow you to directly access the hardware layers of your computer Therefore you need to run a virtual hub on the machine on which your modules are connected To start your tests with PHP you need a PHP 5 3 or more server preferably locally on you machine If you wish to use the PHP server of your internet provider it is possible but you will probably need to configure your ADSL router for it to accept and forward TCP request on the 4444 port 10 1 Getting ready Go to the Yoctopuce web site and download the following items The PHP programming library e The VirtualHub software for Windows Mac OS X or Linux depending on your OS Decompress the library files in a folder of your choice accessible to your web server connect your modules run the VirtualHub software and you are ready to start your first tests You do not need to install any driver 10 2 Control of the Current function A few lines of code are enough to use a Yocto Amp Here is the skeleton of a PHP code snipplet to use the Current function include yocto_api php UNciuce My OCEOmCuUIEIBe mE plain 1A couple of free PHP servers easyPHP for Windows MAMP
26. check identification and USB cable exit end Writeln Current logical name tmodule get_logicalName Write Enter new name Readln newname if not yCheckLogicalName newname then begin Writeln invalid logical name exit end module set_logicalName newname module saveToFlash Writeln logical name is now module get_logicalName end Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not nil Below a short example listing the connected modules program inventory SAPPTYPE CONSOLE uses Svsuiiils yocto_api var module TYModule errmsg string begin Setup the API to use local USB devices if yRegisterHub usb errmsg lt gt YAPI SUCCESS then begin Write RegisterHub error errmsg exit end
27. function get_logicalName function get_logicalName string get_logicalName NSString logicalName function get_logicalName string function get_logicalName As String string get_logicalName String get_logicalName def get_logicalName YModule target get_logicalName Returns a string corresponding to the logical name of the module On failure throws an exception or returns Y_LOGICALNAME_INVALID 168 www yoctopuce com 21 High level API Reference module gt get_luminosity YModule module gt luminosity Returns the luminosity of the module informative leds from 0 to 100 function get_luminosity function get_luminosity function get_luminosity int get_luminosity int luminosity function get_luminosity LongInt function get_luminosity As Integer int get_luminosity int get_luminosity def get_luminosity YModule target get_luminosity Returns an integer corresponding to the luminosity of the module informative leds from 0 to 100 On failure throws an exception or returns Y_LUMINOSITY_INVALID www yoctopuce com 169 21 High level API Reference module gt get_persistentSettings YModule module gt persistentSettings Returns the current state of persistent module settings function get_persistentSettings function get_persistentSettings function get_persistentSettings Y_PERSISTENTSETTINGS_ enum get_persistentSettin
28. gt lt br gt ii Grsisct GmGhllmbeaconm i ia if _GET beacon ON module gt set_beacon Y BEACON ON else S module gt set_beacon Y BEACON OFF printf serial s lt br gt module gt get_serialNumber printf logical name s lt br gt module gt get_logicalName printf luminosity s lt br gt module gt get_luminosity Primi oeacons uE if Smodule gt get_beacon Y BEACON ON printf lt input type radio name beacon value ON checked gt ON printf lt input type radio name beacon value OFF gt OFF lt br gt else printf lt input type radio name beacon value ON gt ON printf lt input type radio name beacon value OFF checked gt OFF lt br gt printf upTime s sec lt br gt intVal S module gt get_upTime 1000 Orsinite tC MUSBmeunsre mite ssmA lt br gt Smodule gt get_usbCurrent printf logs lt br gt lt pre gt s lt pre gt module gt get_lastLogs Be lt input type submit value refresh gt lt FORM gt lt BODY gt lt HTML gt Each property xxx of the module can be read thanks to a method of type get _xxxx and properties which are not read only can be modified with the help of the set xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding set _xxx fun
29. long newval def set_timeUTC newval Y DataLogger target set_timeUTC newval Parameters newval an integer corresponding to the current UTC time reference used for recorded data Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code 270 www yoctopuce com 21 High level API Reference datalogger set_userData YDataLogger datalogger setUserData Stores a user context provided as argument in the userData attribute of the function function set_userData data function set_userData data function set_userData data void set_userData void data void setUserData void data procedure set_userData data Tobject procedure set_userData ByVal data As Object void set_userData object data void set_userData Object data def set_userData data This attribute is never touched by the API and is at disposal of the caller to store a context Parameters data any kind of object to be stored www yoctopuce com 271 21 High level API Reference datalogger wait_async YDataLogger Waits for all pending asynchronous commands on the module to complete and invoke the user provided callback function function wait_async callback context function wait_async callback context The callback function can therefore freely issue synchronous or asynchronous commands without risking to block the Javascript VM Paramete
30. then by logical name Parameters func a string that uniquely characterizes the current sensor Returns a YCurrent object allowing you to drive the current sensor 198 www yoctopuce com 21 High level API Reference YCurrent FirstCurrent yFirstCurrent Starts the enumeration of current sensors currently accessible function yFirstCurrent function FirstCurrent function yFirstCurrent YCurrent yFirstCurrent YCurrent yFirstCurrent function yFirstCurrent TYCurrent function yFirstCurrent As YCurrent lt lt lt x YCurrent FirstCurrent YCurrent FirstCurrent def FirstCurrent Use the method yCurrent nextCurrent to iterate on next current sensors YCurrent Returns a pointer to a YCurrent object corresponding to the first current sensor currently online or a null pointer if there are none www yoctopuce com 199 21 High level API Reference current gt calibrateFromPoints YCurrent Configures error correction data points in particular to compensate for a possible perturbation of the measure caused by an enclosure function calibrateFromPoints rawValues refValues function calibrateFromPoints rawValues refValues function calibrateFromPoints rawValues refValues int calibrateFromPoints vector lt double gt rawValues vector lt double gt refValues int calibrateFromPoints NSMutableArray rawValues NSMutableArra
31. use the IP address 127 0 0 1 callback that keywork make the API run in HTTP Callback mode This a special mode allowing to take control of Yoctopuce devices through a NAT filter when using a VirtualHub ou a networked YoctoHub You only need to configure your hub to call your server script on a regular basis This mode is currently available for PHP and Node JS only Be aware that only one application can use direct USB access at a given time on a machine Multiple access would cause conflicts while trying to access the USB modules In particular this means that you must stop the VirtualHub software before starting an application that uses direct USB access The workaround for this limitation is to setup the library to use the VirtualHub rather than direct USB access If acces control has been activated on the hub virtual or not you want to reach the URL parameter should look like http username password adresse port You can call RegisterHub several times to connect to several machines Parameters url a string containing either usb callback or the root URL of the hub to monitor errmsg a string passed by reference to receive any error message Returns YAPI SUCCESS when the call succeeds On failure throws an exception or returns a negative error code 140 www yoctopuce com 21 High level API Reference YAPI RegisterHubDiscoveryCallback YAPI yRegisterHubDiscoveryCallback Register a callback
32. 79 15 2 Control of the Current fUNCtION 0 eee ee ceeeeeesecee teens ceeeeneeeeeaeeeessanenecnanenesnaneeeesneeeenenaeees 79 15 3 Controlorthe module part seirene ate atti 81 15 4 EPrOPMANGIING iesi si oetheiteeieiy evecare bie ednesday Halhateede tin bie 83 16 Using the Yocto Amp with Python oo cece ee eeeeeseeseeeeneenesneneens 85 16 1 SOUCE FIGS sicciedsdeveds aa ee EE aaa a E E tutu aa Eana can Metra arinaa aea Gentes 85 KRYDDA STKE TA E E T E A siete 85 16 3 Control of the Current function oo eee eeeeeeeeeneeeeeenee ee tee cette aeeeeeeaeeee teeter seaeeeeeeneeeeseneaeees 85 16 4 Control of the module part 0 eee ce eeseceeeeseeeeeeceeneseeneneesesaeeceesaeaeseeaaeesessaneseeseneneennees 87 16 5 ErrorNnangling r a cee baci E A ea dierent 89 17 Using the Yocto Amp With Java oo ccc cee ees cette eeneeteneeseeteeteeneeeeeee 91 17 1 GOING AE e V A E E evened hh Ad aha ten i cuesia cia dena TEET 91 17 2 Control of the Current function 2 eee eeee ee enee ee eete cette nets eeeaeeeeeeaeeeeeeeeeeeeaeeeeseeaeesenaaeees 91 1 7 3 Control of the module part sea ka aaa wane Ale RR Aaa AREAS 93 1724 EmrOr Nand INA a eara tei i ea EE A ees ites Ea de ls eee 95 18 Using the Yocto Amp with Android oo ccec cece ee eeeeeseeseeeeneeeeeees 97 18 1 Native access and VirtualHub oo eee eeenee ee eene eee ee aces eeaaeeeeeeaeeeeseeeeeeeaeeeeseeaeeeenaeees 97 18 2 GOING TOADY a a a e aT Ear ae E Tai Ea a r aa A a iaraa aaae Aa Taa
33. Heanor lengi hE if args 1 equalsIgnoreCase ON module setBeacon YModule BEACON_ ON elge i module setBeacon YModule BEACON OFF System out printin serial module get_serialNumber System out println logical name module get_logicalName System out println luminosity module get_luminosity if module get_beacon YModule BEACON ON System out printlin beacon ON 7 r eles d System out printlin beacon ORENA System out printin upTime module get_upTime 1000 sec System out printin USB current module get_usbCurrent a As System out println logs n module get_lastLogs catch YAPI Exception ex System out printin args 1 not connected check identification and USB cable NGNIEME Gig selSVeyNEME Each property xxx of the module can be read thanks to a method of type YModule get xxxx and properties which are not read only can be modified with the help of the YModule set xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding YModule set xxx function However this modification is performed only in the random access memory RAM of the module if the module is restarted the modifications are lost To memorize them persistently it is necessary to ask the module to save its current c
34. Hz DC 5 mA 3 2 mA 1 2 mA 0 3 Windows Linux Intel ARM Mac OS X Android no driver needed C Objective C C VB NET Delphi Python Java Android Javascript Node js PHP Java yes 0x24E0 0x001F YoctoBox Long Thick Black Vents www yoctopuce com 295 23 Characteristics 296 www yoctopuce com 56 15 5 15 5 A D Q o o pranan 200801 y d wweoo fEl L JO J soraz om ise Live tho To o oo al omnem J I 0 U a Vv OREO OE O a io 4 5 MAX All dimensions are in mm Toutes les dimensions sont en mm Yocto Amp A4 Scale Echelle Index A Access 97 Accessories 3 Activating 98 Advanced 109 Alternating 9 Android 97 98 Assembly 15 Basic 65 Blueprint 297 C C 71 C 51 56 calibrateFromPoints YCurrent 199 Calibration 114 Callback 46 Characteristics 295 CheckLogicalName YAPI 127 Command 29 119 Compatibility 97 Components 7 Concepts 19 Connections 15 16 Current 9 22 30 33 41 51 59 66 72 79 85 91 100 195 D Dangerous 7 Data 112 273 DataLogger 23 238 Delphi 79 describe YCurrent 200 describe YDataLogger 241 describe
35. REM we need to retreive both DC and AC voltage from the device If sensor isOnline Then m sensor get_module sensorDC yFindCurrent m get_serialNumber current1 ScnsonAcy yHindeurrnrenite m cet ses aliNumben CUEN EA Else Die Module not connected End If While True If Not m isOnline Then Die Module not connected ConsolemWrite DE sensor De get eurrentvalue k loser moi Consoles Write VAC NS sensorAG gericunrenuvalue To String Console WriteLine press Ctrl C to exit ySleep 1000 errmsg End While End Sub End Module ime used with all side www yoctopuce com 67 13 Using Yocto Amp with Visual Basic NET 13 4 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon Imports System 10 Imports System Environment Module Modulel Sub usage Console WriteLine usage demo lt serial or logical name gt ON OFF End End Sub Sub Main Dim argv As String System Environment GetCommandLineArgs Dim errmsg As String Dim m As ymodule Te yeeie tery USDOL ETAn lt 7 VARIT ol Clo 5 Mren Console WriteLine RegisterHub error errmsg End End If If argv Length lt 2 Then usage m yFindModule argv 1 REM use serial or logical name rf m isOnline Li aroy tengih gt 2 Th
36. Teady oiio eene ceed ceded NAE a Eae EAN A EEA E EE EEr ASNE A eiia 33 9 2 Control of the Current FUNCTION oo eee ceeeeeeeeeeeeeeeeeeeeteaeeeeteaeeeeseaeeeeseaaeeeseaaeeeeeeeeeeeeneeeetaas 33 9 3 Control of the Module Part oo eee ceeeseseeeceseeeeeseneceesaeeeeesaesenenaaaenessaeeeecnaneeeesneeeesineeteaas 35 9 4 Error handling EEE E E E EE A E TEEST 38 10 Using Yocto Amp with PHP oo ccees ces eesceneeneetesnesteseeteeteetesneeee 41 TOA GOMING TOADS nnana e e tee e shaves a e e aap et iaaa 41 10 2 Control of the Current function ssssssssssessrnsssrrsnsrnrssrrnsttrntsttrnstnrnnentnntennantnneatenaetnnnteenne 41 10 3 lt C nirok f the module part a er E a 43 10 4 HTTP callback API and NAT filters eesseeeeesiieeiissesirssriiresinstrirneitinstrirnsrnnnnrinnnerennnet 46 10 5 Eror Aandling sor rana reaa rada ALEE aT cece deamon rns teed EA Taa T EEAO EEEF 49 11 Using Yocto Amp with C once ccs ces ees teseenesneeseeseeseeseesesneeseeseeseeseeeee 51 11 1 Control of the Current fUNCtION sesei tiddi aeda irtad iiri 51 11 2 Control of the module part ii cicicci he iecsspeceasceptiasided decace du sdeasephabsd duds caeaesbeedudatianahdciseesseeet 53 11 8 Error handling esien aint iid vente ald ee neler 56 11 4 Integration variants for the C Yoctopuce library cccccccceeeseeeeeeeeeeeeeeneeeeeeteeeeteeeeeeees 56 12 Using Yocto Amp with Objective C ooo eeseesteeesteeseesteseesteenen 59 121 G ntr lof the Current TUN
37. YAPI HandleEvents from this thread 110 www yoctopuce com 19 Advanced programming The value change callback This type of callback is called when a current sensor changes in a significant way It takes as parameter the relevant function and the new value as a character string static void valueChangeCallback YCurrent fct string value Console Writehinel fel ger handwaneikd 2 value In most programming languages callbacks are global procedures not methods If you wish for the callback to call a method of an object define your callback as a global procedure which then calls your method If you need to keep a reference to your object you can store it directly in the YCurrent object using function set _userData You can then retrieve it in the global callback procedure using get_userData Setting up a value change callback The callback is set up for a given Current function with the help of the registerValueCallback method The following example sets up a callback for the first available Current function YCurrent f YCurrent FirstCurrent f registerValueCallback current1ChangeCallBack Note that each module function can thus have its own distinct callback By the way if you like to work with value change callbacks you will appreciate the fact that value change callbacks are not limited to sensors but are also available for all Yoctopuce devices for instance you can also receive a callb
38. YModule 154 Description 29 Direct 9 DisableExceptions YAPI 128 Distribution 17 download YModule 155 Dynamic 85 121 E Electrocution 7 Elements 5 6 EnableExceptions YAPI 129 EnableUSBHost YAPI 130 Error 38 49 56 63 70 76 83 89 95 107 Event 109 F Files 85 Filters 46 FindCurrent YCurrent 197 FindDataLogger YDataLogger 239 FindModule YModule 152 FirstCurrent YCurrent 198 FirstDataLogger YDataLogger 240 FirstModule YModule 153 Fixing 15 forgetAllDataStreams YDataLogger 242 FreeAPI YAPI 131 functionCount YModule 156 functionld YModule 157 functionName YModule 158 Functions 126 functionValue YModule 159 G General 19 29 126 get_advertisedValue YCurrent 201 get_advertisedValue YDataLogger 243 get_autoStart YDataLogger 244 get_averageValue YMeasure 286 get_beacon YModule 160 get_currentRawValue YCurrent 202 get_currentRunIndex YDataLogger 245 get_currentValue YCurrent 203 get_dataSets YDataLogger 246 get_dataStreams YDataLogger 247 get_endTimeUTC YDataSet 274 get_endTimeUTC YMeasure 287 get_errorMessage YCurrent 204 get_errorMessage YDataLogger 248 get_errorMessage YModule 161 get_errorType YCurrent 205 get_errorType YDataLogger 249 get_errorType YModule 162 get_firmwareRelease YModule 163 get_friendlyName YCurrent 206 get_friendlyName YDataLogger 250 get_functionDescriptor YCurrent 207 get_functionDescriptor YDataLogger 251 get_functionld YCurrent 208 ge
39. YRETCODE yHandleEvents NSError errmsg function yHandleEvents var errmsg string integer function yHandleEvents ByRef errmsg As String As YRETCODE YRETCODE HandleEvents ref string errmsg int HandleEvents def HandleEvents errmsg None If your program includes significant loops you may want to include a call to this function to make sure that the library takes care of the information pushed by the modules on the communication channels This is not strictly necessary but it may improve the reactivity of the library for the following commands This function may signal an error in case there is a communication problem while contacting a module Parameters errmsg a string passed by reference to receive any error message Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 135 21 High level API Reference YAPI InitAPI ylnitAPI Initializes the Yoctopuce programming library explicitly function yInitAPI mode errmsg node js function InitAPI mode errmsg function yInitAPI mode amp errmsg YRETCODE yInitAPI int mode string amp errmsg YRETCODE yInitAPI int mode NSError errmsg function yInitAPI mode integer var errmsg string integer _ v function ylnitAPI ByVal mode As Integer ByRef errmsg As String As Integer int InitAPI int mode ref string errmsg synchronized static int InitAPI
40. a get_currentValue method returns a Y CURRENTVALUE INVALID value and so on In any case the returned value is of the expected type and is not a null pointer which would risk crashing your program At worst if you display the value without testing it it will be outside the expected bounds for the returned value In the case of functions which do not normally return information the return value is YAPI SUCCESS if everything went well and a different error code in case of failure When you work without exceptions you can obtain an error code and an error message explaining the source of the error You can request them from the object which returned the error calling the errType and errMessage methods Their returned values contain the same information as in the exceptions when they are active www yoctopuce com 89 90 www yoctopuce com 17 Using the Yocto Amp with Java Java is an object oriented language created by Sun Microsystem Beside being free its main strength is its portability Unfortunately this portability has an excruciating price In Java hardware abstraction is so high that it is almost impossible to work directly with the hardware Therefore the Yoctopuce API does not support native mode in regular Java The Java API needs a Virtual Hub to communicate with Yoctopuce devices 17 1 Getting ready Go to the Yoctopuce web site and download the following items The
41. automatically finds the API source files 16 2 Dynamic library A section of the low level library is written in C but you should not need to interact directly with it it is provided as a DLL under Windows as a so files under UNIX and as a dylib file under Mac OS X Everything was done to ensure the simplest possible interaction from Python the distinct versions of the dynamic library corresponding to the distinct operating systems and architectures are stored in the cdll directory The API automatically loads the correct file during its initialization You should not have to worry about it If you ever need to recompile the dynamic library its complete source code is located in the Yoctopuce C library In order to keep them simple all the examples provided in this documentation are console applications Naturally the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface 16 3 Control of the Current function A few lines of code are enough to use a Yocto Amp Here is the skeleton of a Python code snipplet to use the Current function 1 http www python org download www yoctopuce com EN libraries php www yoctopuce com 85 16 Using the Yocto Amp with Python erences errmsg YRef Param Get access to your device connected locally on USB for instance YAPI RegisterHub usb errmsg current YCurrent FindCurrent YAMPMK01 123456 current1
42. beforehand have the adequate firmware on your local disk Firmware destined for Yoctopuce modules are available as byn files and can be downloaded from the Yoctopuce web site To update a firmware simply click on the upgrade button on the configuration window and follow the instructions If the update fails for one reason or another unplug and re plug the module and start the update process again This solves the issue in most cases If the module was unplugged while it was being reprogrammed it does probably not work anymore and is not listed in the interface However it is always possible to reprogram the module correctly by using the Virtual Hub software in command line 4 3 www yoctopuce com EN virtualhub php 4 More information available in the virtual hub documentation 12 www yoctopuce com 5 First steps Logical name of the module The logical name is a name that you choose which allows you to access your module in the same way a file name allows you to access its content A logical name has a maximum length of 19 characters Authorized characters are A Z a z 0 9 _ and If you assign the same logical name to two modules connected to the same computer and you try to access one of them through this logical name behavior is undetermined you have no way of knowing which of the two modules answers Luminosity This parameter allows you to act on the maximal intensity of the leds of the module This enables you i
43. but this time used with all side materials needed to make it work nicely as a small demo tinelude Myoctolapr hi include yocto_current h include lt iostream gt include lt stdlib h gt using namespace std 52 www yoctopuce com 11 Using Yocto Amp with C static void usage void cout lt usages demo lt serilalnumber gt lt endl cout lt lt a demo lt logical_name gt lt lt endl Celt 7 demo any use any discovered device lt lt endl u64 now yGetTickCount dirty active wait loop while yGetTickCount now lt 3000 exit 1 int Mein nt eiee Const char aro 1 string errmsg string target YCurrent sensor YCurrent sensorAC YCurrent sensorDC YModule ang 17 argc 2 usage target string argv 1 YAPI DisableExceptions Setup the API to use local USB devices Bien MAP ie Regisiter Hubli Musbu errmsg 9 IYARTISUCCESS la Cerra lt lt WReGrsiberHUD me cor Ae ermo a end return 1 if target any retreive any voltage sensor can be AC or DC sensor YCurrent FirstCurrent if sensor NULL cerr lt lt No module connected Check cable lt lt endl exit 1 else sensor YCurrent FindCurrent target currentl1 we need to retreive both DC and AC voltage from the device if sensor gt isOnline m sensor gt get_module sensore We uberis His sore lCwrardsioue Im 9gct iSe
44. data Stores a user context provided as argument in the userData attribute of the function current wait_async callback context Waits for all pending asynchronous commands on the module to complete and invoke the user provided callback function www yoctopuce com 197 21 High level API Reference YCurrent FindCurrent YCurrent yFindCurrent Retrieves a current sensor for a given identifier function yFindCurrent func nodejs function FindCurrent func function yFindCurrent func YCurrent yFindCurrent const string amp func YCurrent yFindCurrent NSString func function yFindCurrent func string TYCurrent function yFindCurrent ByVal func As String As YCurrent Y Current FindCurrent string func Y Current FindCurrent String func def FindCurrent func The identifier can be specified using several formats e FunctionLogicalName e ModuleSerialNumber Functionldentifier e ModuleSerialNumber FunctionLogicalName e ModuleLogicalName Functionldentifier e ModuleLogicalName FunctionLogicalName This function does not require that the current sensor is online at the time it is invoked The returned object is nevertheless valid Use the method YCurrent isOnline to test if the current sensor is indeed online at a given time In case of ambiguity when looking for a current sensor by logical name no error is notified the first instance found is returned The search is performed first by hardware name
45. data but this may saturate the USB hub Remember to call the saveToFlash method and then to reboot the module to apply this setting 7 4 Current function interface The Yoctopuce application programming interface allows you to read an instant measure of the sensor as well as the minimal and maximal values observed logicalName Character string containing the logical name of the current sensor initially empty This attribute can be modified at will by the user Once initialized to an non empty value it can be used to access the current sensor directly If two current sensors with the same logical name are used in the same 22 www yoctopuce com 7 Programming general concepts project there is no way to determine which one answers when one tries accessing by logical name The logical name is limited to 19 characters among A Z a z 0 9 _ and advertisedValue Short character string summarizing the current state of the current sensor that is automatically advertised up to the parent hub For a current sensor the advertised value is the measured value unit Short character string representing the measuring unit for the measured value currentValue Current in mA as a floating point number lowestValue Minimal current observed as a floating point number highestValue Maximal current observed as a floating point number logFrequency Datalogger recording frequency or OFF when measures should not be stored
46. def UpdateDeviceList errmsg None The library searches the machines or USB ports previously registered using yRegisterHub and invokes any user defined callback function in case a change in the list of connected devices is detected This function can be called as frequently as desired to refresh the device list and to make the application aware of hot plug events Parameters errmsg a string passed by reference to receive any error message Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code 148 www yoctopuce com 21 High level API Reference YAPI UpdateDeviceList_async YAPI yUpdateDeviceList_async Triggers a re detection of connected Yoctopuce modules function yUpdateDeviceList_async callback context function UpdateDeviceList_async callback context The library searches the machines or USB ports previously registered using yRegisterHub and invokes any user defined callback function in case a change in the list of connected devices is detected This function can be called as frequently as desired to refresh the device list and to make the application aware of hot plug events This asynchronous version exists only in Javascript It uses a callback instead of a return value in order to avoid blocking Firefox Javascript VM that does not implement context switching during blocking I O calls Parameters callback callback function that
47. ends with two empty lines that is a sequence of four ASCII characters 13 10 13 10 Here is a sample program written in pascal using the yapi d i DLL to read and then update the luminosity of a module www yoctopuce com 121 20 Using with unsupported languages Ar Dil functions Inport function yapilInitAPI mode integer errmsg k pansichar sinteger cdecl external yapi dill name yapilInitAPI function yapilUpdateDevicelist fonce integer ernrmsg pansichar integer icdecl external yapi dll name yapiUpdateDeviceList function yapiHTTPRequest device pansichar url pansichar buffer pansichar butisaze integer var EUSE neeger errmsg 3 pansichar integer caeci external yapi dll name yapiHTTPRequest var errmsgBuffer array 0 256 of ansichar dataBuffer array LO TTo 4 Mor anisae alc errmsg data pansitehar TE BUL Salva e A abinlielewsiee const serial YAMPMK01 12345 getValue GET api module luminosity HTTP 1 1 13 10 13 10 setValue GET api module luminosity 100 HTTP 1 1 13 10 13 10 begin errmsg G errmsgBuffer data dataBuffer API initialization if yapiInitAPI 1 errmsg lt 0 then begin writeln errmsg Dalit endi forces a device inventory if yapiUpdateDeviceList 1 errmsg lt 0 then begin writeln errmsg heey end requests the module luminosity if yapiHTTPRequest serial getValue data sizeof dataBuffer fullsize errmsg lt 0
48. function to be called each time a network hub or a VirtualHub is detected on the local network void RegisterHubDiscoveryCallback NewHubCallback callback Parameters callback a procedure taking a two string as parameter or null www yoctopuce com 141 21 High level API Reference YAPI RegisterLogFunction YAPI yRegisterLogFunction Registers a log callback function void yRegisterLogFunction yLogFunction logfun void yRegisterLogFunction yLogCallback logfun procedure yRegisterLogFunction logfun yLogFunc procedure yRegisterLogFunction ByVal logfun As yLogFunc cs void RegisterLogFunction yLogFunc logfun java _ void RegisterLogFunction LogCallback logfun def RegisterLogFunction logfun This callback will be called each time the API have something to say Quite usefull to debug the API Parameters logfun a procedure taking a string parameter or nul 1 142 www yoctopuce com 21 High level API Reference YAPI SelectArchitecture YAPI ySelectArchitecture Select the architecture or the library to be loaded to access to USB def SelectArchitecture arch By default the Python library automatically detects the appropriate library to use However for Linux ARM it not possible to reliably distinguish between a Hard Float armhf and a Soft Float armel install For in this case it is therefore recommended to manually select the proper architecture by calling SelectArch
49. functions through the REST interface The module functions can be manipulated in the same way To know the state of the current function build the following URL http 127 0 0 1 4444 bySerial YAMPMK01 12345 api current txt Note that if you can use logical names for the modules instead of their serial number you cannot use logical names for functions Only hardware names are authorized to access functions You can retrieve a module function attribute in a way rather similar to that used with the modules For example http 127 0 0 1 4444 bySerial YAMPMK01 12345 api current logicalName Rather logically attributes can be modified in the same manner http 127 0 0 1 4444 bySerial YAMPMK01 12345 api current logicalName myFunction You can find the list of available attributes for your Yocto Amp at the beginning of the Programming chapter Accessing Yoctopuce data logger through the REST interface This section only applies to devices with a built in data logger The preview of all recorded data streams can be retrieved in JSON format using the following URL http 127 0 0 1 4444 bySerial YAMPMK01 12345 dataLogger json Individual measures for any given stream can be obtained by appending the desired function identifier as well as start time of the stream 120 www yoctopuce com 20 Using with unsupported languages http 127 0 0 1 4444 bySerial YAMPMK01 12345 dataLogger json id current amp utc 1389801080 20 3 Using dynami
50. get_serialnumber Print Module to use lt input name serial value Sserial gt lt br gt if isset _ GET newname S newname GET newname if yCheckLogicalName S newname die Invalid name module gt set_logicalName newname Smodule gt saveToFlash printf Current name s lt br gt Smodule gt get_logicalName print New name lt input name newname value maxlength 19 gt lt br gt eS lt input type submit gt lt FORM gt lt BODY gt lt HTML gt Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not NULL Below a short example listing the connected modules lt HTML gt lt HEAD gt lt TITLE gt inventory lt TITLE gt lt HEAD gt lt BODY gt lt H1l gt Device list lt H1 gt
51. get_timeUTC Returns an integer corresponding to the Unix timestamp for current UTC time if known On failure throws an exception or returns Y_TIMEUTC_INVALID YDataLogger www yoctopuce com 259 21 High level API Reference datalogger get_userData YDataLogger datalogger userData Returns the value of the userData attribute as previously stored using method set_userData function get_userData function get_userData function get_userData void get_userData void userData function get_userData Tobject function get_userData As Object object get_userData Object get_userData def get_userData This attribute is never touched directly by the API and is at disposal of the caller to store a context Returns the object stored previously by the caller 260 www yoctopuce com 21 High level API Reference datalogger isOnline YDataLogger Checks if the data logger is currently reachable without raising any error function isOnline node js function isOnline function isOnline bool isOnline BOOL isOnline function isOnline boolean function isOnline As Boolean bool isOnline boolean isOnline def isOnline If there is a cached value for the data logger in cache that has not yet expired the device is considered reachable No exception is raised if there is an error while trying to contact the device hosting the
52. in milliseconds errmsg a string passed by reference to receive any error message Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code 146 www yoctopuce com 21 High level API Reference YAPI UnregisterHub YAPI yUnregisterHub Setup the Yoctopuce library to no more use modules connected on a previously registered machine with RegisterHub function yUnregisterHub url function UnregisterHub url function yUnregisterHub url void yUnregisterHub const string amp url void yUnregisterHub NSString url procedure yUnregisterHub url string procedure yUnregisterHub ByVal url As String void UnregisterHub string url synchronized static void UnregisterHub String url def UnregisterHub url Parameters url a string containing either usb or the www yoctopuce com 147 21 High level API Reference YAPI UpdateDeviceList YAPI yUpdateDeviceList Triggers a re detection of connected Yoctopuce modules function yUpdateDeviceList errmsg node js function UpdateDeviceList errmsg function yUpdateDeviceList amp errmsg YRETCODE yUpdateDeviceList string amp errmsg YRETCODE yUpdateDeviceList NSError errmsg function yUpdateDeviceList var errmsg string integer function yUpdateDeviceList ByRef errmsg As String As YRETCODE YRETCODE UpdateDeviceList ref string errmsg int UpdateDeviceList
53. is invoked when the result is known The callback function receives three arguments the caller specific context object the result code YAP I_SUCCESS if the operation completes successfully and the error message context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback www yoctopuce com 149 21 High level API Reference 21 2 Module control interface This interface is identical for all Yoctopuce USB modules It can be used to control the module global parameters and to enumerate the functions provided by each module In order to use the functions described here you should include lt script type text javascript src yocto_api js gt lt script gt var yoctolib require yoctolib var YAPI yoctolib YAPI var YModule yoctolib YModule require_once yocto_api php include yocto_api h import yocto_api h uses yocto_api yocto_api vb yocto_api cs import com yoctopuce YoctoAPI YModule from yocto_api import Global functions yFindModule func Allows you to find a module from its serial number or from its logical name yFirstModule Starts the enumeration of modules currently accessible YModule methods module gt describe Returns a descriptive text that identifies the module module download pathname Downloads the specified built in file and returns a binary buffer with its cont
54. library throws an exception In this case there are three possibilities e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the most desirable the Yoctopuce library offers another possibility for error handling allowing you to create a robust program without needing to catch exceptions at every www yoctopuce com 63 12 Using Yocto Amp with Objective C line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get _state method returns a Y STATE INVALID value a get _currentValue method returns a Y CURRENTVALUE INVALID value and so on In any case the returned value is of the expected type and is not a null pointer which would risk crashing your program At worst if you display the value without testing it it will be outside the expected bounds for the returned value In the case of functions which do not nor
55. of a return value in order to avoid blocking Firefox javascript VM that does not implement context switching during blocking I O calls See the documentation section on asynchronous Javascript calls for more details Parameters msValidity an integer corresponding to the validity of the loaded module parameters in milliseconds callback callback function that is invoked when the result is known The callback function receives three arguments the caller specific context object the receiving module object and the error code or YAPT_SUCCESS context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback www yoctopuce com 183 21 High level API Reference module nextModule YModule Continues the module enumeration started using yFirstModule is _ function nextModule node js function nextModule php_ function nextModule cpp _ YModule nextModule YModule nextModule function nextModule TYModule vb _ function nextModule As YModule YModule nextModule YModule nextModule def nextModule Returns a pointer to a YModu1e object corresponding to the next module found or a nu11 pointer if there are no more modules to enumerate 184 www yoctopuce com 21 High level API Reference module reboot Schedules a simple module reboot after the given number of seconds
56. of using an IP address you must use the callback string or http callback which is equivalent inelude yoctonap phpm yRegisterHub callback The remainder of the code stays strictly identical On the Virtua Hub interface at the bottom of the configuration window for the HTTP callback API there is a button allowing you to test the call to the PHP script Be aware that the PHP script controlling the modules remotely through the HTTP callback API can be called only by the Virtua Hub Indeed it requires the information posted by the VirtualHub to function To code a web site which controls Yoctopuce modules interactively you must create a user interface which stores in a file or in a database the actions to be performed on the Yoctopuce modules These actions are then read and run by the control script 48 www yoctopuce com 10 Using Yocto Amp with PHP Common issues For the HTTP callback API to work the PHP option allow_url_fopen must be set Some web site hosts do not set it by default The problem then manifests itself with the following error error URL file access is disabled in the server configuration To set this option you must create in the repertory where the control PHP script is located an htaccess file containing the following line php flag allow_url_fopen On Depending on the security policies of the host it is sometimes impossible to authorize this option at the root of
57. on next data loggers Returns a pointer to a YDataLogger object corresponding to the first data logger currently online or a null pointer if there are none www yoctopuce com 241 21 High level API Reference datalogger describe YDataLogger Returns a short text that describes the data logger in the form TYPE NAME SERIAL FUNCTIONID is function describe node js function describe php function describe string describe NSString describe function describe string function describe As String string describe String describe def describe More precisely TYPE is the type of the function NAME it the name used for the first access to the function SERIAL is the serial number of the module if the module is connected or unresolved and FUNCTIONID is the hardware identifier of the function if the module is connected For example this method returns Relay MyCustomName relayl RELAYLO1 123456 relayl if the module is already connected or Relay BadCustomeName relayl unresolved if the module has not yet been connected This method does not trigger any USB or TCP transaction and can therefore be used in a debugger Returns a string that describes the data logger ex Relay MyCustomName relayl RELAYLOI1 123456 relayl 242 www yoctopuce com 21 High level API Reference
58. port 4444 the standard port used by Yoctopuce You can very well modify this address and enter the address of another machine on which the VirtualHub software is running yFindCurrent The yFindCurrent function allows you to find a current sensor from the serial number of the module on which it resides and from its function name You can also use logical names as long as you have initialized them Let us imagine a Yocto Amp module with serial number YAMPMK01 123456 which you have named MyModule and for which you have given the current function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once yFindCurrent YAMPMK01 123456 current1 yFindCurrent YAMPMK01 123456 MyFunction var current yFindCurrent MyModule currentl var current var current var current var current yFindCurrent MyModule MyFunction yFindCurrent MyFunction yFindCurrent returns an object which you can then use at will to control the current sensor isOnline The isOnline method of the object returned by yFindCurrent allows you to know if the corresponding module is present and in working order get_currentValue The get _currentValue method of the object returned by yFindCurrent allows you to obtain the current as measured by the sensor The returned value is a number directly representing the value in mA A real example Open your preferred
59. r iaiNumnbe r ap gteybuesat soe sl SenserAG VCurrene Handeurrent m gt gen serialNumber ECU ENEZ else cere lt lt No module connected Check cable lt lt endl Cer alae while 1l if sensorDC gt isOnline cout lt lt Module disconnected lt lt endl break cout lt lt Current OC 3 lt lt enor DE Eee en ae TA couts 4 ING BW XS sensorAC gt get_currentValue CTAN cout lt lt Ui iptess CETIS Gto exit eaendii YAPI Sleep 1000 errmsg He return 0 11 2 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon include lt iostream gt include lt stdlib h gt www yoctopuce com 53 11 Using Yocto Amp with C include yocto_ api h using namespace std static void usage const char exe cout lt lt usage lt lt exe lt lt lt serial or logical name gt Graig il int Mainiink acoe const char aro Seng errmsg Setup the API to use local USB devices if yRegisterHub usb errmsg YAPT SUCCESS Geiee lt lt Wikenisiceneltitle error WY lt lt eiciamse lt lt end return 1 Tilerge 2 usage argv 0 ON OFF lt lt endl YModule module yFindModule argv 1 use serial or logical name if module gt isOnline if
60. support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software The only way to prevent this is to implement one of the two error handling techniques described below 76 www yoctopuce com 14 Using Yocto Amp with C The method recommended by most programming languages for unpredictable error handling is the use of exceptions By default it is the behavior of the Yoctopuce library If an error happens while you try to access a module the library throws an exception In this case there are three possibilities e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the
61. terminals of this resistance The current going through the resistance heats it and the more so as the current is stronger Heating is expected and normal but your must take it into account in your installation 16 www yoctopuce com 6 Assembly and connections T C 200 150 100 0 0 5 10 15 20 A Heat of the measuring resistance depending on the measured current 6 4 USB power distribution Although USB means Universal Serial BUS USB devices are not physically organized as a flat bus but as a tree using point to point connections This has consequences on power distribution to make it simple every USB port must supply power to all devices directly or indirectly connected to it And USB puts some limits In theory a USB port provides 100mA and may provide up to 500mA if available and requested by the device In the case of a hub without external power supply 100mA are available for the hub itself and the hub should distribute no more than 100mA to each of its ports This is it and this is not much In particular it means that in theory it is not possible to connect USB devices through two cascaded hubs without external power supply In order to cascade hubs it is necessary to use self powered USB hubs that provide a full 500mA to each subport In practice USB would not have been as successful if it was really so picky about power distribution As it happens most USB hub manufacturers have been doing saving
62. the modules should be looked for The parameter is the address of the virtual hub able to see the devices If the string usb is passed as parameter the API works with modules locally connected to the machine If the initialization does not succeed an exception is thrown YCurrent FindCurrent The YCurrent FindCurrent function allows you to find a current sensor from the serial number of the module on which it resides and from its function name You can use logical names as well as long as you have initialized them Let us imagine a Yocto Amp module with serial number YAMPMK01 123456 which you have named MyModule and for which you have given the current function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once current YCurrent FindCurrent YAMPMK01 123456 current1 current YCurrent FindCurrent YAMPMK01 123456 MyFunction current YCurrent FindCurrent MyModule current1 current YCurrent FindCurrent MyModule MyFunction current YCurrent FindCurrent MyFunction YCurrent FindCurrent returns an object which you can then use at will to control the current sensor isOnline The isOnline method of the object returned by YCurrent FindCurrent allows you to know if the corresponding module is present and in working order get_currentValue The get_currentValue method of the object returned by YCurrent FindCurrent allows you to obtain the
63. the same logical name in each copy Warning the behavior of a project becomes unpredictable when it contains several modules with the same logical name and when the driving software tries to access one of these modules through its logical name When leaving the factory modules do not have an assigned logical name It is yours to define 2 2 Specific elements The sensor This sensor is a analogical digital converter ADS1115IDGST produced by Texas Instruments Its use does not necessitate any particular precaution besides those linked to electrocution hazards 1 short short short long long long short short short 2 support yoctopuce com 6 www yoctopuce com 3 Electrocution hazards While the Yocto Amp module is perfectly able to manage a SPECMAXVOLT voltage we strongly discourage you to work on a voltage high enough to present risks Nevertheless if you decide to override this advice respect these recommendations they may well protect you from an embarrassing nomination to the Darwin Awards e Use your head your luck won t last forever e Don t work if you are tired Brilliant decisions taken at 2 a m tend to lose their shine at first light e Do not work under the influence of euphoriant substances Beware of family reunions they are known for their large amount of die offs among the DIY population e Don t work alone If things go bad you can then hope to be rescued fast enough 3 1 Dangerous components Some compo
64. then begin writeln errmsg halt end searches for the HTTP header end p pos 13410 13 10 data displays the response minus the HTTP header writeln copy data p 4 length data p 3 changes the luminosity if yapiHTTPRequest serial setValue data sizeof dataBuffer fullsize errmsg lt 0 then begin writeln errmsg halt end end Module inventory To perform an inventory of Yoctopuce modules you need two functions from the dynamic library int yapiGetAllDevices int buffer int maxsize int neededsize char errmsg int yapiGetDeviceInfo int devdesc yDeviceSt infos char errmsg The yapiGetAllDevices function retrieves the list of all connected modules as a list of handles buffer points to a 32 bit integer array which contains the returned handles maxsize is the size in bytes of the buffer To neededsize is assigned the necessary size to store all the handles From this you can deduce either the number of connected modules or that the input buffer is too small The errmsg 122 www yoctopuce com 20 Using with unsupported languages parameter must point to a 255 character buffer to retrieve a potential error message This pointer can also point to null The function returns a negative integer in case of error zero otherwise The yapiGetDeviceinfo function retrieves the information related to a module from its handle devdesc is a 32 bit integer representing the module and which
65. to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding set xxx function However this modification is performed only in the random access memory RAM of the module if the module is restarted the modifications are lost To memorize them persistently it is necessary to ask the module to save its current configuration in its permanent memory To do so use the saveToFlash method Inversely it is possible to force the module to forget its current settings by using the revertFromFlash method The short example below allows you to modify the logical name of a module import lt Foundation Foundation h gt import yocto_api h static void usage const char exe NSLog usage s lt serial gt lt newLogicalName gt n exe exis 1i int neaka Yin argc Const char w ewei NSError error autoreleasepool Setup the API to use local USB devices if yRegisterHub usb amp error YAPT SUCCESS NSLog RegisterHub error error localizedDescription return 1 Litera 2 usage argv 0 NSString serial or name NSString stringWithUTF8String argv 1 YModule module yFindModule serial or name use serial or logical name if module isOnline if argc gt 3 NSString newname NSString stringWithUTF8String argv 2 if yCheckLogicalName newname NSLog Invalid name n newname
66. unique hardware identifier is made of the device serial number followed by string module Returns a string that uniquely identifies the module www yoctopuce com 165 21 High level API Reference module gt get_icon2d YModule module gt icon2d Returns the icon of the module function get_icon2d node js function get_icon2d function get_icon2d string get_icon2d NSData icon2d function get_icon2d TByteArray function get_icon2d As Byte def get_icon2d YModule target get_icon2d The icon is a PNG image and does not exceeds 1536 bytes Returns a binary buffer with module icon in png format 166 www yoctopuce com 21 High level API Reference module gt get_lastLogs module gt lastLogs Returns a string with last logs of the module function get_lastLogs function get_lastLogs function get_lastLogs string get_lastLogs NSString lastLogs function get_lastLogs string function get_lastLogs As String string get_lastLogs String get_lastLogs def get_lastLogs YModule target get_lastLogs This method return only logs that are still in the module Returns a string with last logs of the module YModule www yoctopuce com 167 21 High level API Reference module gt get_logicalName YModule module gt logicalName Returns the logical name of the module function get_logicalName
67. yFirstModule while module nil NSLog 3 3 module serialNumber module productName module module nextModule return 0 12 3 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software The only way to prevent this is to implement one of the two error handling techniques described below The method recommended by most programming languages for unpredictable error handling is the use of exceptions By default it is the behavior of the Yoctopuce library If an error happens while you try to access a module the
68. yoctopuce com 233 21 High level API Reference current set_reportFrequency YCurrent current setReportFrequency Changes the timed value notification frequency for this function function set_reportFrequency newval function set_reportFrequency newval function set_reportFrequency newval int set_reportFrequency const string amp newval int setReportFrequency NSString newval function set_reportFrequency newval string integer function set_reportFrequency ByVal newval As String As Integer int set_reportFrequency string newval int set_reportFrequency String newval def set_reportFrequency newval YCurrent target set_reportFrequency newval The frequency can be specified as samples per second as sample per minute for instance 15 m or in samples per hour eg 4 h To disable timed value notifications for this function use the value OFF Parameters newval a string corresponding to the timed value notification frequency for this function Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code 234 www yoctopuce com 21 High level API Reference current set_resolution YCurrent current setResolution Changes the resolution of the measured values function set_resolution newval function set_resolution newval function set_resolution newval int set_resolution double newval int setResolut
69. 14 www yoctopuce com 19 Advanced programming The Yoctopuce modules support two types of calibration On the one hand a linear interpolation based on 1 to 5 reference points which can be performed directly inside the Yocto Amp On the other hand the API supports an external arbitrary calibration implemented with callbacks 1 to 5 point linear interpolation These transformations are performed directly inside the Yocto Amp which means that you only have to store the calibration points in the module flash memory and all the correction computations are done in a perfectly transparent manner The function get_currentValue returns the corrected value while the function get currentRawValue keeps returning the value before the correction Calibration points are simply Raw_value Corrected_value couples Let us look at the impact of the number of calibration points on the corrections 1 point correction The 1 point correction only adds a shift to the measures For example if you provide the calibration point a b all the measured values are corrected by adding to them b a so that when the value read on the sensor is a the current function returns b o O es 20 T oor lt gt AN amp 5 g C SS 15 O ne O O 10 5 sensor value 5 10 15 20 25 30 Measure correction with 1 calibration point here 5 10 The application is very simple you only need to call the calibrateFromPoints method of the functi
70. 44 www yoctopuce com 21 High level API Reference datalogger get_autoStart YDataLogger datalogger autoStart Returns the default activation state of the data logger on power up function get_autoStart function get_autoStart function get_autoStart Y_AUTOSTART_enum get_autoStart Y_AUTOSTART_enum autoStart function get_autoStart Integer function get_autoStart As Integer int get_autoStart int get_autoStart def get_autoStart YDataLogger target get_autoStart Returns either Y_AUTOSTART_OFF or Y_AUTOSTART_ON according to the default activation state of the data logger on power up On failure throws an exception or returns Y_AUTOSTART_INVALID www yoctopuce com 245 21 High level API Reference datalogger get_currentRunIndex YDataLogger datalogger currentRunIndex Returns the current run number corresponding to the number of times the module was powered on with the dataLogger enabled at some point function get_currentRunIndex function get_currentRunIndex function get_currentRunIndex int get_currentRunindex int currentRunIndex pas function get_currentRunIndex Longint ve _ function get_currentRunIndex As Integer int get_currentRunIndex int get_currentRunIndex def get_currentRunIndex YDataLogger target get_currentRunindex Returns an integer corresponding to the current run number corresponding to the n
71. API standpoint the modules and their functions are strongly uncorrelated by design Nevertheless the API provides the possibility to go from one to the other Thus the get_module method available for each function class allows you to find the object corresponding to the module hosting this function Inversely the YModule class provides several methods allowing you to enumerate the functions available on a module 7 2 The Yocto Amp module The Yocto Amp module provides a two instances of the Current function The current1 input corresponds to the DC current component while the current2 input corresponds to the AC current component RMS The typical accuracy of the DC measure is 2 mA or 1 per cent while the precision of the AC measure is 5 mA or 3 per cent for frequencies between 30Hz and 80Hz 20 www yoctopuce com 7 Programming general concepts module Module attribute type modifiable productName String read only serialNumber String read only logicalName String modifiable productId Hexadecimal number read only productRelease Hexadecimal number read only firmwareRelease String read only persistentSettings Enumerated modifiable luminosity 0 100 modifiable beacon On Off modifiable upTime Time read only usbCurrent Used current mA read only rebootCountdown Integer modifiable usbBandwidth Enumerated modifiable current1 Current current2 Current attribute type modifiable
72. CUON a t aa a eaa aa a a aa nA EE EErEE Ean inii 59 12 2 Con tr lof the module part a er ives E aaa eea aaa pra aaaea eea a Naara anade i 61 W223 ErMrORNANGIING AE E E A EA E ch ai EAE 63 13 Using Yocto Amp with Visual Basic NET oo teeteeeeeeees 65 T3Aelnstallation creck Ae eich iii ne es 65 13 2 Using the Yoctopuce API in a Visual Basic project oo eee eeeeeeeeeeeeeeeeeneeeeteneeeeeeneaeees 65 13 3 Control of the Current function oo ieee ec eeeeceeneeeeeeneeeeteaeeeeteaaeeeteeaeeeeeeaeeeeeeaaeeeteeeeeseeaeeey 66 13 4 Control of the module part oo eee ceeeseceeeseeeeeeeeeeeeecseneeeeeaeecnesaeaeneeaaeeseseaneseesneneennes 68 13 9 Error handling sic ccc Sie aA a aii dna Sahih ei een el 70 14 Using YOCtO AMp with CE oo ccs ces eesnesneesesseeseesesscsueecesneesseneeseesseeseees 71 4 1 Installation sea es edvesdeceheccceetesstel ce seeds E E Fevivievielecd dined eri 71 14 2 Using the Yoctopuce API in a Visual C project 0 ec eeeeeeeeeeeeneeeeeeneeeeteeeeeeeneeeeneas 71 14 3 Control of the Current function oo eee cece ceeneeeeeenee ee tee eee eeaaeeeeeeaeeeeeeaeeeeseeeeeteeeeeseeaeeey 72 14 4 Control of the module part oo eeecceeeeeeeeeeseeceeeceeeeeeeeaneesesaeeenesaeaeseeaaeenessaaeneeeneneennees 74 1425 SE ror NanglinG ac eae eG ee ohne AR ie Ree NE ae EA 76 15 Using Yocto Amp with Delphi oo cece cece cee eeseeseeseceeeeseesneseeseeneeeees 79 15 12 Preparatlon ana sian nets teas Ate icc ener Aa eee ot eared ea
73. Console WriteLine Usage Consolleanriteiine crecname h M serialnumber i Console WriteLine execname lt logical name gt ConsolerWritelumne excename sa lamiyn e System Threading Thread Sleep 2500 Environment Exit 0 static void die string msg Console WriteLine msg check USB cable Environment Exit 0 static void Main string args string errmsg SEEGE E YCurrent sensor YCurrent sensorDC null YCurrent sensorAC null YModule m null if args Length lt 1 usage target args 0 ToUpper Setup the API to use local USB devices if YAPI RegisterHub usb ref errmsg YAPI SUCCESS Console WriteLine RegisterHub error errmsg Environment Exit 0 if target ANY retreive any voltage sensor can be AC or DC sensor YCurrent FirstCurrent if sensor null die No module connected else sensor YCurrent FindCurrent target currentl we need to retreive both DC and AC voltage from the device if sensor isOnline m sensor get_module ScnsonD Veurnene Findeurrent mi euaser ral Number ty Me CuUrrenti Ti SensorAG M Veurnent windeurrent mM gee scrvalNumber ss current2 www yoctopuce com 73 14 Using Yocto Amp with C else die Module not connected while true if m isOnline die Module not connected Console Write UDC we scnsorDe get eu
74. Difference between Find and First The YXxx FindXxxx and YXxx FirstXxxx methods do not work exactly the same way If there is no available module YXxx FirstXxxx returns a null value On the opposite even if there is no corresponding module YXxx FindXxxx returns a valid object which is not online but which could become so if the corresponding module is later connected Function handling When the object corresponding to a function is found its methods are available in a classic way Note that most of these subfunctions require the module hosting the function to be connected in order to be handled This is generally not guaranteed as a USB module can be disconnected after the control software has started The isOnline method available in all the classes is then very helpful Access to the modules Even if it is perfectly possible to build a complete project while making a total abstraction of which function is hosted on which module the modules themselves are also accessible from the API In fact they can be handled in a way quite similar to the functions They are assigned a serial number at the factory which allows you to find the corresponding object with YModule Find You can also assign arbitrary logical names to the modules to make finding them easier Finally the YModule class contains the YModule FirstModule and nextModule enumeration methods allowing you to list the connected modules Functions Module interaction From the
75. DisableExceptions function yDisableExceptions void yDisableExceptions void yDisableExceptions procedure yDisableExceptions procedure yDisableExceptions void DisableExceptions def DisableExceptions When exceptions are disabled every function returns a specific error value which depends on its type and which is documented in this reference manual www yoctopuce com 129 21 High level API Reference YAPI EnableExceptions YAPI yEnableExceptions Re enables the use of exceptions for runtime error handling function yEnableExceptions node js function EnableExceptions function yEnableExceptions void yEnableExceptions void yEnableExceptions procedure yEnableExceptions procedure yEnableExceptions cs void EnableExceptions def EnableExceptions Be aware than when exceptions are enabled every function that fails triggers an exception If the exception is not caught by the user code it either fires the debugger or aborts i e crash the program On failure throws an exception or returns a negative error code 130 www yoctopuce com 21 High level API Reference YAPI EnableUSBHost YAPI yEnableUSBHost This function is used only on Android synchronized static void EnableUSBHost Object osContext Before calling yRegisterHub usb you need to activate the USB host port of the system This function takes as argument an object of class android content Co
76. Java programming library e The VirtualHub software for Windows Mac OS X or Linux depending on your OS The library is available as source files as well as a jar file Decompress the library files in a folder of your choice connect your modules run the VirtualHub software and you are ready to start your first tests You do not need to install any driver In order to keep them simple all the examples provided in this documentation are console applications Naturally the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface 17 2 Control of the Current function A few lines of code are enough to use a Yocto Amp Here is the skeleton of a Java code snippet to use the Current function ea ooo Get access to your device connected locally on USB for instance YAPT Rega site chub LA 7 ORO current YCurrent FindCurrent YAMPMK01 123456 current1 Hot plug is easy just check that the device is online if current isOnline Use current get_currentValue 1 www yoctopuce com EN libraries php 2 www yoctopuce com EN virtualhub php www yoctopuce com 91 17 Using the Yocto Amp with Java ferences Let us look at these lines in more details YAPI RegisterHub The yAPI RegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for The parameter is the address of the Virtual Hub able to see the devic
77. L The software is compiled with a small library which provides control of the DLL It is the fastest method to code module support in a given language Indeed the useful part of the control code is located in the DLL which is the same for all languages the effort to support a new language is limited to coding the small library which controls the DLL From the end user stand point there are few differences one must simply make sure that the DLL is installed on the end user s computer at the same time as the main software 24 www yoctopuce com 7 Programming general concepts The application uses the DLL to natively control the locally connected module Control by service Some languages do simply not allow you to easily gain access to the hardware layers of the machine It is the case for Javascript for instance To deal with this case Yoctopuce provides a solution in the form of a small piece of software called Virtual Hub It can access the modules and your application only needs to use a library which offers all necessary functions to control the modules via this virtual hub The end users will have to start the virtual hub before running the project control software itself unless they decide to install the hub as a service deamon in which case the virtual hub starts automatically when the machine starts up The application connects itself to the virtual hub to gain access to the module The service control method com
78. Line luminosity tS mage OSES hosies engi a Console Write beacon a if m get_beacon YModule BEACON_ ON Console WriteLine ON else Console WriteLine OFF Console WriteLine upTime Ws gee oime 000 ostrine A eect Console Wrrrelinel WUSBicuEsenr UR em gous Cli remin ioste ingi Or n AmA 74 www yoctopuce com 14 Using Yocto Amp with C Console WriteLine Logs r n m get_lastLogs else Console WriteLine args 0 not connected check identification and USB cable Each property xxx of the module can be read thanks to a method of type YModule get xxxx and properties which are not read only can be modified with the help of the YModule set xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding YModule set xxx function However this modification is performed only in the random access memory RAM of the module if the module is restarted the modifications are lost To memorize them persistently it is necessary to ask the module to save its current configuration in its permanent memory To do so use the YModule saveToFlash method Inversely it is possible to force the module to forget its current settings by using the YModule revertFromFlash method The short example below allows you to modify the logical name of a module using
79. Measure gt get_preview ArrayList lt YMeasure gt get_preview def get_preview Each item includes the start of a time interval the end of a time interval the minimal value observed during the time interval the average value observed during the time interval the maximal value observed during the time interval This preview is available as soon as loadMore has been called for the first time Returns a table of records where each record depicts the measured values during a time interval On failure throws an exception or returns an empty array www yoctopuce com 279 21 High level API Reference dataset get_progress YDataSet dataset progress Returns the progress of the downloads of the measures from the data logger on a scale from 0 to 100 function get_progress function get_progress function get_progress cpp int get_progress int progress pas_ function get_progress LongInt v function get_progress As Integer lt s int get_progress java int get_progress def get_progress When the object is instanciated by get_dataSet the progress is zero Each time loadMore is invoked the progress is updated to reach the value 100 only once all measures have been loaded Returns an integer in the range 0 to 100 percentage of completion 280 www yoctopuce com 21 High level API Reference dataset get_startTimeUTC YDataS
80. Online The isOnline method of the object returned by YCurrent FindCurrent allows you to know if the corresponding module is present and in working order get_currentValue The get_currentValue method of the object returned by YCurrent FindCurrent allows you to obtain the current as measured by the sensor The returned value is a number directly representing the value in mA A real example Launch Python and open the corresponding sample script provided in the directory Examples Doc GettingStarted Yocto Amp of the Yoctopuce library In this example you will recognize the functions explained above but this time used with all side materials needed to make it work nicely as a small demo usr bin python coding utf 8 import os sys from yocto_api import from yocto current import 86 www yoctopuce com 16 Using the Yocto Amp with Python def usage scriptname os path basename sys argv 0 Pane Us agens print scriptname lt serial_ number gt print scriptname lt logical_name gt print scriptname any sys exit def die msg SVS erit Motu Checks USBTcab tre errmsg YRefParam if len sys argv lt 2 usage target sys argv l Setup the API to use local USB devices if YAPI RegisterHub usb errmsg YAPI SUCCESS sys exit init error errmsg value if target any retreive any voltage sensor can be AC or DC sensor YCurrent FirstCurrent if se
81. System using oystem Collections GenerLer using System Ling using System Text namespace ConsoleApplicationl class Program static void usage string execname System AppDomain CurrentDomain FriendlyName Console WriteLine Usage Console WriteLine usage demo lt serial or logical name gt lt new logical name gt System Threading Thread Sleep 2500 Environment Exit 0 static void Main string args YModule m string errmsg string newname if args Length 2 usage if YAPI RegisterHub usb ref errmsg YAPI SUCCESS Console WriteLine RegisterHub error errmsg Environment Exit 0 m YModule FindModule args 0 use serial or logical name if m isOnline newname args 1 if YAPI CheckLogicalName newname Console WriteLine Invalid name newname Environment Exit 0 m set_logicalName newname m saveToFlash do not forget this Console Write Module serial m get serialNumber Console WriteLine name m get_logicalName alleg Console Write not connected check identification and USB cable www yoctopuce com 75 14 Using Yocto Amp with C Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology
82. Under Mac OS X all the examples and project models are tested with XCode 4 available on the App Store Moreover under Max OS X and under Linux you can compile the examples using a command line with GCC using the provided GNUmakefile In the same manner under Windows a Makefile allows you to compile examples using a command line fully knowing the compilation and linking arguments Yoctopuce C libraries are integrally provided as source files A section of the low level library is written in pure C but you should not need to interact directly with it everything was done to ensure the simplest possible interaction from C The library is naturally also available as binary files so that you can link it directly if you prefer You will soon notice that the C API defines many functions which return objects You do not need to deallocate these objects yourself the API does it automatically at the end of the application In order to keep them simple all the examples provided in this documentation are console applications Naturally the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface You will find in the last section of this chapter all the information needed to create a wholly new project linked with the Yoctopuce libraries 11 1 Control of the Current function A few lines of code are enough to use a Yocto Amp Here is the skeleton of a C code snipplet to use th
83. Using Yocto Amp with Visual Basic NET Then add in the same manner the yapi d11 DLL located in the Sources d11 directory Then from the Solution Explorer window right click on the DLL select Properties and in the Properties panel set the Copy to output folder to always You are now ready to use your Yoctopuce modules from Visual Studio In order to keep them simple all the examples provided in this documentation are console applications Naturally the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface 13 3 Control of the Current function A few lines of code are enough to use a Yocto Amp Here is the skeleton of a Visual Basic code snipplet to use the Current function eas ol Dim errmsg As String errmsg Dim current As YCurrent REM Get access to your device connected locally on USB for instance yRegisterHub usb errmsg current yFindCurrent YAMPMK01 123456 current1 REM Hot plug ns easy Just check that the device as online If current isOnline Then REM Use current get curren Value Mh iyqiel desc Let s look at these lines in more details yRegisterHub The yRegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for When used with the parameter usb it will use the modules locally connected to the computer running the library If the initialization does not succeed this function returns a v
84. Validity function load msValidity integer YRETCODE function load ByVal msValidity As Integer As YRETCODE YRETCODE load int msValidity int load long msValidity def load msValidity By default whenever accessing a device all function attributes are kept in cache for the standard duration 5 ms This method can be used to temporarily mark the cache as valid for a longer period in order to reduce network trafic for instance Parameters msValidity an integer corresponding to the validity attributed to the loaded function parameters in milliseconds Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 263 21 High level API Reference datalogger load_async YDataLogger Preloads the data logger cache with a specified validity duration asynchronous version function load_async msValidity callback context function load_async msValidity callback context By default whenever accessing a device all function attributes are kept in cache for the standard duration 5 ms This method can be used to temporarily mark the cache as valid for a longer period in order to reduce network trafic for instance This asynchronous version exists only in Javascript It uses a callback instead of a return value in order to avoid blocking the Javascript virtual machine Parameters msValidity an integer corresponding to the va
85. YModule 185 S saveToFlash YModule 186 SelectArchitecture YAPI 142 Sensor 114 Sequence 273 Service 24 set_autoStart YDataLogger 266 set_beacon YModule 187 set_highestValue YCurrent 229 set_logFrequency YCurrent 230 set_logicalName YCurrent 231 set_logicalName YDataLogger 267 set_logicalIName YModule 188 set_lowestValue YCurrent 232 set_luminosity YModule 189 set_recording YDataLogger 268 set_reportFrequency YCurrent 233 set_resolution YCurrent 234 set_timeUTC YDataLogger 269 set_usbBandwidth YModule 190 set_userData YCurrent 235 set_userData YDataLogger 270 set_userData YModule 191 SetDelegate YAPI 143 SetTimeout YAPI 144 Sleep YAPI 145 Source 85 Start 26 T Test 11 triggerFirmwareUpdate YModule 192 Troubleshooting 293 U UnregisterHub YAPI 146 Unsupported 119 UpdateDeviceList YAPI 147 UpdateDeviceList_async YAPI 148 V Value 286 Variants 56 VirtualHub 97 119 Visual 65 71 W wait_async YCurrent 236 wait_async YDataLogger 271 wait_async YModule 193 Y YAPI 127 148 yCheckLogicalName 127 YCurrent 197 236 YDataLogger 239 271 YDataSet 274 284 yDisableExceptions 128 yEnableExceptions 129 yEnableUSBHost 130 yFindCurrent 197 yFindDataLogger 239 yFindModule 152 yFirstCurrent 198 yFirstDataLogger 240 yFirstModule 153 yFreeAPI 131 yGetAPIVersion 132 yGetTickCount 133 yHandleEvents 134 ylnitAPI 135 YMeasure 286 290 YModule 152 193 Yocto Amp 20
86. Yocto Amp User s guide Table of contents 1 Introduction ction teed eee athe ath aa tad ta aad eee thea naga tae tat 1 TA PREFEQUISITOS sccccctice iessdeceastativbisdeaeedsccpadsceiebasazaidistiadajetecafaibubizesssdcnendscedesusebisaacidie ciufepsascaes 1 132 OptiomalACCESSONISS access iiaae a og a a a Ea a ea ea oes 3 2 Presentation coeesccce Gertie ete teal ete etisalat Mactan 5 221 COMMON CIGEMENIS ei a A a a a de veveeescenoteeecsebiebeek 5 2 Oe OPEC eeM E a see cettanceseectt fe ssthcted a aaea A aea EE eaa D eara eE ara 6 3 Electrocution hazards ooo cece ccccescecececeececececvevececcevscecsesavaveccevsveveceeseveveteavaveeeevetes 7 3 1 Dangerous COMPONMEMIS rociera areia areca eden eared E coed EEEE E A a adta EEE 7 4 Direct current vs alternating current 0 ccc ces eescseeseseesesneseeneseeneees 9 oO PINSUSIEDS vn ee oe ee hee eh tenis 11 BFA elete iA EA E EErEE devs coe ete dceccuencd ae cies cocoa E EEEE E 11 5 2 Test Of the MO AU E a a a decucabalsdes develsadeebendeasiivs 11 Py th eters cack EEE TEES E Ue ce eno yaw ES EAA Renovo A Nava eaten AAA TEE 12 6 Assembly and CONNECTIONS ounces cseseesessesesseseaveseseseseseseeseseeneseeseseeneesens 15 yl IMAG AE E etn cg cute teat gh chats E eeeany tan tas ete E E tees 15 6 22 GONNECTIONS 3 2icevesceseise tec ccs EEE EA E ea bebe a a os oe hd saved eee onan E EEE 16 6 3 Heating wtaw s een ene ied tee i oie ene ees eee eee ee Cente 16 6 4 USB power CISthDUTION s
87. a ieee aeaaeai 97 18 3 Compatibility srini suae a i e e aa A a a eaaa AEE EE eee reba 97 18 4 Activating the USB port under Android ooo eececeeeeneeeeeeeeeeseneeeeeeaeeeeeeaeeeeseeeeessnaeeeenas 98 18 5 Control of the Current function oo eee eeeeeeeeneeeeeene eee eeaaeeeeeeaeeeeeeaeeeeseaeeeeeeeeeeseneaeeteaaes 100 18 6 Control oF the module part cvcvcctacivntietesedi a ed eed et 102 18 7 ErrOn handling siia ection devetacenniebecdee abet e a a Na Eai RE 107 19 Advanced programming ee ee ree 109 19 4 Eventsprogrammin 220 EEEE E E Aa ties ON 109 19 2 The data lOQQO0 rnini diein iai aedi ee T Sd ede vee estate eteveecd cede benedeni rE 112 19 3 Sensor Calibration z z c e be Gti dade e ra a ai a aa T ar a Aa eaaa aa pac adedietidiea 114 20 Using with unsupported languages 2 eects eee eeeeeseeeeeteeeeneeeeees 119 20h Commanding EA E EEE eee etter ea eee nt diet Sian 119 20 2 VirtualH b and HTTP GE ast5 eae ek tee ciel ek tie adedoann Sete 119 20 3 Using dynamMicilIbrarieS ecvyences secs ateerteed cots aaa aa etd a tenet eee egies etnies 121 20 4 Porting the high level library oo eee center eeeneeee centr eteaeeeeeeaeeeeseaeeeeseaaeeseeneeeeeeneeeeegs 124 21 High level API Reference ooo ccc cscs essessesnesseseeseeseeseecesueeeeseeseeneeneaneasees 125 21i General TUMGtOMS iis a a aaa aaa a a Eea aa aar aaa ded a E aaa Taa E in ia LeAF ROERE 126 21 2 Module control interface ooo eee ceeeceeeeeeeneeeeeeneeec
88. ack any time a relay state changes The timed report callback This type of callback is automatically called at a predefined time interval The callback frequency can be configured individually for each sensor with frequencies going from hundred calls per seconds down to one call per hour The callback takes as parameter the relevant function and the measured value as an YMeasure object Contrarily to the value change callback that only receives the latest value an YMeasure object provides both minimal maximal and average values since the timed report callback Moreover the measure includes precise timestamps which makes it possible to use timed reports for a time based graph even when not handled immediately static void periodicCallback YCurrent fct YMeasure measure Cons oler Wisakeetnine Chcie ices hardwereilal it Ut measure get_averageValue Setting up a timed report callback The callback is set up for a given Current function with the help of the registerTimedReportCallback method The callback will only be invoked once a callback frequency as been set using set _reportFrequency which defaults to timed report callback turned off The frequency is specified as a string same as for the data logger by specifying the number of calls per second s per minute m or per hour h The maximal frequency is 100 times per second i e 100 s and the minimal frequency is 1 time per hour i e 1 h When the frequency is hig
89. alue different from YAPI SUCCESS and errmsg contains the error message yFindCurrent The yFindCurrent function allows you to find a current sensor from the serial number of the module on which it resides and from its function name You can use logical names as well as long as you have initialized them Let us imagine a Yocto Amp module with serial number YAMPMK01 123456 which you have named MyModule and for which you have given the current function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once current yFindCurrent YAMPMK01 123456 current1 current yFindCurrent YAMPMK01 123456 MyFunction current yFindCurrent MyModule current1 current yFindCurrent MyModule MyFunction current yFindCurrent MyFunction yFindCurrent returns an object which you can then use at will to control the current sensor isOnline The isOnline method of the object returned by yFindCurrent allows you to know if the corresponding module is present and in working order get_currentValue The get _currentValue method of the object returned by yFindCurrent allows you to obtain the current as measured by the sensor The returned value is a number directly representing the value in mA 4 Remember to change the filter of the selection window otherwise the DLL will not show 66 www yoctopuce com 13 Using Yocto Amp with Visual Basic NET A real ex
90. ame USB A to micro B Data cable Make sure not to buy a simple USB charging cable without data connectivity The correct type of cable is available on the Yoctopuce shop You must plug in your Yocto Amp module with a USB cable of type A micro B If you insert a USB hub between the computer and the Yocto Amp module make sure to take into account the USB current limits If you do not be prepared to face unstable behaviors and unpredictable failures You can find more details on this topic in the chapter about assembly and connections 3 Although they existed for some time Mini A connectors are not available anymore http www usb org developers Deprecation_Announcement_052507 pdf 2 www yoctopuce com 1 Introduction 1 2 Optional accessories The accessories below are not necessary to use the Yocto Amp module but might be useful depending on your project These are mostly common products that you can buy from your favourite hacking store To save you the tedious job of looking for them most of them are also available on the Yoctopuce shop Screws and spacers In order to mount the Yocto Amp module you can put small screws in the 2 5mm assembly holes with a screw head no larger than 4 5mm The best way is to use threaded spacers which you can then mount wherever you want You can find more details on this topic in the chapter about assembly and connections Micro USB hub If you intend to put several Yoctopuce modules i
91. ample Launch Microsoft VisualBasic and open the corresponding sample project provided in the directory Examples Doc GettingStarted Yocto Amp of the Yoctopuce library In this example you will recognize the functions explained above but this t materials needed to make it work nicely as a small demo Module Modulel Private Sub Usage Dim execname As String System AppDomain CurrentDomain FriendlyName Console Wettehine Usage Console WriteLine execname demo Console WriteLine execname demo Console WriteLine execname demo System Threading Thread Sleep 2500 End End Sub lt serial number gt lt logical_ name gt any W Sub Die ByVal msg As String Console WriteLine msg check USB End End Sub cable a Sub Main Dim argv As Dim errmsg As Dim target As Siteung Dim sensor As YCurrent Dim sensorDC As YCurrent Dim sensorAC As YCurrent Dim m As YModule Nothing String String System Environment GetCommandLineArgs we Nothing Nothing If argv Length lt 2 Then Usage target argv 1 REM Setup the APT to use local USB devices If yRegisterHub usb errmsg lt gt YAPI SUCCESS Then Console WriteLine RegisterHub error errmsg End End Ef Tf target any Then REM retreive any voltage sensor can be AC or DC sensor yFirstCurrent If sensor Is Nothing Then Die No moduille connected Else sensor yFindCurrent target voltagel End If
92. ange 2 4 if steingvargvilz on module gt set_beacon Y_BEACON_ON elise module gt set_beacon Y_ BEACON OFF co t lt lt Mserial lt lt module gt get_serialNumber lt lt endl cout lt lt logical name lt lt module gt get_logicalName lt lt endl cout lt lt luminosity lt lt module gt get_luminosity lt lt endl cout lt lt beacon aa ii module gt get_beacon Y_BEACON_ON eout lt ON lt lt endl else Cowie SK MOIR lt lt lt EE cout lt lt upTime Cout lt USB eurten t ea module gt oct ausb Cur remti Onee cout lt lt Logs lt lt endl lt lt module gt get_lastLogs lt lt endl else mA lt lt endl De nodule Jeb uptime 000 eeue endi cout lt lt argv 1 lt lt not connected check identification and USB cable lt lt endl return 0 Each property xxx of the module can be read thanks to a method of type get _xxxx and properties which are not read only can be modified with the help of the set _xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding set _xxx function However this modification is performed only in the random access memory RAM of the module if the module is restarted the modifications are lost To memorize them persistently it is necess
93. ar basis If you wish to use this feature choose the callback type follow the steps below carefully 1 Specify the Type of callback you want to use Yocto API callback z Yoctopuce devices can be controled through remote PHP scripts That Yocto AFP caliback protocol is designed so it can pass trough NAT filters without opening ports See your device user manual PHP programming section for more details 2 Specify the URL to use for reporting values HTTPS protocol is not yet supported Callback URL http iwww mysite com yoctotest yoctocontrol php 3 If your callback requires authentication enter credentials here Digest authentication is recommended but Basic authentication works as well Username yocto Password CON 4 Setup the desired frequency of notifications No less than 3 seconds between two notification But notify after 600 seconds in any case 5 Press on the Test button to check your parameters 6 When everything works press on the OK button Test fox Cancel And select Yocto API callback You then only need to define the URL of the PHP script and if need be the user name and password to access this URL Supported authentication methods are basic and digest The second method is safer than the first one because it does not allow transfer of the password on the network Usage From the programmer standpoint the only difference is at the level of the yRegisterHub function call Instead
94. ary to ask the module to save its current configuration in its permanent memory To do so use the saveToFlash method Inversely it is possible to force the module to forget its current settings by using the revertFromFlash method The short example below allows you to modify the logical name of a module include lt iostream gt include lt stdlib h gt include yocto_ api h using namespace std static void usage const char exe 54 www yoctopuce com 11 Using Yocto Amp with C Conn lt lt Mulsage lt lt exeu lt lt UW l lt serilal gt lt newlogecalNeame gt s lt lt endl ezici int Main int argc Const char argi string errmsg Setup the API to use local USB devices if yRegisterHub usb errmsg YAPT SUCCESS cerre Regus berHUDmerEOr lt lt errms oia aenda mewta e mene lt 2 usage argv 0 YModule module yFindModule argv 1 use serial or logical name if module gt isOnline if arge gt 3 string newname argv 2 if yCheckLogicalName newname cerr lt lt Invalid name lt lt newname lt lt lt lt endl usage argv 0 module gt set_logicalName newname module gt saveToFlash cout lt lt Curnent mame lt lt modile ger liogicallName lt lt endl else cout lt lt argv 1 lt lt not connected check identification and USB cable lt lt endl return UF Warning the
95. ata logger This function only works if the device uses a recent firmware as DataSet objects are not supported by firmwares older than version 13000 a Parameters startTime the start of the desired measure time interval as a Unix timestamp i e the number of seconds since January 1 1970 UTC The special value 0 can be used to include any meaasure without initial limit endTime the end of the desired measure time interval as a Unix timestamp i e the number of seconds since January 1 1970 UTC The special value 0 can be used to include any meaasure without ending limit Returns an instance of YDataSet providing access to historical data Past measures can be loaded progressively using methods from the YDataSet object www yoctopuce com 217 21 High level API Reference current get_reportFrequency YCurrent current reportFrequency Returns the timed value notification frequency or OFF if timed value notifications are disabled for this function function get_reportFrequency function get_reportFrequency function get_reportFrequency string get_reportFrequency NSString reportFrequency function get_reportFrequency string function get_reportFrequency As String string get_reportFrequency String get_reportFrequency def get_reportFrequency YCurrent target get_reportFrequency Returns a string corresponding to the timed value notification frequency or OFF if t
96. ation of a module when you have several identical ones It is indeed possible to trigger off the Yocto beacon by software as it is possible to detect by software that a Yocto beacon is on The Yocto led has a third functionality which is less pleasant when the internal software which controls the module encounters a fatal error the Yocto led starts emitting an SOS in morse 1 If this happens unplug and re plug the module If it happens again check that the module contains the latest version of the firmware and if it is the case contact Yoctopuce support Current sensor Each Yocto module is able to measure its own current consumption on the USB bus Current supply on a USB bus being quite critical this functionality can be of great help You can only view the current consumption of a module by software Serial number Each Yocto module has a unique serial number assigned to it at the factory For Yocto Amp modules this number starts with YAMPMKO1 The module can be software driven using this serial number The serial number cannot be modified Logical name The logical name is similar to the serial number it is a supposedly unique character string which allows you to reference your module by software However in the opposite of the serial number the logical name can be modified at will The benefit is to enable you to build several copies of the same project without needing to modify the driving software You only need to program
97. back yDeviceUpdateFunc arrivalCallback synchronized static void RegisterDeviceArrivalCallback DeviceArrivalCallback arrivalCallback def RegisterDeviceArrivalCallback arrivalCallback This callback will be invoked while yUpdat eDeviceList is running You will have to call this function on a regular basis Parameters arrivalCallback a procedure taking a YModule parameter or null 138 www yoctopuce com 21 High level API Reference YAPI RegisterDeviceRemovalCallback YAPI yRegisterDeviceRemovalCallback Register a callback function to be called each time a device is unpluged function yRegisterDeviceRemovalCallback removalCallback function RegisterDeviceRemovalCallback removalCallback function yRegisterDeviceRemovalCallback removalCallback void yRegisterDeviceRemovalCallback yDeviceUpdateCallback removalCallback void yRegisterDeviceRemovalCallback yDeviceUpdateCallback removalCallback procedure yRegisterDeviceRemovalCallback removalCallback yDeviceUpdateFunc procedure yRegisterDeviceRemovalCallback ByVal removalCallback As yDeviceUpdateFunc void RegisterDeviceRemovalCallback yDeviceUpdateFunc removalCallback synchronized static void RegisterDeviceRemovalCallback DeviceRemovalCallback removalCallback def RegisterDeviceRemovalCallback removalCallback This callback will be invoked while yUpdateDeviceList is running You will have to call this function on a regular basis Parameters
98. beacon Y_BEACON_enum get_beacon Y_BEACON_enum beacon function get_beacon Integer function get_beacon As Integer int get_beacon int get_beacon def get_beacon YModule target get_beacon Returns YModule either Y_BEACON_OFF or Y_BEACON_ON according to the state of the localization beacon On failure throws an exception or returns Y_BEACON_INVALID www yoctopuce com 161 21 High level API Reference module get_errorMessage module errorMessage Returns the error message of the latest error with this module object function get_errorMessage function get_errorMessage function get_errorMessage string get_errorMessage NSString errorMessage function get_errorMessage string function get_errorMessage As String string get_errorMessage String get_errorMessage def get_errorMessage This method is mostly useful when using the Yoctopuce library with exceptions disabled YModule Returns a string corresponding to the latest error message that occured while using this module object 162 www yoctopuce com 21 High level API Reference module get_errorType YModule module errorType Returns the numerical error code of the latest error with this module object function get_errorType function get_errorType function get_errorType YRETCODE get_errorType function get_errorType YRETCODE function get_errorType
99. bject oriented programming language promoted by Microsoft it is somewhat similar to Java Like Visual Basic and Delphi it allows you to create Windows applications quite easily All the examples and the project models are tested with Microsoft C 2010 Express freely available on the Microsoft web site 14 1 Installation Download the Visual C Yoctopuce library from the Yoctopuce web site There is no setup program simply copy the content of the zip file into the directory of your choice You mostly need the content of the Sources directory The other directories contain the documentation and a few sample programs All sample projects are Visual C 2010 projects if you are using a previous version you may have to recreate the projects structure from scratch 14 2 Using the Yoctopuce API in a Visual C project The Visual C NET Yoctopuce library is composed of a DLL and of source files in Visual C The DLL is not a NET DLL but a classic DLL written in C which manages the low level communications with the modules The source files in Visual C manage the high level part of the API Therefore your need both this DLL and the cs files of the sources directory to create a project managing Yoctopuce modules Configuring a Visual C project The following indications are provided for Visual Studio Express 2010 but the process is similar for other versions Start by creating your project Then on the Solution Explorer panel right cl
100. ble gt rawValues ArrayList lt Double gt refValues def loadCalibrationPoints rawValues refValues YCurrent target loadCalibrationPoints rawValues refValues Parameters rawValues array of floating point numbers that will be filled by the function with the raw sensor values for the correction points refValues array of floating point numbers that will be filled by the function with the desired values for the correction points Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 225 21 High level API Reference current load_async YCurrent Preloads the current sensor cache with a specified validity duration asynchronous version function load_async msValidity callback context function load_async msValidity callback context By default whenever accessing a device all function attributes are kept in cache for the standard duration 5 ms This method can be used to temporarily mark the cache as valid for a longer period in order to reduce network trafic for instance This asynchronous version exists only in Javascript It uses a callback instead of a return value in order to avoid blocking the Javascript virtual machine Parameters msValidity an integer corresponding to the validity of the loaded function parameters in milliseconds callback callback function that is invoked when the result is known The callback funct
101. bles are provided pre compiled for all the Yoctopuce officially supported platforms OS Naturally the executable sources are also provided 8 1 Installing Download the command line API You do not need to run any setup simply copy the executables corresponding to your platform OS in a directory of your choice You may add this directory to your PATH variable to be able to access these executables from anywhere You are all set you only need to connect your Yocto Amp open a shell and start working by typing for example YCurrent any get currentValue To use the command API on Linux you need either have root privileges or to define an udev rule for your system See the Troubleshooting chapter for more details 8 2 Use general description All the command line API executables work on the same principle They must be called the following way Executable options target command parameter options manage the global workings of the commands they allow you for instance to pilot a module remotely through the network or to force the module to save its configuration after executing the command target is the name of the module or of the function to which the command applies Some very generic commands do not need a target You can also use the aliases any and all or a list of names separated by comas without space lif you want to recompile the command line API you also need the C API 2 http www yoctopuce com EN li
102. braries php www yoctopuce com 29 8 Using the Yocto Amp in command line command is the command you want to run Almost all the functions available in the classic programming APIs are available as commands You need to respect neither the case nor the underlined characters in the command name parameters logically are the parameters needed by the command At any time the command line API executables can provide a rather detailed help Use for instance executable help to know the list of available commands for a given command line API executable or even executable command help to obtain a detailed description of the parameters of a command 8 3 Control of the Current function To control the Current function of your Yocto Amp you need the YCurrent executable file For instance you can launch YCurrent any get_currentValue This example uses the any target to indicate that we want to work on the first Current function found among all those available on the connected Yoctopuce modules when running This prevents you from having to know the exact names of your function and of your module But you can use logical names as well as long as you have configured them beforehand Let us imagine a Yocto Amp module with the YAMPMK01 123456 serial number which you have called MyModule and its current1 function which you have renamed MyFunction The five following calls are strictly equivalent as long as MyFunction is
103. buying this Yocto Amp and sincerely hopes that you will be satisfied with it The Yoctopuce engineers have put a large amount of effort to ensure that your Yocto Amp is easy to install anywhere and easy to drive from a maximum of programming languages If you are nevertheless disappointed with this module do not hesitate to contact Yoctopuce support By design all Yoctopuce modules are driven the same way Therefore user s guides for all the modules of the range are very similar If you have already carefully read through the user s guide of another Yoctopuce module you can jump directly to the description of the module functions 1 1 Prerequisites In order to use your Yocto Amp module you should have the following items at hand A computer Yoctopuce modules are intended to be driven by a computer or possibly an embedded microprocessor You will write the control software yourself according to your needs using the information provided in this manual Yoctopuce provides software libraries to drive its modules for the following operating systems Windows Mac OS X Linux and Android Yoctopuce modules do not require installing any specific system driver as they leverage the standard HID driver provided with every operating system 1 support yoctopuce com www yoctopuce com 1 Introduction Windows versions currently supported are Windows XP Windows 2003 Windows Vista and Windows 7 Both 32 bit and 64 bit versions ar
104. c class Inventory extends Activity Override public void onCreate Bundle savedInstanceState super onCreate savedIinstanceState setContentView R layout inventory public void refreshInventory View view LinearLayout layout LinearLayout findViewById R id inventoryList layout removeAllViews cry 4 YAPI UpdateDeviceList YModule module YModule FirstModule while module null String line module get_serialNumber module get_productName TextView tx new TextView this tx setText line layout addView tx module module nextModule Pp cach AETI ceprson ei i e printStackTrace Override protected void onStart SUPE ISOM clate ip try 4 YAPI EnableUSBHost this YAPI RegisterHub usb Peate YAPT OE cepr lon Te er printortackurcacel i refreshInventory null Override protected void onStop super onStop YAPI FreeAPI 106 www yoctopuce com 18 Using the Yocto Amp with Android 18 7 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible
105. c libraries The low level Yoctopuce API is available under several formats of dynamic libraries written in C The sources are available with the C API If you use one of these low level libraries you do not need the VirtualHub anymore Filename Platform libyapi dylib Max OS X libyapi amd64 so Linux Intel 64 bits libyapi armel so Linux ARM EL libyapi armhf so Linux ARM HL libyapi i386 so Linux Intel 32 bits yapi64 dll Windows 64 bits yapi dll Windows 32 bits These dynamic libraries contain all the functions necessary to completely rebuild the whole high level API in any language able to integrate these libraries This chapter nevertheless restrains itself to describing basic use of the modules Driving a module The three essential functions of the low level API are the following ine Veo wrmine Ab lint iConne ci Onmrype char erirmsG i int yapiUpdateDeviceList int forceupdate char errmsg int yapiHTTPRequest char device char request char buffer int buffsize int fullsize char errmsg The yapilnitAPI function initializes the API and must be called once at the beginning of the program For a USB type connection the connection_type parameter takes value 1 The errmsg parameter must point to a 255 character buffer to retrieve a potential error message This pointer can also point to null The function returns a negative integer in case of error zero otherwise The yapiUpdateDeviceList manages the inventory of
106. cached values for the module that have not yet expired the device is considered reachable No exception is raised if there is an error while trying to contact the requested module Returns true if the module can be reached and false otherwise 180 www yoctopuce com 21 High level API Reference module gt isOnline_async YModule Checks if the module is currently reachable without raising any error function isOnline_async callback context function isOnline_async callback context If there are valid cached values for the module that have not yet expired the device is considered reachable No exception is raised if there is an error while trying to contact the requested module This asynchronous version exists only in Javascript It uses a callback instead of a return value in order to avoid blocking Firefox Javascript VM that does not implement context switching during blocking I O calls Parameters callback callback function that is invoked when the result is known The callback function receives three arguments the caller specific context object the receiving module object and the boolean result context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback www yoctopuce com 181 21 High level API Reference module load YModule Preloads the module cache with a specified validity duration is__ functi
107. can use logical names as well as long as you have initialized them Let us imagine a Yocto Amp module with serial number YAMPMK0O1 123456 which you have named MyModule and for which you have given the current function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once YCurrent current yFindCurrent YAMPMKO01 123456 current1 YyCurrent current yFindCurrent YAMPMK01 123456 MyFunction yFindCurrent yCurrent current MyModule current1 YCurrent current yFindCurrent MyModule MyFunction YCurrent current yFindCurrent MyFunction yFindCurrent returns an object which you can then use at will to control the current sensor isOnline The isOnline method of the object returned by yFindCurrent allows you to know if the corresponding module is present and in working order get_currentValue The get _currentValue method of the object returned by yFindCurrent allows you to obtain the current as measured by the sensor The returned value is a number directly representing the value in mA 12 2 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon import lt Foundation Foundation h gt import yocto_api h static void usage const char exe NSLog usage
108. ce yocto_api php include yocto_api h import yocto_api h uses yocto_api yocto_api vb yocto_api cs import com yoctopuce YoctoAPI YModule from yocto_api import YDataSet methods dataset get_endTimeUTC Returns the end time of the dataset relative to the Jan 1 1970 dataset get_functionld Returns the hardware identifier of the function that performed the measure without reference to the module dataset get_hardwareld Returns the unique hardware identifier of the function who performed the measures in the form SERIAL FUNCTIONID dataset get_measures Returns all measured values currently available for this DataSet as a list of YMeasure objects dataset get_preview Returns a condensed version of the measures that can retrieved in this YDataSet as a list of YMeasure objects dataset get_progress Returns the progress of the downloads of the measures from the data logger on a scale from 0 to 100 dataset get_startTimeUTC Returns the start time of the dataset relative to the Jan 1 1970 dataset get_summary Returns an YMeasure object which summarizes the whole DataSet dataset get_unit Returns the measuring unit for the measured value www yoctopuce com 273 21 High level API Reference dataset loadMore Loads the the next block of measures from the dataLogger and updates the progress indicator dataset loadMore_async callback context Loa
109. ceptions By default it is the behavior of the Yoctopuce library If an error happens while you try to access a module the library throws an exception In this case there are three possibilities e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the most desirable the Yoctopuce library offers another possibility for error handling allowing you to create a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get _state method returns a Y STATE INVALID value a get _currentValue method returns a Y CURRENTVALUE INVALID value and so on In any case the returned value is of the expected type and is not a null pointer which would risk crashing your program At worst if you display the value without testing it it will be outside the expected bounds for the retu
110. ces through a VirtualHub software The modification is trivial it is just a matter of parameter change in the yRegisterHub call 7 7 Programming where to start At this point of the user s guide you should know the main theoretical points of your Yocto Amp It is now time to practice You must download the Yoctopuce library for your favorite programming language from the Yoctopuce web site Then skip directly to the chapter corresponding to the chosen programming language All the examples described in this guide are available in the programming libraries For some languages the libraries also include some complete graphical applications with their source code When you have mastered the basic programming of your module you can turn to the chapter on advanced programming that describes some techniques that will help you make the most of your Yocto Amp 2 http www yoctopuce com EN libraries php 26 www yoctopuce com 7 Programming general concepts www yoctopuce com 27 28 www yoctopuce com 8 Using the Yocto Amp in command line When you want to perform a punctual operation on your Yocto Amp such as reading a value assigning a logical name and so on you can obviously use the Virtual Hub but there is a simpler faster and more efficient method the command line API The command line API is a set of executables one by type of functionality offered by the range of Yoctopuce products These executa
111. con program modulecontrol SAPPTYPE CONSOLE uses SVa UCS yocto_ api const serial YAMPMK01 123456 use serial number or logical name procedure refresh module Tymodule begin if module isOnline then begin Weiceln aur Writeln Serial 7 module nge res crrlall Number k Writeln Logical name module get_logicalName Writeln Luminosity intToStr module get_luminosity Write Beacon ee BE module get_beacon Y_ BEACON ON then Writeln on else Writeln off Writeln uptime 7 ent ho Sita module toget uptime dav OOO ES isi i Writeln USB current oo Ve ap intToStr module get_usbCurrent mA www yoctopuce com 81 15 Using Yocto Amp with Delphi Writeln Logs 5 Ve Writeln module get_lastlogs Writeln Writeln refresh b beacon ON space beacon off end else Writeln Module not connected check identification and USB cable end procedure beacon module Tymodule state integer begin module set_beacon state refresh module end var module TYModule Tehat errmsg string began Setup the API to use local USB devices if yRegisterHub usb errmsg lt gt YAPI SUCCESS then begin Write RegisterHub error errmsg exit end module yFindModule serial refresh module TASSEN fread c case c of r refresh module b beacon module Y BEACON ON 1s beacon module Y BEACON TORE
112. connected Yoctopuce modules It must be called at least once To manage hot plug and detect potential newly connected modules this function must be called at regular intervals The forceupdate parameter must take value 1 to force a hardware scan The errmsg parameter must point to a 255 character buffer to retrieve a potential error message This pointer can also point to null The function returns a negative integer in case of error zero otherwise Finally the yapiHT TPRequest function sends HTTP requests to the module REST API The device parameter contains the serial number or the logical name of the module which you want to reach The request parameter contains the full HTTP request including terminal line breaks buffer points to a character buffer long enough to contain the answer buffsize is the size of the buffer fullsize is a pointer to an integer to which will be assigned the actual size of the answer The errmsg parameter must point to a 255 character buffer to retrieve a potential error message This pointer can also point to null The function returns a negative integer in case of error zero otherwise The format of the requests is the same as the one described in the VirtualHub et HTTP GET section All the character strings used by the API are strings made of 8 bit characters Unicode and UTF8 are not supported The resutlt returned in the buffer variable respects the HTTP protocol It therefore includes an HTTP header This header
113. cript1 5 type text JavaScript gt n Print setTimeout window location reload 1000 Pe ime UCE PENNA eS lt BODY gt lt HTML gt 10 3 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon lt HTML gt lt HEAD gt lt TITLE gt Module Control lt TITLE gt lt HEAD gt lt BODY gt lt FORM method get gt lt php include yocto_api php Use explicit error handling rather than exceptions yDisableExceptions Setup the API to use the VirtualHub on local machine if yRegisterHub http 127 0 0 1 4444 Serrmsg YAPI SUCCESS die Cannot contact VirtualHub on 127 0 0 1 Serrmsg www yoctopuce com 43 10 Using Yocto Amp with PHP Sserial GET serial ie Geertie P 0 Check if a specified module is available online Smodule yFindModule S serial if Smodule gt isOnline die Module not connected check serial and USB cable else or use any connected module suitable for the demo Smodule yFirstModule if module skip VirtualHub Smodule Smodule gt nextModule if is_null Smodule die No module connected check USB cable else serial module gt get_serialnumber Print Module to use lt input name serial value Sserial
114. ction However this modification is performed only in the random access memory RAM of the module if the module is restarted the modifications are lost To memorize them persistently it is necessary to ask the module to save its current configuration in its permanent memory To do so use the saveToFlash method Inversely it is possible to force the module to forget its current settings by using the revertFromFlash method The short example below allows you to modify the logical name of a module lt HTML gt lt HEAD gt lt TITLE gt save settings lt TITLE gt lt BODY gt lt FORM method get gt lt php include yocto_api php Use explicit error handling rather than exceptions yDisableExceptions Setup the API to use the VirtualHub on local machine if yRegisterHub http 127 0 0 1 4444 Serrmsg YAPI_SUCCESS 44 www yoctopuce com 10 Using Yocto Amp with PHP dve MGannot contact Vamtualiiib on 27m0 OTIC serra See Serra ae Secreta Yo UN Ff Check if a specified module is available online Smodule yFindModule S serial if Smodule gt isOnline die Module not connected check serial and USB cable else or use any connected module suitable for the demo Smodule yFirstModule if module skip VirtualHub Smodule Smodule gt nextModule if is_null Smodule die No module connected check USB cable else serial module gt
115. ction the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get _state method returns a Y STATE INVALID value a get _currentValue method returns a Y CURRENTVALUE INVALID value and so on In any case the returned value is of the expected type and is not a null pointer which would risk crashing your program At worst if you display the value without testing it it will be outside the expected 38 www yoctopuce com 9 Using Yocto Amp with Javascript bounds for the returned value In the case of functions which do not normally return information the return value is YAPI SUCCESS if everything went well and a different error code in case of failure When you work without exceptions you can obtain an error code and an error message explaining the source of the error You can request them from the object which returned the error calling the errType and errMessage methods Their returned values contain the same information as in the exceptions when they are active www yoctopuce com 39 40 www yoctopuce com 10 Using Yocto Amp with PHP PHP is like Javascript an atypical language when interfacing with hardware is at stakes Nevertheless using PHP with Yoctopuce modules provides you with the opportunity to very easily create web sites which are able to interact with their physical environment
116. current as measured by the sensor The returned value is a number directly representing the value in mA 100 www yoctopuce com 18 Using the Yocto Amp with Android A real example Launch you Java environment and open the corresponding sample project provided in the directory Examples Doc Examples of the Yoctopuce library In this example you can recognize the functions explained above but this time used with all the side materials needed to make it work nicely as a small demo package com yoctopuce doc_examples import android app Activity import android os Bundle import android os Handler import android view View import android widget AdapterView import android widget AdapterView OnItemSelectedListener import android widget ArrayAdapter import android widget Spinner import android widget TextView import com yoctopuce YoctoAPI YAPI import com yoctopuce YoctoAPI YAPI Exception import com yoctopuce YoctoAPI YCurrent import com yoctopuce YoctoAPI YModule public class GettingStarted Yocto Amp extends Activity implements OnItemSelectedListener private ArrayAdapter lt String gt aa Met eNee Sieve Sree Au private Handler handler null Override public void onCreate Bundle savedInstanceState i super onCreate savedInstanceState setContentView R layout gettingstarted_yocto_amp Spinner my spin Spinner findViewById R id spinner1 my spin setOnItemSelectedListener thi
117. d of the device serial number and of the hardware identifier of the current sensor for example RELAYLO1 123456 relayl1 Returns a string that uniquely identifies the current sensor ex RELAYLO1 123456 relayl1 On failure throws an exception or returns Y_HARDWAREID_INVALID 210 www yoctopuce com 21 High level API Reference current get_highestValue current highestValue Returns the maximal value observed function get_highestValue function get_highestValue function get_highestValue double get_highestValue double highestValue function get_highestValue double function get_highestValue As Double double get_highestValue double get_highestValue def get_highestValue YCurrent target get_highestValue Returns a floating point number corresponding to the maximal value observed On failure throws an exception or returns Y_HIGHESTVALUE_INVALID YCurrent www yoctopuce com 211 21 High level API Reference current get_logFrequency YCurrent current logFrequency Returns the datalogger recording frequency for this function or OFF when measures are not stored in the data logger flash memory function get_logFrequency function get_logFrequency function get_logFrequency string get_logFrequency NSString logFrequency function get_logFrequency string function get_logFrequency As String string get_logFrequency S
118. dTimeUTC Returns the end time of the measure relative to the Jan 1 1970 UTC Unix timestamp measure get_maxValue Returns the largest value observed during the time interval covered by this measure measure get_minValue Returns the smallest value observed during the time interval covered by this measure measure get_startTimeUTC Returns the start time of the measure relative to the Jan 1 1970 UTC Unix timestamp 286 www yoctopuce com 21 High level API Reference measure get_averageValue YMeasure measure averageValue Returns the average value observed during the time interval covered by this measure function get_averageValue function get_averageValue function get_averageValue double get_averageValue double averageValue function get_averageValue double function get_averageValue As Double double get_averageValue double get_averageValue def get_averageValue Returns a floating point number corresponding to the average value observed www yoctopuce com 287 21 High level API Reference measure gt get_endTimeUTC YMeasure measure endTimeUTC Returns the end time of the measure relative to the Jan 1 1970 UTC Unix timestamp function get_endTimeUTC function get_endTimeUTC function get_endTimeUTC double get_endTimeUTC double endTimeUTC function get_endTimeUTC double function get_endTimeUTC As Double doub
119. data logger Returns true if the data logger can be reached and false otherwise www yoctopuce com 261 21 High level API Reference datalogger isOnline_async YDataLogger Checks if the data logger is currently reachable without raising any error asynchronous version is _ function isOnline_async callback context node js function isOnline_async callback context If there is a cached value for the data logger in cache that has not yet expired the device is considered reachable No exception is raised if there is an error while trying to contact the device hosting the requested function This asynchronous version exists only in Javascript It uses a callback instead of a return value in order to avoid blocking the Javascript virtual machine Parameters callback callback function that is invoked when the result is known The callback function receives three arguments the caller specific context object the receiving function object and the boolean result context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback 262 www yoctopuce com 21 High level API Reference datalogger load YDataLogger Preloads the data logger cache with a specified validity duration function load msValidity function load msValidity function load msValidity YRETCODE load int msValidity YRETCODE load int ms
120. defined only once to avoid any ambiguity YCurrent YAMPMK01 123456 currentl describe YCurrent YAMPMK01 123456 MyFunction describe YCurrent MyModule currentl describe YCurrent MyModule MyFunction describe YCurrent MyFunction describe To work on all the Current functions at the same time use the all target YCurrent all describe For more details on the possibilities of the YCurrent executable use YCurrent help 8 4 Control of the module part Each module can be controlled in a similar way with the help of the YModule executable For example to obtain the list of all the connected modules use YModule inventory You can also use the following command to obtain an even more detailed list of the connected modules 30 www yoctopuce com 8 Using the Yocto Amp in command line YModule all describe Each xxx property of the module can be obtained thanks to a command of the get_xxxx type and the properties which are not read only can be modified with the set_xxx command For example YModule YAMPMKO01 12346 set _logicalName MonPremierModule YModule YAMPMKO01 12346 get_logicalName Changing the settings of the module When you want to change the settings of a module simply use the corresponding set xxx command However this change happens only in the module RAM if the module restarts the changes are lost To store them permanently you must tell the module to save its current configuration in its nonvo
121. details Parameters callback callback function that is invoked when the result is known The callback function receives three arguments the caller specific context object the receiving function object and the requested YModule object context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback 216 www yoctopuce com 21 High level API Reference current get_recordedData YCurrent current recordedData Retrieves a DataSet object holding historical data for this sensor for a specified time interval function get_recordedData startTime endTime function get_recordedData startTime endTime function get_recordedData startTime endTime YDataSet get_recordedData s64 startTime s64 endTime YDataSet recordedData s64 startTime S64 endTime function get_recordedData startTime int64 endTime int64 TYDataSet function get_recordedData As YDataSet YDataSet get_recordedData long startTime long endTime YDataSet get_recordedData long startTime long endTime def get_recordedData startTime endTime YCurrent target get_recordedData startTime endTime The measures will be retrieved from the data logger which must have been turned on at the desired time See the documentation of the DataSet class for information on how to get an overview of the recorded data and how to load progressively a large set of measures from the d
122. ds the the next block of measures from the dataLogger asynchronously 274 www yoctopuce com 21 High level API Reference dataset get_endTimeUTC YDataSet dataset endTimeUTC Returns the end time of the dataset relative to the Jan 1 1970 function get_endTimeUTC function get_endTimeUTC function get_endTimeUTC s64 get_endTimeUTC s64 endTimeUTC function get_endTimeUTC int64 function get_endTimeUTC As Long long get_endTimeUTC long get_endTimeUTC def get_endTimeUTC When the YDataSet is created the end time is the value passed in parameter to the get_dataSet function After the very first call to LoadMore the end time is updated to reflect the timestamp of the last measure actually found in the dataLogger within the specified range Returns an unsigned number corresponding to the number of seconds between the Jan 1 1970 and the end of this data set i e Unix time representation of the absolute time www yoctopuce com 275 21 High level API Reference dataset get_functionld YDataSet dataset functionld Returns the hardware identifier of the function that performed the measure without reference to the module function get_functionld function get_functionld function get_functionld string get_functionld NSString functionld function get_functionld string v function get_functionld As String string get_functionld
123. e System out printin ex getMessage System exit 1 YAPI FreeAPI Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the YModule saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the YModule yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not null Below a short example listing the connected modules import com yoctopuce YoctoAPI public class Demo PUL Ew Stat ie vord Maan StesnG args try setup the API to use local VirtualHub YAPI RegisterHub 127 0 0 1 I eaman CAAPI Teorem e System kout prinia weannoe iContact VarevalHubmons 2n OR Oma ex getLocalizedMessage System out printin Ensure that the VirtualHub application is running System exit 1 Sye cem out prine Enea Gem Sti YModule module YModule FirstModule while module null try SYSUeM ouk pEUntElm mModulergeiserualiNumbe e ety yee mod
124. e throws an exception or returns Y_UNIT_INVALID YCurrent 220 www yoctopuce com 21 High level API Reference current get_userData YCurrent current userData Returns the value of the userData attribute as previously stored using method set_userData function get_userData function get_userData function get_userData void get_userData void userData function get_userData Tobject function get_userData As Object object get_userData Object get_userData def get_userData This attribute is never touched directly by the API and is at disposal of the caller to store a context Returns the object stored previously by the caller www yoctopuce com 221 21 High level API Reference current isOnline YCurrent Checks if the current sensor is currently reachable without raising any error is function isOnline node js function isOnline php_ function isOnline cpp _ bool isOnline BOOL isOnline pas function isOnline boolean vb function isOnline As Boolean bool isOnline java_ boolean isOnline def isOnline If there is a cached value for the current sensor in cache that has not yet expired the device is considered reachable No exception is raised if there is an error while trying to contact the device hosting the current sensor Returns t rue if the current sensor can be reached and false o
125. e Current function include yocto_api h include yocto_ current h bes String errmsg YCurrent current Get access to your device connected locally on USB for instance yRegisterHub usb errmsg current yFindCurrent YAMPMK01 123456 current1 1 http www microsoft com visualstudio en us products 2010 editions visual cpp express www yoctopuce com EN libraries php www yoctopuce com 51 11 Using Yocto Amp with C Hot plug is easy just check that the device is online if current gt isOnline 7 USe cuErone JormeuErentaValie l um ar Let s look at these lines in more details yocto_api h et yocto_current h These two include files provide access to the functions allowing you to manage Yoctopuce modules yocto api h must always be used yocto current h is necessary to manage modules containing a current sensor such as Yocto Amp yRegisterHub The yRegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for When used with the parameter usb it will use the modules locally connected to the computer running the library If the initialization does not succeed this function returns a value different from YAPI SUCCESS and errmsg contains the error message yFindCurrent The yFindCurrent function allows you to find a current sensor from the serial number of the module on which it resides and from its function name You can use log
126. e Java for Android library 18 3 Compatibility In an ideal world you would only need to have a smart phone running under Android to be able to make Yoctopuce modules work Unfortunately it is not quite so in the real world A machine running under Android must fulfil to a few requirements to be able to manage Yoctopuce USB modules natively 1 www yoctopuce com EN libraries php www yoctopuce com 97 18 Using the Yocto Amp with Android Android 4 x Android 4 0 api 14 and following are officially supported Theoretically support of USB host functions since Android 3 1 But be aware that the Yoctopuce Java for Android API is regularly tested only from Android 4 onwards USB host support Naturally not only must your machine have a USB port this port must also be able to run in host mode In host mode the machine literally takes control of the devices which are connected to it The USB ports of a desktop computer for example work in host mode The opposite of the host mode is the device mode USB keys for instance work in device mode they must be controlled by a host Some USB ports are able to work in both modes they are OTG On The Go ports It so happens that many mobile devices can only work in device mode they are designed to be connected to a charger or a desktop computer and nothing else It is therefore highly recommended to pay careful attention to the technical specifications of a product working under Andr
127. e com 251 21 High level API Reference datalogger get_functionDescriptor YDataLogger datalogger functionDescriptor Returns a unique identifier of type YFUN_DESCR corresponding to the function function get_functionDescriptor function get_functionDescriptor function get_functionDescriptor YFUN_DESCR get_functionDescriptor YFUN_DESCR functionDescriptor function get_functionDescriptor YFUN_DESCR function get_functionDescriptor As YFUN_DESCR YFUN_DESCR get_functionDescriptor String get_functionDescriptor def get_functionDescriptor This identifier can be used to test if two instances of YFunction reference the same physical function on the same physical device Returns an identifier of type YFUN_DESCR If the function has never been contacted the returned value is Y_FUNCTIONDESCRIPTOR_INVALID 252 www yoctopuce com 21 High level API Reference datalogger get_functionld YDataLogger datalogger functionld Returns the hardware identifier of the data logger without reference to the module function get_functionld function get_functionld function get_functionld string get_functionld NSString functionld function get_functionld As String string get_functionld String get_functionld def get_functionld For example relayl Returns a string that identifies the data logger ex relay1 On failure throws an exception or r
128. e interval the average value observed during the time interval the maximal value observed during the time interval This summary is available as soon as LoadMore has been called for the first time Returns an YMeasure object 282 www yoctopuce com 21 High level API Reference dataset get_unit dataset unit Returns the measuring unit for the measured value function get_unit function get_unit function get_unit string get_unit NSString unit function get_unit string function get_unit As String string get_unit String get_unit def get_unit Returns a string that represents a physical unit On failure throws an exception or returns Y_UNIT_INVALID YDataSet www yoctopuce com 283 21 High level API Reference dataset loadMore YDataSet Loads the the next block of measures from the dataLogger and updates the progress indicator is _ function loadMore node js function loadMore php function loadMore cpp _ int loadMore int loadMore pas _ function loadMore LongInt ve function loadMore As Integer cs__ int loadMore java _ int loadMore def loadMore Returns an integer in the range 0 to 100 percentage of completion or a negative error code in case of failure On failure throws an exception or returns a negative error code 284 www yoctopuce com 21 High level API R
129. e memory as when the module is powered on module gt saveToFlash Saves current settings in the nonvolatile memory of the module module set_beacon newval Turns on or off the module localization beacon www yoctopuce com 151 21 High level API Reference module set_logicalName newval Changes the logical name of the module module set_luminosity newval Changes the luminosity of the module informative leds module set_usbBandwidth newval Changes the number of USB interfaces used by the module module gt set_userData data Stores a user context provided as argument in the userData attribute of the function module triggerFirmwareUpdate secBeforeReboot Schedules a module reboot into special firmware update mode module wait_async callback context Waits for all pending asynchronous commands on the module to complete and invoke the user provided callback function 152 www yoctopuce com 21 High level API Reference YModule FindModule YModule yFindModule Allows you to find a module from its serial number or from its logical name function yFindModule func function FindModule func function yFindModule func YModule yFindModule string func YModule yFindModule NSString func function yFindModule func string TYModule function yFindModule ByVal func As String As YModule YModule FindModule string func YModule FindModule String func def FindModule func
130. e module as set by the factory module get_productRelease Returns the hardware release version of the module module get_rebootCountdown Returns the remaining number of seconds before the module restarts or zero when no reboot has been scheduled module gt get_serialNumber Returns the serial number of the module as set by the factory module get_upTime Returns the number of milliseconds spent since the module was powered on module get_usbBandwidth Returns the number of USB interfaces used by the module module get_usbCurrent Returns the current consumed by the module on the USB bus in milli amps module get_userData Returns the value of the userData attribute as previously stored using method set_userData module gt isOnline Checks if the module is currently reachable without raising any error module isOnline_async callback context Checks if the module is currently reachable without raising any error module load msValidity Preloads the module cache with a specified validity duration module load_async msValidity callback context Preloads the module cache with a specified validity duration asynchronous version module nextModule Continues the module enumeration started using yFirstModule module gt reboot secBeforeReboot Schedules a simple module reboot after the given number of seconds module gt revertFromFlash Reloads the settings stored in the nonvolatil
131. e module is connected It takes as parameter the relevant module static void deviceArrival YModule m Console WriteLine New module m get_serialNumber www yoctopuce com 109 19 Advanced programming Initialization You must then tell the API that it must call the callback when a new module is connected YAPI RegisterDeviceArrivalCallback deviceArrival Note that if modules are already connected when the callback is registered the callback is called for each of the already connected modules Triggering callbacks A classis issue of callback programming is that these callbacks can be triggered at any time including at times when the main program is not ready to receive them This can have undesired side effects such as dead locks and other race conditions Therefore in the Yoctopuce API module arrival departure callbacks are called only when the UpdateDeviceList function is running You only need to call UpdateDeviceList at regular intervals from a timer or from a specific thread to precisely control when the calls to these callbacks happen waiting loop managing callbacks while true module arrival departure callback YAP UpdateDevicelist ref errmsg non active waiting time managing other callbacks VAP I Sileep S00 ae nerro y In a similar way it is possible to have a callback when a module is disconnected You can find a complete example implemented in your favorite program
132. e simple to use and sufficiently generic for the concepts used to be valid for all the modules in the Yoctopuce range and this in all the available programming languages Therefore when you have understood how to drive your Yocto Amp with your favorite programming language learning to use another module even with a different language will most likely take you only a minimum of time 7 1 Programming paradigm The Yoctopuce API is object oriented However for simplicity s sake only the basics of object programming were used Even if you are not familiar with object programming it is unlikely that this will be a hinderance for using Yoctopuce products Note that you will never need to allocate or deallocate an object linked to the Yoctopuce API it is automatically managed There is one class per Yoctopuce function type The name of these classes always starts with a Y followed by the name of the function for example YTemperature YRelay YPressure etc There is also a YModule class dedicated to managing the modules themselves and finally there is the static YAPI class that supervises the global workings of the API and manages low level communications Low level handling Module handling Feature handling YAPI YModule YTemperature YPressure YRelay Y XXX Structure of the Yoctopuce API In the Yoctopuce API priority was put on the ease of access to the module functions by offering the possibility to make abstractions
133. e supported Yoctopuce is frequently testing its modules on Windows XP and Windows 7 Mac OS X versions currently supported are 10 6 Snow Leopard Mac OS X 10 7 Lion and 10 8 Mountain Lion Yoctopuce is frequently testing its modules on Mac OS X 10 6 and 10 7 Linux kernels currently supported are the 2 6 branch and the 3 0 branch Other versions of the Linux kernel and even other UNIX variants are very likely to work as well as Linux support is implemented through the standard libusb API Yoctopuce is frequently testing its modules on Linux kernel 2 6 Android versions currently supported are Android 3 1 and later Moreover it is necessary for the tablet or phone to support the Host USB mode Yoctopuce is frequently testing its modules on Android 4 x on a Nexus 7 and a Samsung Galaxy S3 with the Java for Android library A USB cable type A micro B USB connectors exist in three sizes the standard size that you probably use to connect your printer the very common mini size to connect small devices and finally the micro size often used to connect mobile phones as long as they do not exhibit an apple logo All USB modules manufactured by Yoctopuce use micro size connectors 1 8 8 The most common USB 2 connectors A B Mini B Micro A Micro B 3 To connect your Yocto Amp module to a computer you need a USB cable of type A micro B The price of this cable may vary a lot depending on the source look for it under the n
134. easure gt get_measures ArrayList lt YMeasure gt get_measures def get_measures Each item includes the start of the measure time interval the end of the measure time interval the minimal value observed during the time interval the average value observed during the time interval the maximal value observed during the time interval Before calling this method you should call loadMore to load data from the device You may have to call loadMore several time until all rows are loaded but you can start looking at available data rows before the load is complete The oldest measures are always loaded first and the most recent measures will be loaded last As a result timestamps are normally sorted in ascending order within the measure table unless there was an unexpected adjustment of the datalogger UTC clock Returns a table of records where each record depicts the measured value for a given time interval On failure throws an exception or returns an empty array 278 www yoctopuce com 21 High level API Reference dataset get_preview YDataSet dataset preview Returns a condensed version of the measures that can retrieved in this YDataSet as a list of YMeasure objects function get_preview function get_preview function get_preview vector lt YMeasure gt get_preview NSMutableArray preview function get_preview TYMeasureArray function get_preview As List List lt Y
135. ed by the module micro processor is located at about 100000 cycles In short you can use the saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not Nothing Belowa short example listing the connected modules Module Modulel Sub Main Dim M As ymodule Dim errmsg As String REM Setup the API to use local USB devices If yRegisterHub usb errmsg lt gt YAPI_ SUCCESS Then Console WriteLine RegisterHub error errmsg End End if Console WriteLine Device list M yFirstModule While M IsNot Nothing ConsoverWrittehine Migee serlallNumbex 1 Moget productNamei 7 i M M nextModule www yoctopuce com 69 13 Using Yocto Amp with Visual Basic NET End While End Sub End Module 13 5 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your c
136. ed with a data logger able to store non stop the measures performed by the module The maximal frequency is 100 times per second i e 100 s and the minimal frequency is 1 time per hour i e 1 h When the frequency is higher than or equal to 1 s the measure represents an instant value When the frequency is below the measure will include distinct minimal maximal and average values based on a sampling performed automatically by the device The data logger flash memory can store about 500 000 instant measures or 125 000 averaged measures When the memory is about to be saturated the oldest measures are automatically erased Make sure not to leave the data logger running at high speed unless really needed the flash memory can only stand a limited number of erase cycles typically 100 000 cycles When running at full speed the datalogger can burn more than 100 cycles per day Also be aware that it is useless to record measures at a frequency higher than the refresh frequency of the physical sensor itself Starting stopping the datalogger The data logger can be started with the set_ recording method YDataLogger 1 YDataLogger FirstDataLogger 1 set_recording YDataLogger RECORDING ON It is possible to make the data recording start automatically as soon as the module is powered on YDataLogger 1 YDataLogger FirstDataLogger 1 set_autoStart YDataLogger AUTOSTART ON liget moduile saveToFlash do not forget to
137. eee bkeie Gh Sr import os sys from yocto_api import def usage Sys exit usage demo lt serial or logical name gt lt new logical name gt if len sys argv 3 usage errmsg YRefParam if YAPI RegisterHub usb errmsg YAPI SUCCESS sys exit RegisterHub error str errmsg m YModule FindModule sys argv 1 use serial or logical name iE m Ss Omnlleamen es newname sys argv 2 if not YAPI CheckLogicalName newname sys exit Invalid name newname m set_logicalName newname m saveToFlash do not forget this print Module serial m get_serialNumber name m get_logicalName else sys exit Ynot connected check identi ticarion and WSB cabile Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the YModule saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the YModule yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as
138. eference dataset loadMore_async YDataSet Loads the the next block of measures from the dataLogger asynchronously function loadMore_async callback context function loadMore_async callback context Parameters callback callback function that is invoked when the w The callback function receives three arguments the user specific context object the YDataSet object whose loadMore_async was invoked the load result either the progress indicator 0 100 or a negative error code in case of failure context user specific object that is passed as is to the callback function Returns nothing www yoctopuce com 285 21 High level API Reference 21 6 Measured value YMeasure objects are used within the API to represent a value measured at a specified time These objects are used in particular in conjunction with the YDataSet class In order to use the functions described here you should include lt script type text javascript src yocto_api js gt lt script gt var yoctolib require yoctolib var YAPI yoctolib YAPI var YModule yoctolib YModule require_once yocto_api php include yocto_api h import yocto_api h uses yocto_api yocto_api vb yocto_api cs import com yoctopuce YoctoAPI YModule from yocto_api import YMeasure methods measure get_averageValue Returns the average value observed during the time interval covered by this measure measure get_en
139. effort to attach a reasonable timestamp to the measures using the timestamp found on the latest recorded measures It is therefore possible to preset to the real time an autonomous Yocto Amp by connecting it to an Android mobile phone starting the data logger then connecting the device alone on an USB charger Nevertheless be aware that without external time source the internal clock of the Yocto Amp might be be subject to a clock skew theoretically up to 0 3 19 3 Sensor calibration Your Yocto Amp module is equipped with a digital sensor calibrated at the factory The values it returns are supposed to be reasonably correct in most cases There are however situations where external conditions can impact the measures The Yoctopuce API provides the mean to re caliber the values measured by your Yocto Amp You are not going to modify the hardware settings of the module but rather to transform afterwards the measures taken by the sensor This transformation is controlled by parameters stored in the flash memory of the module making it specific for each module This re calibration is therefore a fully software matter and remains perfectly reversible Before deciding to re calibrate your Yocto Amp module make sure you have well understood the phenomena which impact the measures of your module and that the differences between true values and measured values do not result from a incorrect use or an inadequate location of the module 1
140. employed by the module micro processor is located at about 100000 cycles In short you can use the YModule saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the YModule yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not null Below a short example listing the connected modules using System using System Collections Generic using System Ling using System Text namespace ConsoleApplicationl class Program static void Main string args YModule m sering Giemusice Wills if YAPI RegisterHub usb ref errmsg YAPI SUCCESS Console WriteLine RegisterHub error errmsg Environment Exit 0 Console WriteLine Device list m YModule FirstModule while m null1 eConsollenw mgeiminer Mac Ce mserrltcewNUM Det en eet eem ore cuic EN ame nu ey m m nextModule 14 5 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you
141. en Et axgyv 2 ON Then m set_beacon Y_ BEACON ON If argv 2 OFF Then m set_ beacon Y_ BEACON OFF End TE Console WriteLine serial Wo moget ser taliNumbers Console WriteLine logical name m get_logicalName Console WriteLine luminosity n Str m get_luminosity Console Write beacon my Ee miget beacon YeBEACONsON ihen Console WriteLine ON Else Console WriteLine OFF ENATTE Console WriteLine upTime u Stem get uprimne 7000 see ConsolenWritehine AUSB current M Str m get UsbEUrcrent ODE AETA Console WriteLine Logs Console WriteLine Else Console WriteLine argv 1 not connected check identification and USB cable End If m get_lasthogs End Sub End Module Each property xxx of the module can be read thanks to a method of type get _xxxx and properties which are not read only can be modified with the help of the set _xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding set xxx function However this modification is performed only in the random access memory RAM of the module if the module is restarted the modifications are lost To memorize them persistently it is necessary to ask the module to save its current configuration in its permanent memory To do so use the saveToFlash method Inverse
142. end umtii x end Each property xxx of the module can be read thanks to a method of type get _xxxx and properties which are not read only can be modified with the help of the set xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding set xxx function However this modification is performed only in the random access memory RAM of the module if the module is restarted the modifications are lost To memorize them persistently it is necessary to ask the module to save its current configuration in its permanent memory To do so use the saveToFlash method Inversely it is possible to force the module to forget its current settings by using the revertFromFlash method The short example below allows you to modify the logical name of a module program savesettings SAPPTYPE CONSOLE uses Sys Sp yocto_ api const serial YAMPMK01 123456 use serial number or logical name var module TYModule Guess 8 SENEE newname string begin Setup the API to use local USB devices if yRegisterHub usb errmsg lt gt YAPI SUCCESS then begin Write RegisterHub error errmsg exit 82 www yoctopuce com 15 Using Yocto Amp with Delphi end module yFindModule serial if not module isOnline then begin writeln Module not connected
143. ensor null System out printlin No module connected check USB cablle System exit 1 cry 4 serial sensor module get_serialNumber Pecat cha VAP REE ce pielonmess System out println No module connected check USB cable System exit 1 Demo demo serial Y current M serial current2 YAPI FreeAPI 17 3 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon import com yoctopuce YoctoAPI import java util logging Level import java util logging Logger public class Demo public static void main String args Ery setup the API to use local VirtualHub YAPI RegisterHub 127 0 0 1 Catch YAPT Exception ex System out printlin Cannot contact VirtualHub on 127 0 0 1 ex getLocalizedMessage System out println Ensure that the VirtualHub application is running System exit 1 System out println usage demo serial or logical name ON OFF YModule module if args length 0 module YModule FirstModule if module null System out println No module connected check USB cable System exit 1 else module YModule FindModule args 0 use serial or logical name www yoctopuce com 93 17 Using the Yocto Amp with Java try
144. ent module gt functionCount Returns the number of functions beside the module interface available on the module module functionld functionIndex Retrieves the hardware identifier of the nth function on the module module functionName functionIndex Retrieves the logical name of the nth function on the module module functionValue functionIndex Retrieves the advertised value of the nth function on the module module get_beacon Returns the state of the localization beacon module get_errorMessage Returns the error message of the latest error with this module object module get_errorType Returns the numerical error code of the latest error with this module object module get_firmwareRelease Returns the version of the firmware embedded in the module module get_hardwareld Returns the unique hardware identifier of the module module get_icon2d 150 www yoctopuce com 21 High level API Reference Returns the icon of the module module get_lastLogs Returns a string with last logs of the module module get_logicalName Returns the logical name of the module module get_luminosity Returns the luminosity of the module informative leds from 0 to 100 module get_persistentSettings Returns the current state of persistent module settings module get_productld Returns the USB device identifier of the module module get_productName Returns the commercial name of th
145. es If the initialization does not succeed an exception is thrown YCurrent FindCurrent The YCurrent FindCurrent function allows you to find a current sensor from the serial number of the module on which it resides and from its function name You can use logical names as well as long as you have initialized them Let us imagine a Yocto Amp module with serial number YAMPMK0O1 123456 which you have named MyModule and for which you have given the current function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once current YCurrent FindCurrent current YCurrent FindCurrent YAMPMK01 123456 MyFunction YAMPMK01 123456 current1 current YCurrent FindCurrent MyModule current1 current YCurrent FindCurrent MyModule MyFunction current YCurrent FindCurrent MyFunction YCurrent FindCurrent returns an object which you can then use at will to control the current sensor isOnline The isOnline method of the object returned by YCurrent FindCurrent allows you to know if the corresponding module is present and in working order get_currentValue The get_currentValue method of the object returned by YCurrent FindCurrent allows you to obtain the current as measured by the sensor The returned value is a number directly representing the value in mA A real example Launch you Java environment and open the corresponding sample project provided
146. es with a non negligible advantage the application does not need to run on the machine on which the modules are connected The application can very well be located on another machine which connects itself to the service to drive the modules Moreover the native libraries and DLL mentioned above are also able to connect themselves remotely to one or several virtual hubs 1 www yoctopuce com EN virtualhub php www yoctopuce com 25 7 Programming general concepts When a virtual hub is used the control application does not need to reside on the same machine as the module Whatever the selected programming language and the control paradigm used programming itself stays strictly identical From one language to another functions bear exactly the same name and have the same parameters The only differences are linked to the constraints of the languages themselves Language Native Native with DLL Virtual hub C Objective C s Delphi Python VisualBasic Net s C Net Javascript Node js PHP Java Java for Android Command line Support methods for different languages Limitations of the Yoctopuce libraries Natives et DLL libraries have a technical limitation On the same computer you cannot concurrently run several applications accessing Yoctopuce devices directly If you want to run several projects on the same computer make sure your control applications use Yoctopuce devi
147. escribe As String string describe String describe def describe More precisely TYPE is the type of the function NAME it the name used for the first access to the function SERIAL is the serial number of the module if the module is connected or unresolved and FUNCTIONID is the hardware identifier of the function if the module is connected For example this method returns Relay MyCustomName relayl RELAYLO1 123456 relayl if the module is already connected or Relay BadCustomeName relayl unresolved if the module has not yet been connected This method does not trigger any USB or TCP transaction and can therefore be used in a debugger Returns a string that describes the current sensor ex Relay MyCustomName relayl RELAYLO1 123456 relayl www yoctopuce com 201 21 High level API Reference current get_advertisedValue YCurrent current advertisedValue Returns the current value of the current sensor no more than 6 characters function get_advertisedValue function get_advertisedValue function get_advertisedValue string get_advertisedValue NSString advertisedValue function get_advertisedValue string function get_advertisedValue As String string get_advertisedValue String get_advertisedValue def get_advertisedValue YCurrent target get_advertisedValue Returns a string cor
148. et dataset startTimeUTC Returns the start time of the dataset relative to the Jan 1 1970 function get_startTimeUTC function get_startTimeUTC function get_startTimeUTC s64 get_startTimeUTC s64 startTimeUTC function get_startTimeUTC int64 function get_startTimeUTC As Long long get_startTimeUTC long get_startTimeUTC def get_startTimeUTC When the YDataSet is created the start time is the value passed in parameter to the get_dataSet function After the very first call to LoadMore the start time is updated to reflect the timestamp of the first measure actually found in the dataLogger within the specified range Returns an unsigned number corresponding to the number of seconds between the Jan 1 1970 and the beginning of this data set i e Unix time representation of the absolute time www yoctopuce com 281 21 High level API Reference dataset get_summary YDataSet dataset summary Returns an YMeasure object which summarizes the whole DataSet function get_summary kodes function get_summary php function get_summary YMeasure get_summary YMeasure summary function get_summary TYMeasure function get_summary As YMeasure YMeasure get_summary YMeasure get_summary def get_summary In includes the following information the start of a time interval the end of a time interval the minimal value observed during the tim
149. et state method returns a Y STATE INVALID value a get _currentValue method returns a Y CURRENTVALUE INVALID value and so on In any case the returned value is of the expected type and is not a null pointer which would risk crashing your program At worst if you display the value without testing it it will be outside the expected www yoctopuce com 49 10 Using Yocto Amp with PHP bounds for the returned value In the case of functions which do not normally return information the return value is YAPI _ SUCC ESS if everything went well and a different error code in case of failure When you work without exceptions you can obtain an error code and an error message explaining the source of the error You can request them from the object which returned the error calling the errType and errMessage methods Their returned values contain the same information as in the exceptions when they are active 50 www yoctopuce com 11 Using Yocto Amp with C C is not the simplest language to master However if you take care to limit yourself to its essential functionalities this language can very well be used for short programs quickly coded and it has the advantage of being easily ported from one operating system to another Under Windows all the examples and the project models are tested with Microsoft Visual Studio 2010 Express freely available on the Microsoft web site
150. eturns Y_FUNCTIONID_INVALID www yoctopuce com 253 21 High level API Reference datalogger get_hardwareld YDataLogger datalogger hardwareld Returns the unique hardware identifier of the data logger in the form SERIAL FUNCTIONID function get_hardwareld function get_hardwareld function get_hardwareld string get_hardwareld NSString hardwareld function get_hardwareld As String string get_hardwareld String get_hardwareld def get_hardwareld The unique hardware identifier is composed of the device serial number and of the hardware identifier of the data logger for example RELAYLO1 123456 relayl1 Returns a string that uniquely identifies the data logger ex RELAYLO1 123456 relay1 On failure throws an exception or returns Y_HARDWAREID_INVALID 254 www yoctopuce com 21 High level API Reference datalogger get_logicalName YDataLogger datalogger logicalName Returns the logical name of the data logger function get_logicalName function get_logicalName function get_logicalName string get_logicalName NSString logicalName function get_logicalName string function get_logicalName As String string get_logicalName String get_logicalName def get_logicalName YDataLogger target get_logicalName Returns a string corresponding to the logical name of the data logger On failure throws an exception or return
151. evertFromFlash method The short example below allows you to modify the logical name of a module lt HTML gt lt HEAD gt lt TITLE gt Change module settings lt TITLE gt lt SCRIPT type text javascript srce yocto api js gt lt SCRIPIT gt lt SCRIPT language javascript1l 5 type text JavaScript gt lt Use explicit error handling rather than exceptions 36 www yoctopuce com 9 Using Yocto Amp with Javascript yDisableExceptions Setup the API to use the VirtualHub on local machine if yRegisterHub http 127 0 0 1 4444 YAPI SUCCESS alere Cannote contact Virecual Hub onm 127 Orda s var module function refresh var serial document getElementById serial value if serial Detect any conected module suitable for the demo module yFirstModule nextModule if module serial module get_serialNumber document getElementBylId serial value serial module yFindModule serial if module isOnline document getHlementById msg value ii document getElementById curName value module get_logicalName else document getElementBylId msg value Module not connected setTimeout refresh 1000 function save var newname document getElementByld newName value if yCheckLogicalName newname alert invalid logical name return module set_logicalName newname module saveT
152. ewval int set_autoStart int newval def set_autoStart newval YDataLogger target set_autoStart newval Remember to call the saveToF lash method of the module if the modification must be kept P Parameters newval either Y_AUTOSTART_OFF or Y_AUTOSTART_ON according to the default activation state of the data logger on power up Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 267 21 High level API Reference datalogger set_logicalName YDataLogger datalogger setLogicalName Changes the logical name of the data logger function set_logicalName newval function set_logicalName newval function set_logicalName newval int set_logicalName const string amp newval int setLogicalName NSString newval function set_logicalName newval string integer function set_logicalName ByVal newval As String As Integer int set_logicalName string newval int set_logicalName String newval def set_logicalName newval YDataLogger target set_logicalName newval You can use yCheckLogicalName prior to this call to make sure that your parameter is valid Remember to call the saveToFlash method of the module if the modification must be kept Parameters newval a string corresponding to the logical name of the data logger Returns YAPI_SUCCESS if the call succeeds On failure throws an exception or retur
153. f necessary to make it a little more discreet while limiting its power consumption Note that this parameter acts on all the signposting leds of the module including the Yocto led If you connect a module and no led turns on it may mean that its luminosity was set to zero Logical names of functions Each Yoctopuce module has a serial number and a logical name In the same way each function on each Yoctopuce module has a hardware name and a logical name the latter can be freely chosen by the user Using logical names for functions provides a greater flexibility when programming modules The two functions provided by the Yocto Amp module are the CurrentDC and CurrentAC functions Simply click on the corresponding rename button to assign a new logical name to one of the functions www yoctopuce com 13 14 www yoctopuce com 6 Assembly and connections This chapter provides important information regarding the use of the Yocto Amp module in real world situations Make sure to read it carefully before going too far into your project if you want to avoid pitfalls 6 1 Fixing While developing your project you can simply let the module hang at the end of its cable Check only that it does not come in contact with any conducting material such as your tools When your project is almost at an end you need to find a way for your modules to stop moving around Examples of assembly on supports The Yocto Amp module contain
154. for Mac OS X www yoctopuce com EN libraries php 3 www yoctopuce com EN virtualhub php www yoctopuce com 41 10 Using Yocto Amp with PHP Get access to your device through the VirtualHub running locally yRegisterHub http 127 0 0 1 4444 Serrmsg Scurrent yFindCurrent YAMPMK01 123456 currentl Check that the module is online to handle hot plug if current gt isOnline 7 USE cuErent get iCUErentaVa lies e Let s look at these lines in more details yocto_api php and yocto_current php These two PHP includes provides access to the functions allowing you to manage Yoctopuce modules yocto_api php must always be included yocto current php is necessary to manage modules containing a current sensor such as Yocto Amp yRegisterHub The yRegisterHub function allows you to indicate on which machine the Yoctopuce modules are located more precisely on which machine the VirtualHub software is running In our case the 127 0 0 1 4444 address indicates the local machine port 4444 the standard port used by Yoctopuce You can very well modify this address and enter the address of another machine on which the VirtualHub software is running yFindCurrent The yFindCurrent function allows you to find a current sensor from the serial number of the module on which it resides and from its function name You can use logical names as well as long as you have initialized them Let us imagine a Yocto Amp m
155. for programming on Mac OS X due to its integration with the Cocoa framework In order to use the Objective C library you need XCode version 4 2 earlier versions will not work available freely when you run Lion If you are still under Snow Leopard you need to be registered as Apple developer to be able to download XCode 4 2 The Yoctopuce library is ARC compatible You can therefore implement your projects either using the traditional retain release method or using the Automatic Reference Counting Yoctopuce Objective C libraries are integrally provided as source files A section of the low level library is written in pure C but you should not need to interact directly with it everything was done to ensure the simplest possible interaction from Objective C You will soon notice that the Objective C API defines many functions which return objects You do not need to deallocate these objects yourself the API does it automatically at the end of the application In order to keep them simple all the examples provided in this documentation are console applications Naturally the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface You can find on Yoctopuce blog a detailed example with video shots showing how to integrate the library into your projects 12 1 Control of the Current function Launch Xcode 4 2 and open the corresponding sample project provided in the directory Exa
156. function reboot secBeforeReboot function reboot secBeforeReboot function reboot secBeforeReboot int reboot int secBeforeReboot int reboot int secBeforeReboot function reboot secBeforeReboot Longint Longint function reboot As Integer int reboot int secBeforeReboot int reboot int secBeforeReboot def reboot secBeforeReboot YModule target reboot secBeforeReboot YModule Parameters secBeforeReboot number of seconds before rebooting Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 185 21 High level API Reference module gt revertFromFlash YModule Reloads the settings stored in the nonvolatile memory as when the module is powered on 5s function revertFromFlash koasjs function revertFromFlash prp function revertFromFlash cep_ int revertFromFlash int revertFromFlash eas _ function revertFromFlash Longint vo function revertFromFlash As Integer cs _ intrevertFromFlash java int revertFromFlash def revertFromFlash YModule target revertFromFlash Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code 186 www yoctopuce com 21 High level API Reference module saveToFlash Saves current settings in the nonvolatile memory of the module function sa
157. g current1 sensorAC YCurrent FindCurrent m serialNumber stringByAppendingString current2 else NSLog No module connected check USB cable return i while 1l af Alpa asOndine NSLog No module connected check identification and USB return 17 NSLog Current DC Sf mA sensorDC currentValue NSLog AC Sf mA SensorAC currentValue NSLog press Ctrl C to exit YAPI Sleep 1000 NULL return 0 cable There are only a few really important lines in this example We will look at them in details yocto_api h et yocto_current h These two import files provide access to the functions allowing you to manage Yoctopuce modules yocto api h must always be used yocto current h is necessary to manage modules containing a current sensor such as Yocto Amp _ yRegisterHub The yRegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for When used with the parameter usb it will use the modules locally connected to the computer running the library If the initialization does not succeed this function returns a value different from YAPI SUCCESS and errmsg contains the error message 60 www yoctopuce com 12 Using Yocto Amp with Objective C yFindCurrent The yFindCurrent function allows you to find a current sensor from the serial number of the module on which it resides and from its function name You
158. g mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the most desirable the Yoctopuce library offers another possibility for error handling allowing you to create a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get _state method returns a Y STATE INVALID value a get _currentValue method returns a Y CURRENTVALUE INVALID value and so on In any case the returned value is of the expected type and is not a null pointer which would risk crashing your program At worst if you display the value without testing it it will be outside the expected bounds for the returned value In the case of functions which do not normally return information the return value is YAPI SUCCESS if everything went well and a different error code in case of failure When you work without exceptions you can obtain an error code and an error message ex
159. g the current sensor object 206 www yoctopuce com 21 High level API Reference current get_friendlyName YCurrent current friendlyName Returns a global identifier of the current sensor in the format MODULE_NAME FUNCTION_NAME function get_friendlyName function get_friendlyName function get_friendlyName string get_friendlyName NSString friendlyName string get_friendlyName String get_friendlyName def get_friendlyName The returned string uses the logical names of the module and of the current sensor if they are defined otherwise the serial number of the module and the hardware identifier of the current sensor for exemple MyCustomName relayl1 Returns a string that uniquely identifies the current sensor using logical names ex MyCustomName relay1 On failure throws an exception or returns Y_FRIENDLYNAME_ INVALID www yoctopuce com 207 21 High level API Reference current get_functionDescriptor YCurrent current functionDescriptor Returns a unique identifier of type YFUN_DESCR corresponding to the function function get_functionDescriptor function get_functionDescriptor function get_functionDescriptor YFUN_DESCR get_functionDescriptor YFUN_DESCR functionDescriptor function get_functionDescriptor YFUN_DESCR function get_functionDescriptor As YFUN_DESCR YFUN_DESCR get_functionDescriptor String get_funct
160. gger String func def FindDataLogger func The identifier can be specified using several formats e FunctionLogicalName e ModuleSerialNumber Functionldentifier e ModuleSerialNumber FunctionLogicalName e ModuleLogicalName Functionldentifier e ModuleLogicalName FunctionLogicalName This function does not require that the data logger is online at the time it is invoked The returned object is nevertheless valid Use the method YDat aaLogger isOnline to test if the data logger is indeed online at a given time In case of ambiguity when looking for a data logger by logical name no error is notified the first instance found is returned The search is performed first by hardware name then by logical name Parameters func a string that uniquely characterizes the data logger Returns a YDataLogger object allowing you to drive the data logger 240 www yoctopuce com 21 High level API Reference YDataLogger FirstDataLogger yFirstDataLogger Starts the enumeration of data loggers currently accessible function yFirstDataLogger function FirstDataLogger function yFirstDataLogger YDataLogger yFirstDataLogger YDataLogger yFirstDataLogger function yFirstDataLogger TYDataLogger function yFirstDataLogger As YDataLogger YDataLogger FirstDataLogger YDataLogger FirstDataLogger def FirstDataLogger YDataLogger Use the method YDataLogger nextDataLogger to iterate
161. gs Y_PERSISTENTSETTINGS_ enum persistentSettings pas _ function get_persistentSettings Integer v _ function get_persistentSettings As Integer int get_persistentSettings int get_persistentSettings def get_persistentSettings YModule target get_persistentSettings Returns a value among Y_PERSISTENTSETTINGS_LOADED Y_PERSISTENTSETTINGS_SAVED and Y_PERSISTENTSETTINGS_MODIFIED corresponding to the current state of persistent module settings On failure throws an exception or returns Y_PERSISTENTSETTINGS_INVALID 170 www yoctopuce com 21 High level API Reference module gt get_productld module gt productld Returns the USB device identifier of the module function get_productld function get_productld function get_productld int get_productld int productld function get_productld LongInt function get_productld As Integer int get_productld int get_productld def get_productld YModule target get_productld Returns an integer corresponding to the USB device identifier of the module On failure throws an exception or returns Y_PRODUCTID_INVALID YModule www yoctopuce com 171 21 High level API Reference module get_productName YModule module productName Returns the commercial name of the module as set by the factory function get_productName function get_productName function get_productName
162. h SW Bstecic lyoctosstetic lt Wh e aene lm slept iresd lusb estar Integration as a dynamic library Integration of the Yoctopuce library as a dynamic library allows you to produce an executable smaller than with the two previous methods and to possibly update this library if a patch reveals itself necessary without needing to recompile the source code of the application On the other hand it is an integration mode which systematically requires you to copy the dynamic library on the target machine where the application will run yocto dll for Windows libyocto so 1 0 1 for Mac OS X and Linux To integrate the dynamic Yoctopuce library to your project you must include the Sources directory of the Yoctopuce library into your IncludePath and add the sub directory Binaries corresponding to your operating system into your LibPath Then for you project to build correctly you need to link with your project the dynamic Yoctopuce library and the prerequisite system libraries e For Windows yocto lib e For Mac OS X libyocto lOKit framework and CoreFoundation framework e For Linux libyocto libm libpthread libusb1 0 and libstdc With GCC the command line to compile is simply www yoctopuce com 57 11 Using Yocto Amp with C cise e546 Silverio Slim Siloiwniaseicl Sikuisio il 510 llisictelerrer 58 www yoctopuce com 12 Using Yocto Amp with Objective C Objective C is language of choice
163. he current sensor is currently reachable without raising any error asynchronous version currentload msvValidity Preloads the current sensor cache with a specified validity duration current loadCalibrationPoints rawValues refValues Retrieves error correction data points previously entered using the method calibrateFromPoints current gt load_async msValidity callback context Preloads the current sensor cache with a specified validity duration asynchronous version current nextCurrent Continues the enumeration of current sensors started using yFirstCurrent current registerTimedReportCallback callback Registers the callback function that is invoked on every periodic timed notification current registerValueCallback callback Registers the callback function that is invoked on every change of advertised value current set_highestValue newval Changes the recorded maximal value observed current set_logFrequency newval Changes the datalogger recording frequency for this function current set_logicalName newval Changes the logical name of the current sensor 196 www yoctopuce com 21 High level API Reference current set_lowestValue newval Changes the recorded minimal value observed current set_reportFrequency newval Changes the timed value notification frequency for this function current set_resolution newval Changes the resolution of the measured values current set_userData
164. her than or equal to 1 s the measure represents an instant value When the frequency is below the measure will include distinct minimal maximal and average values based on a sampling performed automatically by the device The following example sets up a timed report callback 4 times per minute for t he first available Current function YCurrent f YCurrent FirstCurrent fase pace porebimequency VAy mn i 1 The value passed as parameter is the same as the value returned by the get_advertisedValue method www yoctopuce com 111 19 Advanced programming f registerTimedReportCallback periodicCallback As for value change callbacks each module function can thus have its own distinct timed report callback Generic callback functions It is sometimes desirable to use the same callback function for various types of sensors e g for a generic sensor graphing application This is possible by defining the callback for an object of class YSensor rather than YCurrent Thus the same callback function will be usable with any subclass of YSensor and in particular with YCurrent With the callback function you can use the method get _unt to get the physical unit of the sensor if you need to display it A complete example You can find a complete example implemented in your favorite programming language in the Examples Prog EventBased directory of the corresponding library 19 2 The data logger Your Yocto Amp is equipp
165. his does not work But if you run a Virtual Hub and you give your command in the form YModule r 127 0 0 1 inventory it works because the command is not executed natively anymore but through the Virtual Hub Note that the Virtual Hub counts as a native application 3 http www yoctopuce com EN virtualhub php www yoctopuce com 31 32 www yoctopuce com 9 Using Yocto Amp with Javascript Javascript is probably not the first language that comes to mind to control hardware but its ease of use is a great advantage with Javascript you only need a text editor and a web browser to realize your first tests At the time of writing the Javascript library functions with any recent browser except Opera It is likely that Opera will end up working with the Yoctopuce library one of these days but it is not the case right now Javascript is one of those languages which do not allow you to directly access the hardware layers of your computer Therefore you need to run the Yoctopuce TCP IP to USB gateway named VirtualHub on the machine on which your modules are connected 9 1 Getting ready Go to the Yoctopuce web site and download the following items e The Javascript programming library e The VirtualHub software for Windows Mac OS X or Linux depending on your OS Decompress the library files in a folder of your choice connect your modules run the VirtualHub software and you are ready to start your first tests Y
166. hronized static int PreregisterHub String url def PreregisterHub url errmsg None This function has the same purpose and same arguments as RegisterHub but does not trigger an error when the selected hub is not available at the time of the function call This makes it possible to register a network hub independently of the current connectivity and to try to contact it only when a device is actively needed 7 Parameters url a string containing either usb callback or the root URL of the hub to monitor errmsg a string passed by reference to receive any error message Returns YAP I SUCCESS when the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 137 21 High level API Reference YAPI RegisterDeviceArrivalCallback YAPI yRegisterDeviceArrivalCallback Register a callback function to be called each time a device is pluged function yRegisterDeviceArrivalCallback arrivalCallback nodejs function RegisterDeviceArrivalCallback arrivalCallback function yRegisterDeviceArrivalCallback arrivalCallback void yRegisterDeviceArrivalCallback yDeviceUpdateCallback arrivalCallback void yRegisterDeviceArrivalCallback yDeviceUpdateCallback arrivalCallback procedure yRegisterDeviceArrivalCallback arrivalCallback yDeviceUpdateFunc procedure yRegisterDeviceArrivalCallback ByVal arrivalCallback As yDeviceUpdateFunc void RegisterDeviceArrivalCall
167. ical names as well as long as you have initialized them Let us imagine a Yocto Amp module with serial number YAMPMK0O1 123456 which you have named MyModule and for which you have given the current function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once YCurrent current YCurrent current YCurrent current YCurrent current YCurrent current yFindCurrent YAMPMK01 123456 current1 yFindCurrent YAMPMK01 123456 MyFunction yFindCurrent MyModule currentl1 yFindCurrent MyModule MyFunction yFindCurrent MyFunction yFindCurrent returns an object which you can then use at will to control the current sensor isOnline The isOnline method of the object returned by yFindCurrent allows you to know if the corresponding module is present and in working order get_currentValue The get _currentValue method of the object returned by yFindCurrent allows you to obtain the current as measured by the sensor The returned value is a number directly representing the value in mA A real example Launch your C environment and open the corresponding sample project provided in the directory Examples Doc GettingStarted Yocto Amp of the Yoctopuce library If you prefer to work with your favorite text editor open the file main cpp and type make to build the example when you are done In this example you will recognize the functions explained above
168. ick on your project and select Add and then Add an existing item A file selection window opens Select the yocto_api cs file and the files corresponding to the functions of the Yoctopuce modules that your project is going to manage If in doubt select all the files You then have the choice between simply adding these files to your project or to add them as links the Add button is in fact a scroll down menu In the first case Visual Studio copies the selected files into your project In the second case Visual Studio simply keeps a link on the original files We recommend you to use links which makes updates of the library much easier 1 http www microsoft com visualstudio en us products 2010 editions visual csharp express www yoctopuce com EN libraries php 3 The sources of this DLL are available in the C API www yoctopuce com 71 14 Using Yocto Amp with C Then add in the same manner the yapi d11 DLL located in the Sources d1l1 directory Then from the Solution Explorer window right click on the DLL select Properties and in the Properties panel set the Copy to output folder to always You are now ready to use your Yoctopuce modules from Visual Studio In order to keep them simple all the examples provided in this documentation are console applications Naturally the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface 14 3 Control of the Curre
169. id name android hardware usb host gt tag in the manifest section lt manifest gt lt uses feature android name android hardware usb host gt lt manifest gt When first accessing a Yoctopuce module Android opens a window to inform the user that the application is going to access the connected module The user can deny or authorize access to the device If the user authorizes the access the application can access the connected device as long as 2 Yoctohubs are a plug and play way to add network connectivity to your Yoctopuce devices more info on hittp www yoctopuce com EN products category extensions and networking 98 www yoctopuce com 18 Using the Yocto Amp with Android it stays connected To enable the Yoctopuce library to correctly manage these authorizations your must provide a pointer on the application context by calling the EnableUSBHost method of the YAPI class before the first USB access This function takes as arguments an object of the android content Context class or of a subclass As the Activity class is a subclass of Context it is simpler to call YAPI EnableUSBHost this inthe method onCreate of your application If the object passed as parameter is not of the correct type a YAPI Exception exception is generated Override public void onCreate Bundle savedInstanceState super onCreate savedinstanceState tey Pass the application Conte
170. if the module is restarted the modifications are lost To memorize them persistently it is necessary to ask the module to save its current configuration in its permanent memory To do so use the YModule saveToFlash method Inversely it is possible to force the module to forget its current settings by using the YModule revertFromFlash method The short example below allows you to modify the logical name of a module package com yoctopuce doc_ examples import android app Activity import android os Bundle import android view View import android widget AdapterView import android widget AdapterView OnItemSelectedListener import android widget ArrayAdapter import android widget EditText import android widget Spinner import android widget TextView import android widget Toast import com yoctopuce YoctoAPI YAPI import com yoctopuce YoctoAPI YAPI Exception import com yoctopuce YoctoAPI YModule public class SaveSettings extends Activity implements OnItemSelectedListener private ArrayAdapter lt String gt aa private YModule module null Override public void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout savesettings Spinner my spin Spinner findViewById R id spinner1 my Spin isetOnleemseleetedinisitener chs aa new ArrayAdapter lt String gt this android R layout simple spinner item aa setDropDownViewResource android R layout
171. if you do not have a text editor use Notepad rather than Microsoft Word 42 www yoctopuce com 10 Using Yocto Amp with PHP lt HTML gt lt HEAD gt lt TITLE gt Hello World lt TITLE gt lt HEAD gt lt BODY gt lt php include yocto api php include yocto icurrent jphp Use explicit error handling rather than exceptions yDisableExceptions Setup the API to use the VirtualHub on local machine if yRegisterHub http 127 0 0 1 4444 Serrmsg YAPI SUCCESS die Cannoe contact Vixrtuallhub on L270 05 INa Sserial GET serial af eserial f yg Check if a specified module is available online Ssensor yFindCurrent S serial currentl1 if Ssensor gt isOnline die Module not connected check serial and USB cable else or use any connected module suitable for the demo Ssensor yFirstCurrent dr GES medi Hesnserh die No module connected check USB cable else serial sensor gt module gt get_serialnumber Print Module to use lt input name serial value Sserial gt lt br gt if Ssensor gt isOnline SsensorDC yFindCurrent serial currentl1 SsensorAC yFindCurrent serial current2 SDC SsensorDC gt get_currentValue SAC sensorAC gt get_currentValue Print Current DC SDC mA Bes SAO mA ore trigger auto refresh after one second Print lt script language javas
172. ime 1000 sec lt br gt html USB current tmodule get_usbCurrent mA lt br gt html logs lt br gt lt pre gt tmodule get_lastlogs lt pre gt lt br gt document getElementById data innerHTML html else document getHElementById msg value Module not connected setTimeout refresh 1000 function beacon state module set beacon state refresh _ gt lt SCRE lt HEAD gt lt BODY onload refresh gt Module to use lt input id serial gt lt input id msg style color red border none readonly gt lt br gt lt span id data gt lt span gt lt BODY gt lt HTML gt Each property xxx of the module can be read thanks to a method of type get _xxxx and properties which are not read only can be modified with the help of the set xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding set _xxx function However this modification is performed only in the random access memory RAM of the module if the module is restarted the modifications are lost To memorize them persistently it is necessary to ask the module to save its current configuration in its permanent memory To do so use the saveToFlash method Inversely it is possible to force the module to forget its current settings by using the r
173. imed value notifications are disabled for this function On failure throws an exception or returns Y_REPORTFREQUENCY_INVALID 218 www yoctopuce com 21 High level API Reference current get_resolution YCurrent current resolution Returns the resolution of the measured values function get_resolution function get_resolution function get_resolution double get_resolution double resolution function get_resolution double function get_resolution As Double pas ee ES double get_resolution double get_resolution def get_resolution YCurrent target get_resolution The resolution corresponds to the numerical precision of the measures which is not always the same as the actual precision of the sensor Returns a floating point number corresponding to the resolution of the measured values On failure throws an exception or returns Y_RESOLUTION_INVALID www yoctopuce com 219 21 High level API Reference current get_unit current unit Returns the measuring unit for the measured value is __ function get_unit node js function get_unit php_ function get_unit string get_unit NSString unit function get_unit string v function get_unit As String string get_unit String get_unit def get_unit Y Current target get_unit Returns a string corresponding to the measuring unit for the measured value On failur
174. in the data logger flash memory reportFrequency Timed value notification frequency or OFF when timed value notifications are disabled for this function calibrationParam Extra calibration parameters for instance to compensate for the effects of an enclosure as an array of 16 bit words resolution Measure resolution i e precision of the numeric representation not necessarily of the measure itself 7 5 DataLogger function interface Yoctopuce sensors include a non volatile memory capable of storing ongoing measured data automatically without requiring a permanent connection to a computer The DataLogger function controls the global parameters of the internal data logger logicalName Character string containing the logical name of the data logger initially empty This attribute can be modified at will by the user Once initialized to an non empty value it can be used to access the data logger directly If two data loggers with the same logical name are used in the same project there is no way to determine which one answers when one tries accessing by logical name The logical name is limited to 19 characters among A Z a z 0 9 and advertisedValue Short character string summarizing the current state of the data logger that is automatically advertised up to the parent hub For a data logger the advertised value is its recording state ON or OFF www yoctopuce com 23 7 Programming general concepts
175. in the directory Examples Doc GettingStarted Yocto Amp of the Yoctopuce library In this example you will recognize the functions explained above but this time used with all the side materials needed to make it work nicely as a small demo import com yoctopuce YoctoAPI public class Demo public static void demo String ac_hardwareid String dc_hardwareid we need to retreive both DC and AC voltage from the device YCurrent sensorDe YCurrent FindCurrent de hardwareid YCurrent sensorAC YCurrent FindCurrent ac hardwareid while true bey I System out oration MICE UH sensor DC erie ierbliera Sine Val uen a gt TaN W System out printin AC SensorAC get currentValue mA System out Prine NA press Crmll bo eL YAPI Sleep 1000 catch YAPI Exception ex System out println Module sensorDC module is not connected return 92 www yoctopuce com 17 Using the Yocto Amp with Java public static void main String args cry setup the API to use local VirtualHub VARI Regis berHub ule Or iG ult i Catch YAPI Exception ex SVSECMAOUE OE Init lin ueannOecOntacia Valet vale o mm 1257 OR Ola uc ex getLocalizedMessage System out printlin Ensure that the VirtualHub application is running System exit 1 Sring Serial ui if args length gt 0 serial args 0 else YCurrent sensor YCurrent FirstCurrent if s
176. in the form SERIAL FUNCTIONID www yoctopuce com 195 21 High level API Reference current get_highestValue Returns the maximal value observed current get_logFrequency Returns the datalogger recording frequency for this function or OFF when measures are not stored in the data logger flash memory current get_logicalName Returns the logical name of the current sensor current get_lowestValue Returns the minimal value observed current get_module Gets the YModule object for the device on which the function is located current get_module_async callback context Gets the YModule object for the device on which the function is located asynchronous version current get_recordedData startTime endTime Retrieves a DataSet object holding historical data for this sensor for a specified time interval current get_reportFrequency Returns the timed value notification frequency or OFF if timed value notifications are disabled for this function current get_resolution Returns the resolution of the measured values current get_unit Returns the measuring unit for the measured value current get_userData Returns the value of the userData attribute as previously stored using method set_userData current isOnline Checks if the current sensor is currently reachable without raising any error current isOnline_async callback context Checks if t
177. int mode def InitAPI mode errmsg None YAPI It is not strictly needed to call yInitAPI as the library is automatically initialized when calling yRegisterHub for the first time When Y_DETECT_NONE is used as detection mode you must explicitly use yRegisterHub to point the API to the VirtualHub on which your devices are connected before trying to access them Parameters mode an integer corresponding to the type of automatic device detection to use Possible values are Y_DETECT_NONE Y_DETECT_USB Y_DETECT_NET and Y_DET ECT ALL errmsg a string passed by reference to receive any error message Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code 136 www yoctopuce com 21 High level API Reference YAPI PreregisterHub YAPI yPreregisterHub Fault tolerant alternative to RegisterHub function yPreregisterHub url errmsg function PreregisterHub url errmsg function yPreregisterHub url amp errmsg YRETCODE yPreregisterHub const string amp url string amp errmsg YRETCODE yPreregisterHub NSString url NSError errmsg function yPreregisterHub url string var errmsg string integer function yPreregisterHub ByVal url As String ByRef errmsg As String As Integer int PreregisterHub string url ref string errmsg sync
178. ion double newval function set_resolution newval double integer function set_resolution ByVal newval As Double As Integer int set_resolution double newval int set_resolution double newval def set_resolution newval YCurrent target set_resolution newval The resolution corresponds to the numerical precision when displaying value It does not change the precision of the measure itself Parameters newval a floating point number corresponding to the resolution of the measured values Returns YAPI_SUCCESS if the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 235 21 High level API Reference current set_userData YCurrent current setUserData Stores a user context provided as argument in the userData attribute of the function function set_userData data function set_userData data function set_userData data void set_userData void data void setUserData void data procedure set_userData data Tobject procedure set_userData ByVal data As Object void set_userData object data void set_userData Object data def set_userData data This attribute is never touched by the API and is at disposal of the caller to store a context Parameters data any kind of object to be stored 236 www yoctopuce com 21 High level API Reference current wait_async YCurrent Waits for all pending asynchr
179. ion receives three arguments the caller specific context object the receiving function object and the error code or YAPT_SUCCESS context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback 226 www yoctopuce com 21 High level API Reference current nextCurrent YCurrent Continues the enumeration of current sensors started using yFirstCurrent function nextCurrent function nextCurrent function nextCurrent YCurrent nextCurrent YCurrent nextCurrent function nextCurrent TYCurrent function nextCurrent As YCurrent YCurrent nextCurrent YCurrent nextCurrent def nextCurrent Returns a pointer to a YCurrent object corresponding to a current sensor currently online or a nul pointer if there are no more current sensors to enumerate www yoctopuce com 227 21 High level API Reference current registerTimedReportCallback YCurrent Registers the callback function that is invoked on every periodic timed notification is__ function registerTimedReportCallback callback node js function registerTimedReportCallback callback php function registerTimedReportCallback callback int registerTimedReportCallback YCurrentTimedReportCallback callback int registerTimedReportCallback YCurrentTimedReportCallback callback pas function registerTimedReportCa
180. ionDescriptor def get_functionDescriptor This identifier can be used to test if two instances of YFunction reference the same physical function on the same physical device Returns an identifier of type YFUN_DESCR If the function has never been contacted the returned value is Y_FUNCTIONDESCRIPTOR_INVALID 208 www yoctopuce com 21 High level API Reference current get_functionld YCurrent current functionld Returns the hardware identifier of the current sensor without reference to the module function get_functionld function get_functionld function get_functionld string get_functionld NSString functionld function get_functionld As String string get_functionld String get_functionld def get_functionld For example relayl Returns a string that identifies the current sensor ex relay1 On failure throws an exception or returns Y_FUNCTIONID_INVALID www yoctopuce com 209 21 High level API Reference current get_hardwareld YCurrent current hardwareld Returns the unique hardware identifier of the current sensor in the form SERIAL FUNCTIONID function get_hardwareld function get_hardwareld function get_hardwareld string get_hardwareld NSString hardwareld function get_hardwareld As String string get_hardwareld String get_hardwareld def get_hardwareld The unique hardware identifier is compose
181. is known The callback function receives three arguments the caller specific context object the receiving function object and the requested YModule object context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback www yoctopuce com 257 21 High level API Reference datalogger get_recording YDataLogger datalogger recording Returns the current activation state of the data logger function get_recording function get_recording function get_recording cpp _ Y_RECORDING_enum get_recording Y_RECORDING_enum recording pas_ function get_recording Integer __vb__ function get_recording As Integer int get_recording int get_recording def get_recording Y DataLogger target get_recording Returns either Y_RECORDING_OFF or Y_RECORDING_ON according to the current activation state of the data logger On failure throws an exception or returns Y_RECORDING_INVALID 258 www yoctopuce com 21 High level API Reference datalogger get_timeUTC datalogger timeUTC Returns the Unix timestamp for current UTC time if known function get_timeUTC function get_timeUTC function get_timeUTC s64 get_timeUTC s64 timeUTC function get_timeUTC int64 function get_timeUTC As Long long get_timeUTC long get_timeUTC def get_timeUTC YDataLogger target
182. itecture before any other call to the library Parameters arch A string containing the architecture to use Possibles value are armhf armel 1386 x86 64 32570 TO4DIET Returns nothing On failure throws an exception www yoctopuce com 143 21 High level API Reference YAPI SetDelegate YAPI ySetDelegate Objective C only Register an object that must follow the procol YDeviceHotPlug void ySetDelegate id object The methodes yDeviceArrival and yDeviceRemoval will be invoked while yUpdateDeviceList is running You will have to call this function on a regular basis Parameters object an object that must follow the procol YAP IDelegate or nil 144 www yoctopuce com 21 High level API Reference YAPI SetTimeout YAPI ySetTimeout Invoke the specified callback function after a given timeout function ySetTimeout callback ms_timeout arguments function SetTimeout callback ms_timeout arguments This function behaves more or less like Javascript set Timeout but during the waiting time it will call yHandleEvents and yUpdateDeviceList periodically in order to keep the API up to date with current devices Parameters callback the function to call after the timeout occurs On Microsoft Internet Explorer the callback must be provided as a string to be evaluated ms_timeout an integer corresponding to the duration of the ti
183. k callback def registerValueCallback callback The callback is invoked only during the execution of ySleep or yHandleEvents This provides control over the time when the callback is triggered For good responsiveness remember to call one of these two functions periodically To unregister a callback pass a null pointer as argument Parameters callback the callback function to call or a null pointer The callback function should take two arguments the function object of which the value has changed and the character string describing the new advertised value www yoctopuce com 229 21 High level API Reference current set_highestValue current setHighestValue Changes the recorded maximal value observed function set_highestValue newval function set_highestValue newval function set_highestValue newval int set_highestValue double newval int setHighestValue double newval function set_highestValue newval double integer v _ function set_highestValue ByVal newval As Double As Integer int set_highestValue double newval int set_highestValue double newval def set_highestValue newval YCurrent target set_highestValue newval Parameters newval a floating point number corresponding to the recorded maximal value observed Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code YCurrent 230 www yoctopuce com
184. l functions yFindCurrent func Retrieves a current sensor for a given identifier yFirstCurrent Starts the enumeration of current sensors currently accessible YCurrent methods current calibrateFromPoints rawValues refValues Configures error correction data points in particular to compensate for a possible perturbation of the measure caused by an enclosure current describe Returns a short text that describes the current sensor in the form TYPE NAME SERIAL FUNCTIONID T current get_advertisedValue Returns the current value of the current sensor no more than 6 characters current get_currentRawValue Returns the uncalibrated unrounded raw value returned by the sensor current get_currentValue Returns the current measured value current get_errorMessage Returns the error message of the latest error with the current sensor current get_errorType Returns the numerical error code of the latest error with the current sensor current get_friendlyName Returns a global identifier of the current sensor in the format MODULE_NAME FUNCTION_NAME current get_functionDescriptor Returns a unique identifier of type YF UN_DESCR corresponding to the function current get_functionld Returns the hardware identifier of the current sensor without reference to the module current get_hardwareld Returns the unique hardware identifier of the current sensor
185. latile memory To do so use the saveToFlash command Inversely it is possible to force the module to forget its current settings by using the revert FromFlash method For example YModule YAMPMKO01 12346 set_logicalName MonPremierModule YModule YAMPMKO01 12346 saveToFlash Note that you can do the same thing in a single command with the s option YModule s YAMPMK01 12346 set _logicalName MonPremierModule Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop 8 5 Limitations The command line API has the same limitation than the other APIs there can be only one application at a given time which can access the modules natively By default the command line API works in native mode You can easily work around this limitation by using a Virtual Hub run the VirtualHub on the concerned machine and use the executables of the command line API with the r option For example if you use YModule inventory you obtain a list of the modules connected by USB using a native access If another command which accesses the modules natively is already running t
186. le get_endTimeUTC double get_endTimeUTC def get_endTimeUTC When the recording rate is higher then 1 sample per second the timestamp may have a fractional part Returns an floating point number corresponding to the number of seconds between the Jan 1 1970 UTC and the end of this measure 288 www yoctopuce com 21 High level API Reference measure get_maxValue YMeasure measure maxValue Returns the largest value observed during the time interval covered by this measure function get_maxValue function get_maxValue function get_maxValue double get_maxValue double maxValue function get_maxValue double function get_maxValue As Double double get_maxValue double get_maxValue def get_maxValue Returns a floating point number corresponding to the largest value observed www yoctopuce com 289 21 High level API Reference measure gt get_minValue YMeasure measure minValue Returns the smallest value observed during the time interval covered by this measure function get_minValue function get_minValue function get_minValue double get_minValue double minValue function get_minValue double v _ function get_minValue As Double double get_minValue double get_minValue def get_minValue Returns a floating point number corresponding to the smallest value observed 290 www yoctopuce com
187. lement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to i1sOnline and which could crash the software The only way to prevent this is to implement one of the two error handling techniques described below The method recommended by most programming languages for unpredictable error handling is the use of exceptions By default it is the behavior of the Yoctopuce library If an error happens while you try to access a module the library throws an exception In this case there are three possibilities e If your code catches the exception and handles it everything goes well e If your program is running in debu
188. lic static double CustomInterpolation3Points double rawValue int calibType int parameters double beforeValues double afterValues double result the value to be corrected is rawValue calibration points are in beforeValues and afterValues result interpolation of your choice return result YAPI RegisterCalibrationHandler 3 CustomInterpolation3Points Note that these interpolation callbacks are global and not specific to each function Thus each time someone requests a value from a module which contains in its flash memory the correct number of calibration points the corresponding callback is called to correct the value before returning it enabling thus a perfectly transparent measure correction www yoctopuce com 117 118 www yoctopuce com 20 Using with unsupported languages Yoctopuce modules can be driven from most common programming languages New languages are regularly added depending on the interest expressed by Yoctopuce product users Nevertheless some languages are not and will never be supported by Yoctopuce There can be several reasons for this compilers which are not available anymore unadapted environments etc However there are alternative methods to access Yoctopuce modules from an unsupported programming language 20 1 Command line The easiest method to drive Yoctopuce modules from an unsupported programming language is to use the command line API through system calls
189. lidity of the loaded function parameters in milliseconds callback callback function that is invoked when the result is known The callback function receives three arguments the caller specific context object the receiving function object and the error code or YAPT_SUCCESS context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback 264 www yoctopuce com 21 High level API Reference datalogger nextDataLogger YDataLogger Continues the enumeration of data loggers started using yFirstDataLogger function nextDataLogger function nextDataLogger function nextDataLogger YDataLogger nextDataLogger YDataLogger nextDataLogger function nextDataLogger TYDataLogger function nextDataLogger As YDataLogger YDataLogger nextDataLogger YDataLogger nextDataLogger def nextDataLogger Returns a pointer toa YDataLogger object corresponding to a data logger currently online or a nul pointer if there are no more data loggers to enumerate www yoctopuce com 265 21 High level API Reference datalogger registerValueCallback YDataLogger Registers the callback function that is invoked on every change of advertised value is__ function registerValueCallback callback node js function registerValueCallback callback php_ function registerValueCallback callback i
190. llback callback TYCurrentTimedReportCallback LongInt vb function registerTimedReportCallback As Integer int registerTimedReportCallback TimedReportCallback callback int registerTimedReportCallback TimedReportCallback callback def registerTimedReportCallback callback The callback is invoked only during the execution of ySleep or yHandleEvents This provides control over the time when the callback is triggered For good responsiveness remember to call one of these two functions periodically To unregister a callback pass a null pointer as argument Parameters callback the callback function to call or a null pointer The callback function should take two arguments the function object of which the value has changed and an YMeasure object describing the new advertised value 228 www yoctopuce com 21 High level API Reference current registerValueCallback YCurrent Registers the callback function that is invoked on every change of advertised value function registerValueCallback callback function registerValueCallback callback function registerValueCallback callback int registerValueCallback YCurrentValueCallback callback int registerValueCallback YCurrentValueCallback callback function registerValueCallback callback TYCurrentValueCallback LongInt function registerValueCallback As Integer int registerValueCallback ValueCallback callback int registerValueCallback UpdateCallbac
191. lues This chapter does not repeat the programming concepts described earlier in order to stay as concise as possible In case of doubt do not hesitate to go back to the chapter describing in details all configurable attributes www yoctopuce com 125 21 High level API Reference 21 1 General functions These general functions should be used to initialize and configure the Yoctopuce library In most cases a simple call to function yRegisterHub should be enough The module specific functions yFind or yFirst should then be used to retrieve an object that provides interaction with the module In order to use the functions described here you should include lt script type text javascript src yocto_api js gt lt script gt var yoctolib require yoctolib var YAPI yoctolib YAPI var YModule yoctolib YModule require_once yocto_api php include yocto_api h import yocto_api h uses yocto_api yocto_api vb yocto_api cs import com yoctopuce YoctoAPI YModule from yocto_api import Global functions yCheckLogicalName name Checks if a given string is valid as logical name for a module or a function yDisableExceptions Disables the use of exceptions to report runtime errors yEnableExceptions Re enables the use of exceptions for runtime error handling yEnableUSBHost osContext This function is used only on Android yFreeAPI Frees dynamically allocated memory blocks u
192. ly it is possible to force the module to forget its current settings by using the revertFromFlash method The short example below allows you to modify the logical name of a module 68 www yoctopuce com 13 Using Yocto Amp with Visual Basic NET Module Modulel Sub usage Console WriteLine usage demo lt serial or logical name gt lt new logical name gt End End Sub Sub Main Dim argv As String System Environment GetCommandLineArgs Dim errmsg As String Dim newname As String Dim m As YModule If argv Length lt gt 3 Then usage REM Setup the API to use local USB devices If yRegisterHub usb errmsg lt gt YAPI_SUCCESS Then Console WriteLine RegisterHub error errmsg End End If m yFindModule argv 1 REM use serial or logical name If m isOnline Then newname argv 2 If Not yCheckLogicalName newname Then Console WriteLine Invalid name newname End End If m set_logicalName newname m saveToFlash REM do not forget this Console Write Module serial im get serial Numbex Console Write name m get_logicalName Else Console Write not connected check identification and USB cable End Lf End Sub End Module Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employ
193. ly the Virtual Hub software serves as an abstraction layer for languages which cannot access the hardware layers of your computer However it also offers a succinct interface to configure your modules and to test their basic functions You access this interface with a simple web browser Start the Virtual Hub software in a command line open your preferred web browser and enter the URL http 127 0 0 1 4444 The list of the Yoctopuce modules connected to your computer is displayed Serial Logical Name Description Action V 30 VirtualHub configure view log file Yocto Amp configure view log file beacon e Show device functions Module list as displayed in your web bowser 5 1 Localization You can then physically localize each of the displayed modules by clicking on the beacon button This puts the Yocto led of the corresponding module in Yocto beacon mode It starts flashing which allows you to easily localize it The second effect is to display a little blue circle on the screen You obtain the same behavior when pressing the Yocto button of the module 5 2 Test of the module The first item to check is that your module is working well click on the serial number corresponding to your module This displays a window summarizing the properties of your Yocto Amp 1 www yoctopuce com EN virtualhub php 2 The interface was tested on FireFox 3 IE 6 Safari and Chrome It does not work with Opera www yoc
194. m 87 16 Using the Yocto Amp with Python print serail A Gh WoC Serie Minoa O print logical name m get_logicalName printi umi noS TEN W sitm m ger luminosity ONN if m get_beacon YModule BEACON ON print beacon ON ilsice print beacon OFF print upTime WS Sir m get upiame 000 seo print USB current Wop ees Cee eaen a ive print logs n m get_lastLogs elise print sys argyll iiit met connected cheek wdentitilcation and USB cabile Each property xxx of the module can be read thanks to a method of type YModule get xxxx and properties which are not read only can be modified with the help of the YModule set xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding YModule set xxx function However this modification is performed only in the random access memory RAM of the module if the module is restarted the modifications are lost To memorize them persistently it is necessary to ask the module to save its current configuration in its permanent memory To do so use the YModule saveToFlash method Inversely it is possible to force the module to forget its current settings by using the YModule revertFromFlash method The short example below allows you to modify the logical name of a module usr bin python jp
195. mally return information the return value is YAPI_ SUCCESS if everything went well and a different error code in case of failure When you work without exceptions you can obtain an error code and an error message explaining the source of the error You can request them from the object which returned the error calling the errType and errMessage methods Their returned values contain the same information as in the exceptions when they are active 64 www yoctopuce com 13 Using Yocto Amp with Visual Basic NET VisualBasic has long been the most favored entrance path to the Microsoft world Therefore we had to provide our library for this language even if the new trend is shifting to C All the examples and the project models are tested with Microsoft VisualBasic 2010 Express freely available on the Microsoft web site 13 1 Installation Download the Visual Basic Yoctopuce library from the Yoctopuce web site There is no setup program simply copy the content of the zip file into the directory of your choice You mostly need the content of the Sources directory The other directories contain the documentation and a few sample programs All sample projects are Visual Basic 2010 projects if you are using a previous version you may have to recreate the projects structure from scratch 13 2 Using the Yoctopuce API in a Visual Basic project The Visual Basic NET Yoctopuce library is com
196. meout in milliseconds arguments additional arguments to be passed to the callback function can be provided if needed not supported on Microsoft Internet Explorer Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 145 21 High level API Reference YAPI Sleep YAPI ySleep Pauses the execution flow for a specified duration function ySleep ms_duration errmsg function Sleep ms_duration errmsg function ySleep ms_duration amp errmsg YRETCODE ySleep unsigned ms_duration string amp errmsg YRETCODE ySleep unsigned ms_duration NSError errmsg function ySleep ms_duration integer var errmsg string integer function ySleep ByVal ms_duration As Integer ByRef errmsg As String As Integer int Sleep int ms_duration ref string errmsg int Sleep long ms_duration def Sleep ms_duration errmsg None This function implements a passive waiting loop meaning that it does not consume CPU cycles significatively The processor is left available for other threads and processes During the pause the library nevertheless reads from time to time information from the Yoctopuce modules by calling yHandleEvents in order to stay up to date This function may signal an error in case there is a communication problem while contacting a module Parameters ms_duration an integer corresponding to the duration of the pause
197. ming language in the Examples Prog EventBased directory of the corresponding library Be aware that in most programming languages callbacks must be global procedures and not methods If you wish for the callback to call the method of an object define your callback as a global procedure which then calls your method Detecting a modification in the value of a sensor The Yoctopuce API also provides a callback system allowing you to be notified automatically with the value of any sensor either when the value has changed in a significant way or periodically at a preset frequency The code necessary to do so is rather similar to the code used to detect when a new module has been connected This technique is useful in particular if you want to detect very quick value changes within a few milliseconds as it is much more efficient than reading repeatedly the sensor value and therefore gives better performances Calliback invocation To enable a better control value change callbacks are only called when the YAPI Sleep and YAPI HandleEvents functions are running Therefore you must call one of these functions at a regular interval either from a timer or from a parallel thread while true inactive waiting loop allowing you to trigger value change callbacks YAPI Sleep 500 ref errmsg In programming environments where only the interface thread is allowed to interact with the user it is often appropriate to call
198. mmon functionalities USB connector Yoctopuce modules all come with a micro B USB socket The corresponding cables are not the most common but the sockets are the smallest available Warning the USB connector is simply soldered in surface and can be pulled out if the USB plug acts as a lever In this case if the tracks stayed in position the connector can be soldered back with a good iron and using flux to avoid bridges Alternatively you can solder a USB cable directly in the 1 27mm spaced holes near the connector Yocto button The Yocto button has two functionalities First it can activate the Yocto beacon mode see below under Yocto led Second if you plug in a Yocto module while keeping this button pressed you can then reprogram its firmware with a new version Note that there is a simpler Ul based method to update the firmware but this one works even in case of severely damaged firmware Yocto led Normally the Yocto led is used to indicate that the module is working smoothly The Yocto led then emits a low blue light which varies slowly mimicking breathing The Yocto led stops breathing when the module is not communicating any more as for instance when powered by a USB hub which is disconnected from any active computer www yoctopuce com 2 Presentation When you press the Yocto button the Yocto led switches to Yocto beacon mode It starts flashing faster with a stronger light in order to facilitate the localiz
199. module connected end alga sensor yFindCurrent target currentl m nil sensorDC nil sensorAC nil we need to retreive both DC and AC voltage from the device If sensor isOnline Then begin MJ sensor gee smodulle i sensorDC yFindCurrent m get_serialNumber sensorAC yFindCurrent m get_serialNumber end else Die Module not connected ff Lents pori Pepeo If Not m isOnline Then Die Module not connected Write DE T Priloattostue sensonDe ger current Valuel Write UAC Piloathostm sensonAG germcumnentValiuel Writeln presa T trl OREO ERE ySleep 1000 errmsg until false end Wa eumicen tilat i current 25 Sa There are only a few really important lines in this sample example We will look at them in details 80 www yoctopuce com 15 Using Yocto Amp with Delphi yocto_api and yocto_current These two units provide access to the functions allowing you to manage Yoctopuce modules yocto_ api must always be used yocto_ current is necessary to manage modules containing a current sensor such as Yocto Amp yRegisterHub The yRegisterHub function initializes the Yoctopuce API and specifies where the modules should be looked for When used with the parameter usb it will use the modules locally connected to the computer running the library If the initialization does not succeed this function returns a value different from YAPI SUCCESS and errmsg contains the er
200. most desirable the Yoctopuce library offers another possibility for error handling allowing you to create a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get _state method returns a Y STATE INVALID value a get _currentValue method returns a Y CURRENTVALUE INVALID value and so on In any case the returned value is of the expected type and is not a null pointer which would risk crashing your program At worst if you display the value without testing it it will be outside the expected bounds for the returned value In the case of functions which do not normally return information the return value is YAPI_ SUCCESS if everything went well and a different error code in case of failure When you work without exceptions you can obtain an error code and an error message explaining the source of the error You can request them from the object which returned the error calling the errType and errMessage methods Their returned values contain the same information as in the exceptions when they a
201. mp with Android To tell the truth Android is not a programming language it is an operating system developed by Google for mobile appliances such as smart phones and tablets But it so happens that under Android everything is programmed with the same programming language Java Nevertheless the programming paradigms and the possibilities to access the hardware are slightly different from classical Java and this justifies a separate chapter on Android programming 18 1 Native access and VirtualHub In the opposite to the classical Java API the Java for Android API can access USB modules natively However as there is no VirtualHub running under Android it is not possible to remotely control Yoctopuce modules connected to a machine under Android Naturally the Java for Android API remains perfectly able to connect itself to a VirtualHub running on another OS 18 2 Getting ready Go to the Yoctopuce web site and download the Java for Android programming library The library is available as source files and also as a jar file Connect your modules decompress the library files in the directory of your choice and configure your Android programming environment so that it can find them To keep them simple all the examples provided in this documentation are snippets of Android applications You must integrate them in your own Android applications to make them work However your can find complete applications in the examples provided with th
202. mples Doc GettingStarted Yocto Amp of the Yoctopuce library import lt Foundation Foundation h gt import yocto_api h import yocto_current h static void usage void NSLog usage demo lt serial_ number gt NSLog demo lt logical_ name gt NSLog demo any usevanyaduscovered idevaice il exit dhi int mann Ime drogei const char aarov 1 1 www yoctopuce com EN libraries php 2 www yoctopuce com EN article new objective c library for mac os x www yoctopuce com 59 12 Using Yocto Amp with Objective C NSE EEO error YCurrent sensor YCurrent sensorAC YCurrent sensorDC YModule cml age ee lt Bi ff usage autoreleasepool NSString target NSString stringWithUTF8String argv 1 Setup the API to use local USB devices if YAPI RegisterHub usb amp error YAPI SUCCESS NSLog RegisterHub error error localizedDescription return 1 if target isEqualToString any retreive any current sensor can be AC or DC sensot YCu urrent FirstCu urrenti if sensor NULL NSLog No module connected check USB cable return 1 else sensor YCurrent FindCurrent target stringByAppendingString current1 we need to retreive both DC and AC current from the device if sensor isOnline m sensor module sensorDC YCurrent FindCurrent m serialNumber stringByAppendingStrin
203. n a very small space you can connect them directly to a micro USB hub Yoctopuce builds a USB hub particularly small for this purpose down to 20mmx36mm on which you can directly solder a USB cable instead of using a USB plug For more details see the micro USB hub information sheet YoctoHub Ethernet and YoctoHub Wireless You can add network connectivity to your Yocto Amp thanks to the YoctoHub Ethernet and the YoctoHub Wireless The YoctoHub Ethernet provides Ethernet connectivity and the YoctoHub Wireless provides WiFi connectivity Both can drive up to three devices and behave exactly like a regular computer running a Virtua Hub Enclosures Your Yocto Amp has been designed to be installed as is in your project Nevertheless Yoctopuce sells enclosures specifically designed for Yoctopuce devices These enclosures have removable mounting brackets and magnets allowing them to stick on ferromagnetic surfaces More details are available on the Yoctopuce web site The suggested enclosure model for your Yocto Amp is the YoctoBox Long Thick Black Vents You can install your Yocto Amp in an optional enclosure 4 http www yoctopuce com EN products category enclosures www yoctopuce com 3 www yoctopuce com 2 Presentation og ee 1 Micro B USB socket 4 Measure resistance 2 Yocto button 5 Measure input negative 3 Yocto led 6 Measure input positive 2 1 Common elements All Yocto modules share a number of co
204. name newname Toast LENGTH_ LONG show Ter UCN module set_logicalName newname module saveToFlash do not forget this edite SerTen GN Catch YAPT Exception ex ex print obdekiracen i DisplayModuleInfo www yoctopuce com 105 18 Using the Yocto Amp with Android Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the YModule saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the YModule yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not null Below a short example listing the connected modules package com yoctopuce doc_ examples import android app Activity import android os Bundle import android view View import android widget LinearLayout import android widget TextView import com yoctopuce YoctoAPI YAPI import com yoctopuce YoctoAPI YAPI Exception import com yoctopuce YoctoAPI YModule publi
205. nce initialized to an non empty value it can be used to access a given module If two modules with the same logical name are in the same project there is no way to determine which one answers when one tries accessing by logical name The logical name is limited to 19 characters among A Z a z 0 9 and productlid USB device identifier of the module preprogrammed to 31 at the factory productRelease Release number of the module hardware preprogrammed at the factory firmwareRelease Release version of the embedded firmware changes each time the embedded software is updated persistentSettings State of persistent module settings loaded from flash memory modified by the user or saved to flash memory luminosity Lighting strength of the informative leds e g the Yocto Led contained in the module It is an integer value which varies between 0 leds turned off and 100 maximum led intensity The default value is 50 To change the strength of the module leds or to turn them off completely you only need to change this value beacon Activity of the localization beacon of the module upTime Time elapsed since the last time the module was powered on usbCurrent Current consumed by the module on the USB bus in milli amps rebootCountdown Countdown to use for triggering a reboot of the module usbBandwidth Number of USB interfaces used by the device If this parameter is set to DOUBLE the device can send twice as much
206. nction set_logicalName newval function set_logicalName newval function set_logicalName newval int set_logicalName const string amp newval int setLogicalName NSString newval function set_logicalName newval string integer function set_logicalName ByVal newval As String As Integer int set_logicalName string newval int set_logicalName String newval def set_logicalName newval YModule target set_logicalName newval You can use yCheckLogicalName prior to this call to make sure that your parameter is valid Remember to call the saveToF lash method of the module if the modification must be kept Parameters newval a string corresponding to the logical name of the module Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 189 21 High level API Reference module set_luminosity YModule module setLuminosity Changes the luminosity of the module informative leds function set_luminosity newval function set_luminosity newval function set_luminosity newval int set_luminosity int newval int setLuminosity int newval function set_luminosity newval LongInt integer v function set_luminosity ByVal newval As Integer As Integer int set_luminosity int newval int set_luminosity int newval def set_luminosity newval YModule target set_luminosity newval The parameter is a
207. nctions yFindDataLogger func Retrieves a data logger for a given identifier yFirstDataLogger Starts the enumeration of data loggers currently accessible YDataLogger methods datalogger describe Returns a short text that describes the data logger in the form TYPE NAME SERIAL FUNCTIONID datalogger forgetAllDataStreams Clears the data logger memory and discards all recorded data streams datalogger get_advertisedValue Returns the current value of the data logger no more than 6 characters datalogger get_autoStart Returns the default activation state of the data logger on power up datalogger get_currentRunIndex Returns the current run number corresponding to the number of times the module was powered on with the dataLogger enabled at some point datalogger get_dataSets Returns a list of YDataSet objects that can be used to retrieve all measures stored by the data logger datalogger get_dataStreams v Builds a list of all data streams hold by the data logger legacy method datalogger get_errorMessage Returns the error message of the latest error with the data logger datalogger get_errorType Returns the numerical error code of the latest error with the data logger datalogger get_friendlyName Returns a global identifier of the data logger in the format MODULE_NAME FUNCT ION_NAME datalogger get_functionDescriptor Returns a unique identifier of type YF UN_DESCR corresponding t
208. nd restart your system udev rules to allow write access to all users of yoctogroup for Yoctopuce USB devices SUBSYSTEM usb ATTR idVendor 24e0 MODE 0664 GROUP yoctogroup 22 2 ARM Platforms HF and EL There are two main flavors of executable on ARM HF Hard Float binaries and EL EABI Little Endian binaries These two families are not compatible at all The compatibility of a given ARM platform with of one of these two families depends on the hardware and on the OS build ArmHL and ArmEL compatibility problems are quite difficult to detect Most of the time the OS itself is unable to make a difference between an HF and an EL executable and will return meaningless messages when you try to use the wrong type of binary All pre compiled Yoctopuce binaries are provided in both formats as two separate ArmHF et ArmEL executables If you do not know what family your ARM platform belongs to just try one executable from each family 294 www yoctopuce com 23 Characteristics You can find below a summary of the main technical characteristics of your Yocto Amp module Width Length Weight USB connector Max Current continuous Max Current peak Refresh rate Accuracy AC Accuracy DC Sensitivity Supported Operating Systems Drivers API SDK Libraries USB TCP API SDK Libraries TCP only RoHS USB Vendor ID USB Device ID Suggested enclosure 20 mm 56 mm 8g micro B 10A 17A 10
209. neneeeesaneceenaeeceesansenensaeensnenenessenenensas 150 21 3 Current function interlace aiite neediest Mie a a Rea Gated ena Ailsa ees 195 21 4 DataLogger function interface ooo eect e cette eee eeeeeeeeeaee ee eeaeeeesaaeeeeeaaeeeseeeeeeseeeeeseeeeees 238 21 5 Recorded data SCQUCINCE ee ceceeccceeeseeeeeeeeeeeeneeeeeeseeeeeeesaeeeseseaneseaaaeeneaaaneneenneeeeneneeees 273 21 6 Me asured Value sa Teppi aee e eaea a Ei a a a a ioei oaa aae 286 22 Troubleshooting sassssssannssseserrisseerrtsssntttssttttttstritttnnrnnttnnrrnennrttntnnrttenrrnent rrene 293 22 1 Linuxand USB eren e a a a A a a a E ieee 293 22 22 ARM Platt rms AF and EL er ea ere a a r a a ea eve aane aaea 294 23 ClhatacteristicS eens i enan an a i i et cee 295 BIU priAt 4 00 04 AEA EEE E ona E E E nine widen 297 1 Introduction The Yocto Amp module is a 56x20mm module which allows you to measure by USB the current going through an electrical wire a tool commonly called an ammeter The Yocto Amp is able to measure direct current as well as alternating current Its precision is of 2 mA 1 for direct current and 5 mA 3 for alternating current An important specificity of this module is that it is an isolated ammeter the part measuring current is electrically isolated from the USB part This allows you for instance to measure the current of the mains without risking to destroy your computer The Yocto Amp module Yoctopuce thanks you for
210. nents of the Yocto Amp module find themselves directly on the measured voltage Make sure never to touch them when the module is powered on These components must never be in contact with a conductive component of your project look out for metallic enclosures Even more importantly make sure that your project end user can never touch these components even accidentally i DA P o o i ini Z 7 7 Potentially dangerous components of the Yocto Amp module www yoctopuce com www yoctopuce com 4 Direct current vs alternating current The Yocto Amp module is able to measure a direct current as well as an alternating current You can typically measure a direct current on the terminals of a battery or at the output of a stabilized power supply for electronic equipment It is supposed to stay relatively stable over time Direct current stable over time An alternating current is a current which periodically varies over time The most typical example is the current of the mains A dynamo such as the one on your bike produces alternating current as well Alternating current it varies periodically Note that an alternating current is not necessarily symmetrical One can then describe it as the sum of a direct current and of an alternating symmetrical current www yoctopuce com 4 Direct current vs alternating current Asymmetrical alternating current It s the sum of a direct current and an al
211. newval string integer function set_logicalName ByVal newval As String As Integer int set_logicalName string newval int set_logicalName String newval def set_logicalName newval YCurrent target set_logicalName newval You can use yCheckLogicalName prior to this call to make sure that your parameter is valid Remember to call the saveToFlash method of the module if the modification must be kept Parameters newval a string corresponding to the logical name of the current sensor Returns YAPI_SUCCESS if the call succeeds On failure throws an exception or returns a negative error code 232 www yoctopuce com 21 High level API Reference current set_lowestValue current setLowestValue Changes the recorded minimal value observed function set_lowestValue newval function set_lowestValue newval function set_lowestValue newval int set_lowestValue double newval int setLowestValue double newval function set_lowestValue newval double integer function set_lowestValue ByVal newval As Double As Integer int set_lowestValue double newval int set_lowestValue double newval def set_lowestValue newval YCurrent target set_lowestValue newval Parameters newval a floating point number corresponding to the recorded minimal value observed Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code YCurrent www
212. ng timeFmt MG et averageValue Sensor gee mune yl I You will find a complete example demonstrating how to retrieve data from the logger for each programming language directly in the Yoctopuce library The example can be found in directory Examples Prog DataLogger Timestamp As the Yocto Amp does not have a battery it cannot guess alone the current time when powered on Nevertheless the Yocto Amp will automatically try to adjust its real time reference using the host to which it is connected in order to properly attach a timestamp to each measure in the datalogger e When the Yocto Amp is connected to a computer running either the VirtualHub or any application using the Yoctopuce library it will automatically receive the time from this computer e When the Yocto Amp is connected to a YoctoHub Ethernet it will get the time that the YoctoHub has obtained from the network using a server from pool ntp org When the Yocto Amp is connected to a YoctoHub Wireless it will get the time provided by the YoctoHub based on its internal battery powered real time clock which was itself configured either from the network or from a computer e When the Yocto Amp is connected to an Android mobile device it will get the time from the mobile device as long as an app using the Yoctopuce library is launched When none of these conditions applies for instance if the module is simply connected to an USB charger the Yocto Amp will do its best
213. ns a negative error code 268 www yoctopuce com 21 High level API Reference datalogger set_recording datalogger setRecording Changes the activation state of the data logger to start stop recording data function set_recording newval function set_recording newval function set_recording newval int set_recording Y_RECORDING_enum newval int setRecording Y_RECORDING_enum newval function set_recording newval Integer integer function set_recording ByVal newval As Integer As Integer int set_recording int newval int set_recording int newval def set_recording newval YDataLogger target set_recording newval Parameters data logger to start stop recording data Returns YAPI_SUCCESS if the call succeeds On failure throws an exception or returns a negative error code YDataLogger newval either Y_RECORDING_OFF or Y_RECORDING_ON according to the activation state of the www yoctopuce com 269 21 High level API Reference datalogger set_timeUTC YDataLogger datalogger setTimeUTC Changes the current UTC time reference used for recorded data function set_timeUTC newval function set_timeUTC newval function set_timeUTC newval int set_timeUTC s64 newval int setTimeUTC s64 newval function set_timeUTC newval int64 integer vo function set_timeUTC ByVal newval As Long As Integer int set_timeUTC long newval int set_timeUTC
214. nsor is None die No module connected else sensor YCurrent FindCurrent target currentl we need to retreive both DC and AC voltage from the device if sensor isOnline m sensor get_module SsensorDe VCurrent Find umrentl m eraser cel Number ps V CuEmentds SsensorAe gt YCurcent FimdCurrent m gersericalNumbern current2 algas die Module not connected let s poll while True if not m isOnline die Modulle not connected reste VINES U sh ice SemsouDe GSE Currane VeeS ae ues 0 ap N VAG Siu SensorAGr ger currentValwel i jt man 4 print press Cer Cyto texan i YAPI Sleep 1000 errmsg 16 4 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon usr bin python coding utf 8 import os sys trom yoctol api importi def usage sys exit usage demo lt serial or logical name gt ON OFF errmsg YRefParam if YAPI RegisterHub usb errmsg YAPI SUCCESS sys exit RegisterHub error str errmsg if len sys argv lt 2 usage m YModule FindModule sys argv 1 use serial or logical name if m isOnline dee demlenen ecew 2a if sys argv 2 upper ON m set_beacon YModule BEACON ON LE SySmatgvy 2 uppen VOPR Sinise bcaconi YMocdulle BEACON MOEE www yoctopuce co
215. nt function A few lines of code are enough to use a Yocto Amp Here is the skeleton of a C code snipplet to use the Current function ko oul string errmsg YCurrent current Get access to your device connected locally on USB for instance YAPI RegisterHub usb errmsg current YCurrent FindCurrent YAMPMK01 123456 current1 Hot plug is easy just check that the device is online if current isOnline Use current get_currentValue Let s look at these lines in more details YAPI RegisterHub The YAPI RegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for When used with the parameter usb it will use the modules locally connected to the computer running the library If the initialization does not succeed this function returns a value different from YAPI SUCCESS and errmsg contains the error message YCurrent FindCurrent The YCurrent FindCurrent function allows you to find a current sensor from the serial number of the module on which it resides and from its function name You can use logical names as well as long as you have initialized them Let us imagine a Yocto Amp module with serial number YAMPMK01 123456 which you have named MyModule and for which you have given the current function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once current YCurrent FindCur
216. nt function Launch your Delphi environment copy the yapi dll DLL in a directory create a new console application in the same directory and copy paste the piece of code below program helloworld SAPPTYPE CONSOLE uses Sveulels Windows yocto api ppsiee errara he 1 Actually Borland provided free versions for personal use of Delphi 2006 and 2007 Look for them on the Internet you may still be able to download them 2 Delphi libraries are regularly tested with Delphi 5 and Delphi XE2 www yoctopuce com EN libraries php 4 Use the Tools Environment options menu www yoctopuce com 79 15 Using Yocto Amp with Delphi Procedure usage var execname string begin execname ExtractFileName paramstr 0 writeln execname lt serial number gt writeln execname lt logical name gt writeln execname any oya sleep 2500 lovers end Procedure die msg string begin writeln msg check USB cable manteg end var errmsg a aee target SEEN sensor 5 TYC TrrENt Sens Ci Car TYCUrrent sensorAC TYCurrent m TyModule begin if paramcount lt 1 then usage target paramstr 1 Setup the API to use local USB devices Et S yRegqusterhubi usb emEnso i lt VAP EE SUCCHSs ie begin WriteLn RegisterHub error errmsg halt End if target any then begin retreive any voltage sensor can be AC or DC sensor yFirstCurrent If sensor nil Then Die No
217. nt registerValueCallback YDataLoggerValueCallback callback int registerValueCallback YDataLoggerValueCallback callback pas function registerValueCallback callback TYDataLoggerValueCallback LongInt vb function registerValueCallback As Integer int registerValueCallback ValueCallback callback int registerValueCallback UpdateCallback callback def registerValueCallback callback The callback is invoked only during the execution of ySleep or yHandleEvents This provides control over the time when the callback is triggered For good responsiveness remember to call one of these two functions periodically To unregister a callback pass a null pointer as argument Parameters callback the callback function to call or a null pointer The callback function should take two arguments the function object of which the value has changed and the character string describing the new advertised value 266 www yoctopuce com 21 High level API Reference datalogger set_autoStart YDataLogger datalogger setAutoStart Changes the default activation state of the data logger on power up function set_autoStart newval function set_autoStart newval function set_autoStart newval int set_autoStart Y_AUTOSTART_enum newval int setAutoStart Y_AUTOSTART_enum newval function set_autoStart newval Integer integer function set_autoStart ByVal newval As Integer As Integer int set_autoStart int n
218. ntdown int rebootCountdown function get_rebootCountdown Longint function get_rebootCountdown As Integer int get_rebootCountdown int get_rebootCountdown def get_rebootCountdown YModule target get_rebootCountdown Returns an integer corresponding to the remaining number of seconds before the module restarts or zero when no reboot has been scheduled On failure throws an exception or returns Y_REBOOTCOUNTDOWN_INVALID 174 www yoctopuce com 21 High level API Reference module get_serialNumber module serialNumber Returns the serial number of the module as set by the factory function get_serialNumber function get_serialNumber function get_serialNumber string get_serialNumber NSString serialNumber function get_serialNumber string function get_serialNumber As String string get_serialNumber String get_serialNumber def get_serialNumber YModule target get_serialNumber Returns a string corresponding to the serial number of the module as set by the factory On failure throws an exception or returns Y_SERTALNUMBER_INVALID YModule www yoctopuce com 175 21 High level API Reference module get_upTime YModule module upTime Returns the number of milliseconds spent since the module was powered on is _ function get_upTime node js function get_upTime php_ function get_upTime s64 get_upTime
219. ntext or any subclasee It is not necessary to call this function to reach modules through the network Parameters osContext an object of class android content Context or any subclass www yoctopuce com 131 21 High level API Reference YAPI FreeAPI YAPI yFreeAPI Frees dynamically allocated memory blocks used by the Yoctopuce library is _ function yFreeAPI node js function FreeAPI php _ function yFreeAPI void yFreeAPI void yFreeAPI procedure yFreeAPI procedure yFreeAPI void FreeAPI synchronized static void FreeAPI def FreeAPI It is generally not required to call this function unless you want to free all dynamically allocated memory blocks in order to track a memory leak for instance You should not call any other library function after calling yF reeAPI or your program will crash 132 www yoctopuce com 21 High level API Reference YAPI GetAPIVersion YAPI yGetAPIVersion Returns the version identifier for the Yoctopuce library in use function yGetAPIVersion function GetAPIVersion function yGetAPIVersion string yGetAPIVersion NSString yGetAP IVersion function yGetAPIVersion string function yGetAPIVersion As String String GetAPIVersion String GetAPIVersion def GetAP IVersion The version is a string in the form Major Minor Build for instance 1 01 5535 For languages using an external DLL for ins
220. number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not NULL Below a short example listing the connected modules include lt iostream gt include yocto_ api h using namespace std int maanime earoe const char arov IN string errmsg Setup the API to use local USB devices if yRegisterHub usb errmsg YAPT SUCCESS Cane lt lt Wiieenisiecicitible Cusiceieg H lt lt Saee lt lt eey return 1 cout lt Device List lt lt end YModule module yFirstModule while module NULL coui imode Seiere ESreleUlNMiggie lt lt Y ep cout lt lt module gt get_productName lt lt endl module module gt nextModule www yoctopuce com 55 11 Using Yocto Amp with C return 0 11 3 Error handling When you imp
221. o Writeln Device list module yFirstModule while module lt gt nil do began Writeln module get_serialNumber module get_productName module module nextModule end end 15 4 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help www yoctopuce com 83 15 Using Yocto Amp with Delphi you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to i1sOnline and which could crash the software The only way to prevent this is to implement one of the two error handling techniques described below The method recommended by most programming languages for unpredictable error handling is the use of ex
222. o the function 238 www yoctopuce com 21 High level API Reference datalogger get_functionld Returns the hardware identifier of the data logger without reference to the module datalogger get_hardwareld Returns the unique hardware identifier of the data logger in the form SERIAL FUNCTIONID datalogger get_logicalName Returns the logical name of the data logger datalogger get_module Gets the YModule object for the device on which the function is located datalogger get_module_async callback context Gets the YModule object for the device on which the function is located asynchronous version datalogger get_recording Returns the current activation state of the data logger datalogger get_timeUTC Returns the Unix timestamp for current UTC time if known datalogger get_userData Returns the value of the userData attribute as previously stored using method set_userData datalogger isOnline Checks if the data logger is currently reachable without raising any error datalogger isOnline_async callback context Checks if the data logger is currently reachable without raising any error asynchronous version datalogger load msValidity Preloads the data logger cache with a specified validity duration datalogger load_async msValidity callback context Preloads the data logger cache with a specified validity duration asynchronous version datalogger nex
223. oFlash gt lt SCRIPT gt lt HEAD gt lt BODY onload refresh gt Module to use lt input id serial gt lt input id msg style color red border none readonly gt lt br gt Current name lt input id curName readonly gt lt br gt New logical name lt input id newName gt lt a href javascript save gt Save lt a gt lt BODY gt lt HTML gt Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not NULL Below a short example listing the connected modules lt HTML gt lt HEAD gt lt TITLE gt Modules inventory lt TITLE gt lt SCRIPT type text javascript src yocto api js gt lt SCRIPI gt lt SCRIPT language javascriptl 5 type text JavaScript gt N Use explicit error handling rather than exceptions yDisableExce
224. ode must nevertheless be conceived to interpret in the best possible way the errors indicated by the library The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software The only way to prevent this is to implement one of the two error handling techniques described below The method recommended by most programming languages for unpredictable error handling is the use of exceptions By default it is the behavior of the Yoctopuce library If an error happens while you try to access a module the library throws an exception In this case there are three possibilities e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the most desirable the Yoctopuce library offers another possibility for error handling allowing you to c
225. odule with serial number YAMPMK0O1 123456 which you have named MyModule and for which you have given the current function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once Scurrent yFindCurrent YAMPMK01 123456 currentl1 Scurrent yFindCurrent YAMPMK01 123456 MyFunction Scurrent yFindCurrent MyModule current1 Scurrent yFindCurrent MyModule MyFunction Scurrent yFindCurrent MyFunction yFindCurrent returns an object which you can then use at will to control the current sensor isOnline The isOnline method of the object returned by yFindCurrent allows you to know if the corresponding module is present and in working order get_currentValue The get _currentValue method of the object returned by yFindCurrent allows you to obtain the current as measured by the sensor The returned value is a number directly representing the value in mA A real example Open your preferred text editor copy the code sample below save it with the Yoctopuce library files in a location which is accessible to you web server then use your preferred web browser to access this page The code is also provided in the directory Examples Doc GettingStarted Yocto Amp of the Yoctopuce library In this example you will recognize the functions explained above but this time used with all side materials needed to make it work nicely as a small demo 4
226. of the modules implementing them Therefore it is quite possible to work with a set of functions without ever knowing exactly which module are hosting them at the hardware level This tremendously simplifies programming projects with a large number of modules www yoctopuce com 19 7 Programming general concepts From the programming stand point your Yocto Amp is viewed as a module hosting a given number of functions In the API these functions are objects which can be found independently in several ways Access to the functions of a module Access by logical name Each function can be assigned an arbitrary and persistent logical name this logical name is stored in the flash memory of the module even if this module is disconnected An object corresponding to an Xxx function to which a logical name has been assigned can then be directly found with this logical name and the YXxx FindXxx method Note however that a logical name must be unique among all the connected modules Access by enumeration You can enumerate all the functions of the same type on all the connected modules with the help of the classic enumeration functions FirstXxx and nextXxxx available for each YXxx class Access by hardware name Each module function has a hardware name assigned at the factory and which cannot be modified The functions of a module can also be found directly with this hardware name and the YXxx FindXxx function of the corresponding class
227. oid before hoping to make Yoctopuce modules work with it Unfortunately having a correct version of Android and USB ports working in host mode is not enough to guaranty that Yoctopuce modules will work well under Android Indeed some manufacturers configure their Android image so that devices other than keyboard and mass storage are ignored and this configuration is hard to detect As things currently stand the best way to know if a given Android machine works with Yoctopuce modules consists in trying Supported hardware The library is tested and validated on the following machines e Samsung Galaxy S3 e Samsung Galaxy Note 2 e Google Nexus 5 e Google Nexus 7 e Acer Iconia Tab A200 e Asus Tranformer Pad TF300T e Kurio 7 If your Android machine is not able to control Yoctopuce modules natively you still have the possibility to remotely control modules driven by a VirtualHub on another OS or a YoctoHub 18 4 Activating the USB port under Android By default Android does not allow an application to access the devices connected to the USB port To enable your application to interact with a Yoctopuce module directly connected on your tablet on a USB port a few additional steps are required If you intend to interact only with modules connected on another machine through the network you can ignore this section In your AndroidManifest xml you must declare using the USB Host functionality by adding the lt uses feature andro
228. on you wish to correct The following code applies the correction illustrated on the graph above to the first current1 function found Note the call to the saveToFlash method of the module hosting the function so that the module does not forget the calibration as soon as it is disconnected Double ValuesBefore 5 Double ValuesAfter 10 YCurrent f YCurrent FirstCurrent f calibrateFromPoints ValuesBefore ValuesAfter f get_module saveToFlash 2 point correction 2 point correction allows you to perform both a shift and a multiplication by a given factor between two points If you provide the two points a b and c d the function result is multiplied d b c a in the a c range and shifted so that when the value read by the sensor is a or c the current1 function returns respectively b and d Outside of the a c range the values are simply shifted so as to preserve the continuity of the measures an increase of 1 on the value read by the sensor induces an increase of 1 on the returned value www yoctopuce com 115 19 Advanced programming o se Dr 20 v ES 3 e z ey Pa 15 8 O oO 10 5 A sensor value i 5 10 15 20 25 30 Measure correction with the two calibration points 10 5 and 25 10 The code allowing you to program this calibration is very similar to the preceding code example Double ValuesBefore 10 25 Double ValuesAfter 5 10 YCurrent f YCurrent Fi
229. on load msValidity node js function load msValidity php function load msValidity YRETCODE load int msValidity YRETCODE load int msValidity function load msValidity integer YRETCODE function load ByVal msValidity As Integer As YRETCODE YRETCODE load int msValidity int load long msValidity def load msValidity By default whenever accessing a device all module attributes are kept in cache for the standard duration 5 ms This method can be used to temporarily mark the cache as valid for a longer period in order to reduce network trafic for instance Parameters msValidity an integer corresponding to the validity attributed to the loaded module parameters in milliseconds Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code 182 www yoctopuce com 21 High level API Reference module load_async YModule Preloads the module cache with a specified validity duration asynchronous version function load_async msValidity callback context function load_async msValidity callback context By default whenever accessing a device all module attributes are kept in cache for the standard duration 5 ms This method can be used to temporarily mark the cache as valid for a longer period in order to reduce network trafic for instance This asynchronous version exists only in Javascript It uses a callback instead
230. onfiguration The callback API thus uses the VirtualHub as a gateway All the communications are initiated by the VirtualHub They are thus outgoing communications and therefore perfectly authorized by the DSL router You must configure the VirtualHub so that it calls the PHP script on a regular basis To do so 1 Launch a VirtualHub 2 Access its interface usually 127 0 0 1 4444 3 Click on the configure button of the line corresponding to the Virtua Hub itself 4 Click on the edit button of the Outgoing callbacks section Serial Logical Name Description Action VIRTHUB0 7d1a86fb0 VirtualHub configure view log file RELAYHI 55 Yocto PowerRelay Configure view log fie beacon TMPSENS1 0S5E7F Yocto Temperature configure view log file beacon l Show device functions Click on the configure button on the first line www yoctopuce com 47 10 Using Yocto Amp with PHP VIRTHUBO 7d1a86fb09 Edit parameters for VIRTHUBO 7d1a86f009 and click on the Save button Serial VIRTHUB0 7d1a86fb09 Product name VirtualHub Software version 10789 Logical name Incoming connections Authentication to read information from the devices NO edit Authentication to make changes to the devices NO gait Outgoing callbacks Callback URL octoHub Gi Delay between callbacks min 3 s max 600 s This VirtualHub can post the advertised values of all devices on a specific URL on a regul
231. onfiguration in its permanent memory To do so use the YModule saveToFlash method Inversely it is possible to force the module to forget its current settings by using the YModule revertFromFlash method The short example below allows you to modify the logical name of a module import com yoctopuce YoctoAPI public class Demo public static void main String args Ley 4 setup the API to use local VirtualHub YAPI RegisterHub 127 0 0 1 catch YAPT Exception ex Syo cem out pEanialin Cannio Ee Contaci Vinea Hub one iy s Om Ore set ex getLocalizedMessage System out printin Ensure that the VirtualHub application is running System exit 1 if args length 2 System out printin usage demo lt serial or logical name gt lt new logical name gt System exit 1 YModule m String newname m YModule FindModule args 0 use serial or logical name try newname args 1 if YAPI CheckLogicalName newname System out printin Invalid name newname Systeme escive 1s y 94 www yoctopuce com 17 Using the Yocto Amp with Java m set_logicalName newname m saveToFlash do not forget this System our print ln Modulle serra Wm get serialiNumboersi 9 System out printlin name m get_logicalName catch YAPT Exception ex System out printlin Module args 0 not connected check identification and USB cabl
232. onous commands on the module to complete and invoke the user provided callback function function wait_async callback context function wait_async callback context The callback function can therefore freely issue synchronous or asynchronous commands without risking to block the Javascript VM Parameters callback callback function that is invoked when all pending commands on the module are completed The callback function receives two arguments the caller specific context object and the receiving function object context caller specific object that is passed as is to the callback function Returns nothing www yoctopuce com 237 21 High level API Reference 21 4 DataLogger function interface Yoctopuce sensors include a non volatile memory capable of storing ongoing measured data automatically without requiring a permanent connection to a computer The DataLogger function controls the global parameters of the internal data logger In order to use the functions described here you should include lt script type text javascript src yocto_datalogger js gt lt script gt var yoctolib require yoctolib var YDataLogger yoctolib YDataLogger require_once yocto_datalogger php include yocto_datalogger h import yocto_datalogger h uses yocto_datalogger yocto_datalogger vb yocto_datalogger cs import com yoctopuce YoctoAPI YDataLogger from yocto_datalogger import Global fu
233. or your project to build correctly you need to link with your project the prerequisite system libraries that is For Windows the libraries are added automatically e For Mac OS X IOKit framework and CoreFoundation framework e For Linux libm libpthread libusb1 0 and libstdc Integration as a static library Integration of the Yoctopuce library as a static library is a simpler manner to build a small executable which uses Yoctopuce modules You can quickly compile the program with a single command You do not need to install a dynamic library specific to Yoctopuce everything is in the executable To integrate the static Yoctopuce library to your project you must include the Sources directory of the Yoctopuce library into your IncludePath and add the sub directory Binaries corresponding to your operating system into your libPath Then for you project to build correctly you need to link with your project the Yoctopuce library and the prerequisite system libraries For Windows yocto static lib e For Mac OS X libyocto static a IOKit framework and CoreFoundation framework For Linux libyocto static a libm libpthread libusb1 0 and libstdc Note under Linux if you wish to compile in command line with GCC it is generally advisable to link system libraries as dynamic libraries rather than as static ones To mix static and dynamic libraries on the same command line you must pass the following arguments GO 12
234. ou do not need to install any driver 9 2 Control of the Current function A few lines of code are enough to use a Yocto Amp Here is the skeleton of a JavaScript code snipplet to use the Current function lt SCRIPT type text javascript src yocto_apil jjs gt lt SCRIPT gt lt SCRIPT type text javascript src yocto_ current jis gt lt SCRIPT gt Get access to your device through the VirtualHub running locally yRegisterHub http 127 0 0 1 4444 var current yFindCurrent YAMPMK01 123456 current1 Check that the module is online to handle hot plug if current isOnline 1 Actually as soon as Opera implements support for the HTTP Access Control Allow Origin header www yoctopuce com EN libraries php 3 www yoctopuce com EN virtualhub php www yoctopuce com 33 9 Using Yocto Amp with Javascript Use eurrent get_currentValue Let us look at these lines in more details yocto_api js and yocto_current js These two Javascript includes provide access to functions allowing you to manage Yoctopuce modules yocto api js must always be included yocto current js is necessary to manage modules containing a current sensor such as Yocto Amp yRegisterHub The yRegisterHub function allows you to indicate on which machine the Yoctopuce modules are located more precisely on which machine the VirtualHub software is running In our case the 127 0 0 1 4444 address indicates the local machine
235. ou must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software The only way to prevent this is to implement one of the two error handling techniques described below The method recommended by most programming languages for unpredictable error handling is the use of exceptions By default it is the behavior of the Yoctopuce library If an error happens while you try to access a module the library throws an exception In this case there are three possibilities e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the most desirable the Yoctopuce library offers another possibility for error handling allowing you to create a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a g
236. plaining the source of the error You can request them from the object which returned the error calling the errType and errMessage methods Their returned values contain the same information as in the exceptions when they are active 11 4 Integration variants for the C Yoctopuce library Depending on your needs and on your preferences you can integrate the library into your projects in several distinct manners This section explains how to implement the different options Integration in source format Integrating all the sources of the library into your projects has several advantages e It guaranties the respect of the compilation conventions of your project 32 64 bits inclusion of debugging symbols unicode or ASCII characters etc 56 www yoctopuce com 11 Using Yocto Amp with C e It facilitates debugging if you are looking for the cause of a problem linked to the Yoctopuce library e It reduces the dependencies on third party components for example in the case where you would need to recompile this project for another architecture in many years e It does not require the installation of a dynamic library specific to Yoctopuce on the final system everything is in the executable To integrate the source code the easiest way is to simply include the Sources directory of your Yoctopuce library into your IncludePath and to add all the files of this directory including the sub directory yapi to your project F
237. ple runs the application as soon as a Yocto Relay or a YoctoPowerRelay is connected You can find the vendorlID and the devicelD of Yoctopuce modules in the characteristics section of the documentation lt xml version 1 0 encoding utf 8 gt lt resources gt lt usb device vendor id 9440 product id 12 gt lt usb device vendor id 9440 product id 13 gt lt resources gt www yoctopuce com 99 18 Using the Yocto Amp with Android 18 5 Control of the Current function A few lines of code are enough to use a Yocto Amp Here is the skeleton of a Java code snippet to use the Current function aaa Retrieving the object representing the module connected here locally by USB YAPI EnableUSBHost this YAPI RegisterHub usb current YCurrent FindCurrent YAMPMK01 123456 current1 Hot plug is easy just check that the device is online if current isOnline TAUS eurr ene Get cunrencVal ue lh eo Let us look at these lines in more details YAPI EnableUSBHost The YAPI EnableUSBHost function initializes the API with the Context of the current application This function takes as argument an object of the android content Context class or of a subclass If you intend to connect your application only to other machines through the network this function is facultative YAPI RegisterHub The yAPI RegisterHub function initializes the Yoctopuce API and indicates where
238. posed of a DLL and of source files in Visual Basic The DLL is not a NET DLL but a classic DLL written in C which manages the low level communications with the modules The source files in Visual Basic manage the high level part of the API Therefore your need both this DLL and the vb files of the sources directory to create a project managing Yoctopuce modules Configuring a Visual Basic project The following indications are provided for Visual Studio Express 2010 but the process is similar for other versions Start by creating your project Then on the So ution Explorer panel right click on your project and select Add and then Add an existing item A file selection window opens Select the yocto_api vb file and the files corresponding to the functions of the Yoctopuce modules that your project is going to manage If in doubt select all the files You then have the choice between simply adding these files to your project or to add them as links the Add button is in fact a scroll down menu In the first case Visual Studio copies the selected files into your project In the second case Visual Studio simply keeps a link on the original files We recommend you to use links which makes updates of the library much easier 1 http www microsoft com visualstudio en us products 2010 editions visual basic express www yoctopuce com EN libraries php 3 The sources of this DLL are available in the C API www yoctopuce com 65 13
239. ptions www yoctopuce com 37 9 Using Yocto Amp with Javascript Setup the API to use the VirtualHub on local machine if yRegisterHub http 127 0 0 1 4444 YAPI SUCCESS eulyeneie Me eholatone Contacti Nirteua Hubklon P27 Ole oma function refresh yUpdateDeviceList var htmlcode var module yFirstModule while module htmlcode module get_serialNumber tmodule get_productName lt br gt module module nextModule document getElementById list innerHTML htmlcode setTimeout refresh 500 gt lt SCR TEIS lt HEAD gt lt BODY onload refresh gt lt H1l gt Device list lt H1 gt lt tt gt lt span id list gt lt span gt lt tt gt lt BODY gt lt HTML gt 9 4 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will sta
240. r datalogger errorType Returns the numerical error code of the latest error with the data logger function get_errorType function get_errorType function get_errorType YRETCODE get_errorType function get_errorType YRETCODE function get_errorType As YRETCODE YRETCODE get_errorType int get_errorType def get_errorType This method is mostly useful when using the Yoctopuce library with exceptions disabled Returns a number corresponding to the code of the latest error that occured while using the data logger object 250 www yoctopuce com 21 High level API Reference datalogger get_friendlyName YDataLogger datalogger friendlyName Returns a global identifier of the data logger in the format MODULE_NAME FUNCT ION_NAME function get_friendlyName function get_friendlyName function get_friendlyName string get_friendlyName NSString friendlyName string get_friendlyName String get_friendlyName def get_friendlyName The returned string uses the logical names of the module and of the data logger if they are defined otherwise the serial number of the module and the hardware identifier of the data logger for exemple yCustomName relayl1 Returns a string that uniquely identifies the data logger using logical names ex MyCustomName relay1 On failure throws an exception or returns Y_FRIENDLYNAME_INVALID www yoctopuc
241. rcentVal uek Os erst cy ie toe sila 5 Console Write VAC Ses cnsOrAG Ger meunasemeVcMiuen i Eo Stringi an arte i Console WriteLine press Ctrl C to exit YAPI Sleep 1000 ref errmsg 14 4 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon using System using System Collections Generic using System Ling using System Text namespace ConsoleApplicationl class Program static void usage string execname System AppDomain CurrentDomain FriendlyName Console WriteLine Usage Console WriteLine execname lt serial or logical name gt ON OFF System Threading Thread Sleep 2500 Environment Exit 0 static void Main string args YModule m string errmsg if YAPI RegisterHub usb ref errmsg YAPI SUCCESS Console WriteLine RegisterHub error errmsg Environment Exit 0 HE ano st lence lt 5 usage m YModule FindModule args 0 use serial or logical name if m isOnline if args Length gt 2 if args lolpper ON masee beaconi YModuile BEACON MON ia if args 1 ToUpper OFF m set_beacon YModule BEACON OFF Console WriteLine serial Vo magersertalNumbex ON Console WriteLine logical name m get_logicalName Console Write
242. re active www yoctopuce com 77 78 www yoctopuce com 15 Using Yocto Amp with Delphi Delphi is a descendent of Turbo Pascal Originally Delphi was produced by Borland Embarcadero now edits it The strength of this language resides in its ease of use as anyone with some notions of the Pascal language can develop a Windows application in next to no time Its only disadvantage is to cost something Delphi libraries are provided not as VCL components but directly as source files These files are compatible with most Delphi versions To keep them simple all the examples provided in this documentation are console applications Obviously the libraries work in a strictly identical way with VCL applications You will soon notice that the Delphi API defines many functions which return objects You do not need to deallocate these objects yourself the API does it automatically at the end of the application 15 1 Preparation Go to the Yoctopuce web site and download the Yoctopuce Delphi libraries Uncompress everything in a directory of your choice add the subdirectory sources in the list of directories of Delphi libraries By default the Yoctopuce Delphi library uses the yapi di DLL all the applications you will create with Delphi must have access to this DLL The simplest way to ensure this is to make sure yapi dll is located in the same directory as the executable file of your application 15 2 Control of the Curre
243. reate a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get _state method returns a Y STATE INVALID value a get _currentValue method returns a Y CURRENTVALUE INVALID value and so on In any case the returned value is of the expected type and is not a null pointer which would risk crashing your program At worst if you display the value without testing it it will be outside the expected bounds for the returned value In the case of functions which do not normally return information the return value is YAPI SUCCESS if everything went well and a different error code in case of failure When you work without exceptions you can obtain an error code and an error message explaining the source of the error You can request them from the object which returned the error calling the errType and errMessage methods Their returned values contain the same information as in the exceptions when they are active 70 www yoctopuce com 14 Using Yocto Amp with C C pronounced C Sharp is an o
244. rectory respecting the alphabetical order for example the 51 custom rules file is interpreted AFTER the 50 udev default rules file The 50 udev default file contains the system default udev rules To modify the default behavior you therefore need to create a file with a name that starts with a number larger than 50 that will override the system default rules Note that to add a rule you need a root access on the system In the udev_ conf directory of the Virtua Hub for Linux archive there are two rule examples which you can use as a basis Example 1 51 yoctopuce rules This rule provides all the users with read and write access to the Yoctopuce USB peripherals Access rights for all other peripherals are not modified If this scenario suits you you only need to copy the 51 yoctopuce all rules file into the etc udev rules d directory and to restart your system udev rules to allow write access to all users for Yoctopuce USB devices SUBSYSTEM usb ATTR idVendor 24e0 MODE 0666 Example 2 51 yoctopuce_group rules This rule authorizes the yoctogroup group to have read and write access to Yoctopuce USB peripherals Access rights for all other peripherals are not modified If this scenario suits you you 1 http www yoctopuce com FR virtualhub php www yoctopuce com 293 22 Troubleshooting only need to copy the 51 yoctopuce_group rules file into the etc udev rules d directory a
245. removalCallback a procedure taking a YModule parameter or null www yoctopuce com 139 21 High level API Reference YAPI RegisterHub YAPI yRegisterHub Setup the Yoctopuce library to use modules connected on a given machine function yRegisterHub url errmsg node js function RegisterHub url errmsg php function yRegisterHub url amp errmsg YRETCODE yRegisterHub const string amp url string amp errmsg YRETCODE yRegisterHub NSString url NSError errmsg function yRegisterHub url string var errmsg string integer function yRegisterHub ByVal url As String ByRef errmsg As String As Integer int RegisterHub string url ref string errmsg synchronized static int RegisterHub String url def RegisterHub url errmsg None The parameter will determine how the API will work Use the follwing values usb When the usb keyword is used the API will work with devices connected directly to the USB bus Some programming languages such a Javascript PHP and Java don t provide direct access to USB harware so usb will not work with these In this case use a VirtualHub or a networked YoctoHub see below X X X X or hostname The API will use the devices connected to the host with the given IP address or hostname That host can be a regular computer running a VirtualHub or a networked YoctoHub such as YoctoHub Ethernet or YoctoHub Wireless If you want to use the VirtualHub running on you local computer
246. rent YAMPMK01 123456 current1 current YCurrent FindCurrent YAMPMK01 123456 MyFunction current YCurrent FindCurrent MyModule current1 current YCurrent FindCurrent MyModule MyFunction current YCurrent FindCurrent MyFunction YCurrent FindCurrent returns an object which you can then use at will to control the current sensor isOnline The isOnline method of the object returned by YCurrent FindCurrent allows you to know if the corresponding module is present and in working order 4 Remember to change the filter of the selection window otherwise the DLL will not show 72 www yoctopuce com 14 Using Yocto Amp with C get_currentValue The get_currentValue method of the object returned by YCurrent FindCurrent allows you to obtain the current as measured by the sensor The returned value is a number directly representing the value in mA A real example Launch Microsoft Visual C and open the corresponding sample project provided in the directory Examples Doc GettingStarted Yocto Amp of the Yoctopuce library In this example you will recognize the functions explained above but this time used with all side materials needed to make it work nicely as a small demo using System using ovstem Collections Generic using System Ling using System Text namespace ConsoleApplicationl class Program static void usage i string execname System AppDomain CurrentDomain FriendlyName
247. responding to the current value of the current sensor no more than 6 characters On failure throws an exception or returns Y_ADVERTISEDVALUE_INVALID 202 www yoctopuce com 21 High level API Reference current get_currentRawValue current gt currentRawValue Returns the uncalibrated unrounded raw value returned by the sensor function get_currentRawValue function get_currentRawValue function get_currentRawValue double get_currentRawValue double currentRawValue function get_currentRawValue double function get_currentRawValue As Double double get_currentRawValue double get_currentRawValue def get_currentRawValue YCurrent target get_currentRawValue Returns a floating point number corresponding to the uncalibrated unrounded raw value returned by the sensor YCurrent On failure throws an exception or returns Y_CURRENTRAWVALUE_INVALID www yoctopuce com 203 21 High level API Reference current get_currentValue current currentValue Returns the current measured value function get_currentValue function get_currentValue function get_currentValue double get_currentValue double currentValue function get_currentValue double function get_currentValue As Double double get_currentValue double get_currentValue def get_currentValue Y Current target get_currentValue Returns a floating point number corresponding
248. ript1 5 type text JavaScript gt 2S Setup the API to use the VirtualHub on local machine if yRegisterHub http 127 0 0 1 4444 YAPI SUCCESS ales ti MCannor Contacti Mir tual HUG on 2700 function refresh yar sensor SSMNSOIING sensorDC yar Serial document getElement Bey rd serra kvaler if Serene Ytj y or use any connected module suitable for the demo sensor yFirstCurrent if sensor serial sensor module get_serialNumber document getElementBylId serial value serial sensorDC yFindCurrent serial currentl sensorAC yFindCurrent serial current2 if sensorDC isOnline document getHElementById msg value document getElementById DC value sensorDC get_currentValue document getElementById AC value sensorAC get_currentValue else document getHlementById msg value Module not connected setTimeout refresh 500 gt OER TEE lt HEAD gt lt BODY onload refresh gt Module to use lt input id serial gt lt input id msg style color red border none readonly gt lt br gt DC lt input id DC size 5 readonly gt mA lt br gt AC lt input id AC size 5 readonly gt mA lt BODY gt lt HTML gt 9 3 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to ac
249. rned value In the case of functions which do not normally return information the return value is YAPI_ SUCCESS if everything went well and a different error code in case of failure When you work without exceptions you can obtain an error code and an error message explaining the source of the error You can request them from the object which returned the error calling the errType and errMessage methods Their returned values contain the same information as in the exceptions when they are active 84 www yoctopuce com 16 Using the Yocto Amp with Python Python is an interpreted object oriented language developed by Guido van Rossum Among its advantages is the fact that it is free and the fact that it is available for most platforms Windows as well as UNIX It is an ideal language to write small scripts on a napkin The Yoctopuce library is compatible with Python 2 6 and 3 It works under Windows Mac OS X and Linux Intel as well as ARM The library was tested with Python 2 6 and Python 3 2 Python interpreters are available on the Python web site 16 1 Source files The Yoctopuce library classes for Python that you will use are provided as source files Copy all the content of the Sources directory in the directory of your choice and add this directory to the PYTHONPATH environment variable If you use an IDE to program in Python refer to its documentation to configure it so that it
250. ror message yFindCurrent The yFindCurrent function allows you to find a current sensor from the serial number of the module on which it resides and from its function name You can also use logical names as long as you have initialized them Let us imagine a Yocto Amp module with serial number YAMPMK0O1 123456 which you have named MyModule and for which you have given the current function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once current yFindCurrent YAMPMKO01 123456 current1 current yFindCurrent YAMPMK01 123456 MyFunction current yFindCurrent MyModule current1 current yFindCurrent MyModule MyFunction current yFindCurrent MyFunction yFindCurrent returns an object which you can then use at will to control the current sensor isOnline The isOnline method of the object returned by yFindCurrent allows you to know if the corresponding module is present and in working order get_currentValue The get _currentValue method of the object returned by yFindCurrent allows you to obtain the current as measured by the sensor The returned value is a number directly representing the value in mA 15 3 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization bea
251. rrent Longint v _ function get_usbCurrent As Integer int get_usbCurrent int get_usbCurrent def get_usbCurrent YModule target get_usbCurrent Returns an integer corresponding to the current consumed by the module on the USB bus in milli amps On failure throws an exception or returns Y_USBCURRENT_INVALID 178 www yoctopuce com 21 High level API Reference module get_userData YModule module gt userData Returns the value of the userData attribute as previously stored using method set_userData function get_userData function get_userData function get_userData void get_userData void userData function get_userData Tobject function get_userData As Object object get_userData Object get_userData def get_userData This attribute is never touched directly by the API and is at disposal of the caller to store a context Returns the object stored previously by the caller www yoctopuce com 179 21 High level API Reference module gt isOnline YModule Checks if the module is currently reachable without raising any error 5s function isOnline node js function isOnline php function isOnline cpp _ bool isOnline BOOL isOnline pas function isOnline boolean vb function isOnline As Boolean cs _ bool isOnline java boolean isOnline def isOnline If there are valid
252. rs callback callback function that is invoked when all pending commands on the module are completed The callback function receives two arguments the caller specific context object and the receiving function object context caller specific object that is passed as is to the callback function Returns nothing 272 www yoctopuce com 21 High level API Reference 21 5 Recorded data sequence YDataSet objects make it possible to retrieve a set of recorded measures for a given sensor anda specified time interval They can be used to load data points with a progress report When the YDataSet object is instanciated by the get_recordedData function no data is yet loaded from the module It is only when the loadMore method is called over and over than data will be effectively loaded from the dataLogger A preview of available measures is available using the function get_preview as soon as loadMore has been called once Measures themselves are available using function get_measures when loaded by subsequent calls to loadMore This class can only be used on devices that use a recent firmware as YDataSet objects are not supported by firmwares older than version 13000 In order to use the functions described here you should include lt script type text javascript src yocto_api js gt lt script gt var yoctolib require yoctolib var YAPI yoctolib YAPI var YModule yoctolib YModule require_on
253. rstCurrent f calibrateFromPoints ValuesBefore ValuesAfter f get_module saveToFlash Note that the values before correction must be sorted in a strictly ascending order otherwise they are simply ignored 3 to 5 point correction 3 to 5 point corrections are only a generalization of the 2 point method allowing you to create up to 4 correction ranges for an increased precision These ranges cannot be disjoint RO 5 oO 20 T we f gt amp G ie k gs 158 S O O 10 wos corr ae 5 sensor value i 5 10 15 20 25 30 Correction example with 3 calibration points Back to normal To cancel the effect of a calibration on a function call the calibrateFromPoints method with two empty arrays Double ValuesBefore ee Double ValuesAfter ive YCurrent f YCurrent FirstCurrent 116 www yoctopuce com 19 Advanced programming f calibrateFromPoints ValuesBefore ValuesAfter f get_module saveToFlash You will find in the Examples Prog Calibration directory of the Delphi VB and C libraries an application allowing you to test the effects of the 1 to 5 point calibration Arbitrary interpolation It is also possible to compute the interpolation instead of letting the module do it in order to calculate a spline interpolation for instance To do so you only need to store a callback in the API This callback must specify the number of calibration points it is expecting pub
254. s aa new ArrayAdapter lt String gt this android R layout simple spinner item aa setDropDownViewResource android R layout simple spinner dropdown_item my spin setAdapter aa handler new Handler Override protected void onStart BUSS Omar cltaten iy cry A aa clear YAPI EnableUSBHost this YAPI RegisterHub usb YModule module YModule FirstModule while module null if module get_productName equals Yocto Amp String serial module get_serialNumber aa add serial module module nextModule Bice HUNT McC oesem 4 e prnestackirace gt aa notifyDataSetChanged handler postDelayed r 500 Override protected void onStop super onStop handler removeCallbacks r YAPI FreeAPI www yoctopuce com 101 18 Using the Yocto Amp with Android Override public void onItemSelected AdapterView lt gt parent View view int pos long id serial parent getItemAtPosition pos toString Override public void onNothingSelected AdapterView lt gt arg0 final Runnable r new Runnable Swila oel Ea if serial null UCwAoMe Ce SOMSeie Neuroni Walinelowieecioe Serre MACE ne 1 5 Ley l TextView view TextView findViewById R id dcfield Views eet Seti sORMct luc lk cS OCmSensorm getCurrent valie demsensor geeUminr ye Pecarchy WAP TH x lt Gepiesomec ia e printStackTrace
255. s Y_LOGICALNAME_INVALID www yoctopuce com 255 21 High level API Reference datalogger get_module YDataLogger datalogger module Gets the YModule object for the device on which the function is located is _ function get_module node js function get_module php_ function get_module YModule get_module YModule module function get_module TYModule function get_module As YModule YModule get_module YModule get_module def get_module If the function cannot be located on any module the returned instance of YModu1e is not shown as on line Returns an instance of YModule 256 www yoctopuce com 21 High level API Reference datalogger get_module_async YDataLogger datalogger module_async Gets the YModul1e object for the device on which the function is located asynchronous version function get_module_async callback context function get_module_async callback context If the function cannot be located on any module the returned YModule object does not show as on line This asynchronous version exists only in Javascript It uses a callback instead of a return value in order to avoid blocking Firefox javascript VM that does not implement context switching during blocking I O calls See the documentation section on asynchronous Javascript calls for more details Parameters callback callback function that is invoked when the result
256. s eranda ananin eia dadevevecesenbahideededeeecpessgecesugashisdscedecsdatpedescegnestaes 17 7 Programming general concepts es sssissssiissssirsssnressrrnssnrirnriennrirssrrnesnrrnesnrn 19 ZA Programming PArAGIQM Siiami aa a aa aeaa a aaa aana i aaraa e ee A Aana aa iaaiiai aaia 19 7 2 The YOctO AMp Module raare raran awd a iaaea daera eit haere aaa a a 20 T Module COntrOl Lal E ni O KEE N E Ea E E 21 7 4 Current function interface woe ee cc cccecccceececceceeeeeceeeueceeeauseeuenseuuaueeeauseeueaeeeueceeeuaeeeneaeeeanseees 22 7 5 Datalogger f n tion interfaCe siniseen eee itn a a e aaae 23 7 6 What interface Native DLL or Service oi cccccccccsceueeccceceeeeeceueeeeeeeeeeueeeeeseeeeeeeeeeeuaes 24 FF PLOGrammMings Where tostat ore aree e aa ee Ge ea den aaeei 26 8 Using the Yocto Amp in command line ou ccc eseeseeceseeseseeneseeneees 29 Bel cIMStAllinG saci cees cece enn eii eevee eed eases eee desde ee fed NE EAE tee E ENA vies deck L a aE TE 29 8 2 Use general DOSCription rriar sce cll get Savane a a aT Aaa aa a ee eaei a aA ea aa aE 29 8 3 Control of the Current TUMCtlOn aeee E Hate e A aves cit 30 8 4 Control of the Module Part eee eee seeeeeeeeeeeseeeeeseeeceesaeeceesaeeeneaaeenesaaeeeesnaneneeseneeeesneenenaes 30 B S e ENO E E EE E E Melmna eden dee kat dette E A 31 9 Using Yocto Amp with Javascript ea ssseeesssesneesssenttessnrritesnrrrnnnnnrrnnsnnrrresee 33 OF Getting
257. s in a production application 19 1 Event programming The methods to manage Yoctopuce modules which we presented to you in preceding chapters were polling functions consisting in permanently asking the API if something had changed While easy to understand this programming technique is not the most efficient nor the most reactive Therefore the Yoctopuce programming API also provides an event programming model This technique consists in asking the API to signal by itself the important changes as soon as they are detected Each time a key parameter is modified the API calls a callback function which you have defined in advance Detecting module arrival and departure Hot plug management is important when you work with USB modules because sooner or later you will have to connect or disconnect a module when your application is running The API is designed to manage module unexpected arrival or departure in a transparent way But your application must take this into account if it wants to avoid pretending to use a disconnected module Event programming is particularly useful to detect module connection disconnection Indeed it is simpler to be told of new connections rather than to have to permanently list the connected modules to deduce which ones just arrived and which ones left To be warned as soon as a module is connected you need three pieces of code The callback The callback is the function which is called each time a new Yoctopuc
258. s 2 5mm assembly holes You can use these holes for screws The screw head diameter must not be larger than 4 5mm or they will damage the module circuits Make sure that the lower surface of the module is not in contact with the support We recommend using spacers but other methods are possible Nothing prevents you from fixing the module with a glue gun it will not be good looking but it will hold If your intend to screw your module directly against a conducting part for example a metallic frame insert an isolating layer in between Otherwise you are bound to induce a short circuit there are naked pads under your module Simple packaging tape should be enough for electric insulation www yoctopuce com 15 6 Assembly and connections 6 2 Connections You must know that the behavior of an ammeter is similar to the behavior of an electrical wire it merely lets the current go through while measuring it Therefore an ammeter must always be connected in series never in parallel Always pay great attention to how you connect your Yocto Amp If you connect it in parallel you are going to create a short circuit to destroy your Yocto Amp to damage your power supply and you can even start a fire Never connect an ammeter in parallel but in series This is important 6 3 Heating The Yocto Amp works in letting the current to be measured go through a low value resistance and in measuring the voltage appearing at the
259. s by not implementing current limitation on ports they simply connect the computer power supply to every port and declare themselves as self powered hub even when they are taking all their power from the USB bus in order to prevent any power consumption check in the operating system This looks a bit dirty but given the fact that computer USB ports are usually well protected by a hardware current limitation around 2000mA it actually works in every day life and seldom makes hardware damage What you should remember if you connect Yoctopuce modules through one or more USB hub without external power supply you have no safe guard and you depend entirely on your computer manufacturer attention to provide as much current as possible on the USB ports and to detect overloads before they lead to problems or to hardware damages When modules are not provided enough current they may work erratically and create unpredictable bugs If you want to prevent any risk do not cascade hubs without external power supply and do not connect peripherals requiring more than 100mA behind a bus powered hub In order to help controlling and planning overall power consumption for your project all Yoctopuce modules include a built in current sensor that tells with 5mA precision the consumption of the module on the USB bus www yoctopuce com 17 18 www yoctopuce com 7 Programming general concepts The Yoctopuce API was designed to be at the same tim
260. save the setting Note Yoctopuce modules do not need an active USB connection to work they start working as soon as they are powered on The Yocto Amp can store data without necessarily being connected to a computer you only need to activate the automatic start of the data logger and to power on the module with a simple USB charger Erasing the memory The memory of the data logger can be erased with the forgetAllDataStreams function Be aware that erasing cannot be undone YDataLogger 1 YDataLogger FirstDataLogger jl forgetAllDataStreams 112 www yoctopuce com 19 Advanced programming Choosing the logging frequency The logging frequency can be set up individually for each sensor using the method set _logFrequency The frequency is specified as a string same as for timed report callbacks by specifying the number of calls per second s per minute m or per hour h The default value is 1 s The following example configures the logging frequency at 15 measures per minute for the first sensor found whatever its type YSensor sensor YSensor FirstSensor Sensoxr set logErequency 15 m To avoid wasting flash memory it is possible to disable logging for specified functions In order to do so simply use the value OFF sensor set_logFrequency OFF Limitation The Yocto Amp cannot use a different frequency for timed report callbacks and for recording data into the datalogger Yo
261. sed by the Yoctopuce library yGetAP Version Returns the version identifier for the Yoctopuce library in use yGetTickCount Returns the current value of a monotone millisecond based time counter yHandleEvents errmsg Maintains the device to library communication channel ylnitAPI mode errmsg Initializes the Yoctopuce programming library explicitly yPreregisterHub url errmsg Fault tolerant alternative to RegisterHub yRegisterDeviceArrivalCallback arrivalCallback Register a callback function to be called each time a device is pluged yRegisterDeviceRemovalCallback removalCallback Register a callback function to be called each time a device is unpluged yRegisterHub url errmsg Setup the Yoctopuce library to use modules connected on a given machine yRegisterHubDiscoveryCallback callback 126 www yoctopuce com 21 High level API Reference Register a callback function to be called each time a network hub or a VirtualHub is detected on the local network yRegisterLogFunction logfun Registers a log callback function ySelectArchitecture arch Select the architecture or the library to be loaded to access to USB ySetDelegate object Objective C only Register an object that must follow the procol YDeviceHotPlug ySetTimeout callback ms_timeout arguments Invoke the specified calloack function after a given timeout ySleep ms_duration errmsg Pauses the execution flow for a specified duration
262. simple spinner dropdown_item my spin setAdapter aa Override protected void onStart super onStart 104 www yoctopuce com 18 Using the Yocto Amp with Android cry aa clear YAPI EnableUSBHost this YAPI RegisterHub usb YModule r YModule FirstModule while r null String hwid r get_hardwarelId aa add hwid r r nextModule j Ceen NGAP Mpxcicjpicslein O e printStackTrace refresh Spinner with detected relay aa notifyDataSetChanged Override protected void onStop super onstop YAPI FreeAPI private void DisplayModuleInfo TextView field if module null Re UTI rey YAPI UpdateDeviceList fixme field TextView findViewById R id logicalnamefield field setText module getLogicalName catch YAPI Exception e e printstacki race Override public void onItemSelected AdapterView lt gt parent View view int pos long id String hwid parent getItemAtPosition pos toString module YModule FindModule hwid DisplayModuleInfo Override public void onNothingSelected AdapterView lt gt arg0Q public void saveName View view if module null FECUEN EditText edit EditText findViewById R id newname String newname edit getText toString try if YAPI CheckLogicalName newname Toast makeText getApplicationContext Invalid
263. t get_dataStreams List lt YDataStream gt v int get_dataStreams ArrayList lt YDataStream gt v def get_dataStreams v The caller must pass by reference an empty array to hold YDataStream objects and the function fills it with objects describing available data sequences This is the old way to retrieve data from the DataLogger For new applications you should rather use get_dataSets method or call directly get_recordedData on the sensor object Parameters v an array of YDataStream objects to be filled in Returns YAPI_SUCCESS if the call succeeds On failure throws an exception or returns a negative error code 248 www yoctopuce com 21 High level API Reference datalogger get_errorMessage YDataLogger datalogger errorMessage Returns the error message of the latest error with the data logger function get_errorMessage function get_errorMessage function get_errorMessage string get_errorMessage NSString errorMessage function get_errorMessage string function get_errorMessage As String string get_errorMessage String get_errorMessage def get_errorMessage This method is mostly useful when using the Yoctopuce library with exceptions disabled Returns a string corresponding to the latest error message that occured while using the data logger object www yoctopuce com 249 21 High level API Reference datalogger get_errorType YDataLogge
264. t the whole API in the language of your choice Note however that a large portion of the API source code is automatically generated Therefore it is not necessary for you to port the complete API You only need to port the yocto_api file and one file corresponding to a function for example yocto_relay After a little additional work Yoctopuce is then able to generate all other files Therefore we highly recommend that you contact Yoctopuce support before undertaking to port the Yoctopuce library in another language Collaborative work is advantageous to both parties 124 www yoctopuce com 21 High level API Reference This chapter summarizes the high level API functions to drive your Yocto Amp Syntax and exact type names may vary from one language to another but unless otherwise stated all the functions are available in every language For detailed information regarding the types of arguments and return values for a given language refer to the definition file for this language yocto_api as well as the other yocto_ files that define the function interfaces For languages which support exceptions all of these functions throw exceptions in case of error by default rather than returning the documented error value for each function This is by design to facilitate debugging It is however possible to disable the use of exceptions using the yDisableExceptions function in case you prefer to work with functions that return error va
265. tDataLogger Continues the enumeration of data loggers started using yFirstDataLogger datalogger registerValueCallback callback Registers the callback function that is invoked on every change of advertised value datalogger set_autoStart newval Changes the default activation state of the data logger on power up datalogger set_logicalName newval Changes the logical name of the data logger datalogger set_recording newval Changes the activation state of the data logger to start stop recording data datalogger set_timeUTC newval Changes the current UTC time reference used for recorded data datalogger set_userData data Stores a user context provided as argument in the userData attribute of the function datalogger wait_async callback context Waits for all pending asynchronous commands on the module to complete and invoke the user provided callback function www yoctopuce com 239 21 High level API Reference YDataLogger FindDataLogger YDataLogger yFindDataLogger Retrieves a data logger for a given identifier function yFindDataLogger func node js function FindDataLogger func function yFindDataLogger func YDataLogger yFindDataLogger string func YDataLogger yFindDataLogger NSString func function yFindDataLogger func string TYDataLogger function yFindDataLogger ByVal func As String As YDataLogger Y DataLogger FindDataLogger string func YDataLogger FindDataLo
266. t_functionld YDataLogger 252 get_functionld YDataSet 275 get_hardwareld YCurrent 209 get_hardwareld YDataLogger 253 get_hardwareld YDataSet 276 get_hardwareld YModule 164 get_highestValue YCurrent 210 get_icon2d YModule 165 get_lastLogs YModule 166 get_logFrequency YCurrent 211 get_logicalName YCurrent 212 get_logicalName YDataLogger 254 get_logicalName YModule 167 get_lowestValue YCurrent 213 get_luminosity YModule 168 get_maxValue YMeasure 288 get_measures YDataSet 277 get_minValue YMeasure 289 get_module YCurrent 214 get_module YDataLogger 255 get_module_async YCurrent 215 get_module_async YDataLogger 256 get_persistentSettings YModule 169 get_preview YDataSet 278 get_productld YModule 170 get_productName YModule 171 get_productRelease YModule 172 get_progress YDataSet 279 get_rebootCountdown YModule 173 get_recordedData YCurrent 216 get_recording YDataLogger 257 get_reportFrequency YCurrent 217 get_resolution YCurrent 218 get_serialNumber YModule 174 get_startTimeUTC YDataSet 280 get_startTimeUTC YMeasure 290 get_summary YDataSet 281 get_timeUTC YDataLogger 258 get_unit YCurrent 219 get_unit YDataSet 282 get_upTime YModule 175 get_usbBandwidth YModule 176 get_usbCurrent YModule 177 get_userData YCurrent 220 get_userData YDataLogger 259 get_userData YModule 178 GetAPIVersion YAPI 132 GetTickCount YAPI 133 H HandleEvents YAPI 134 Hazards 7 Heating 16 High level 125
267. tance C VisualBasic or Delphi the character string includes as well the DLL version for instance 1 01 5535 1 01 5439 If you want to verify in your code that the library version is compatible with the version that you have used during development verify that the major number is strictly equal and that the minor number is greater or equal The build number is not relevant with respect to the library compatibility Returns a character string describing the library version www yoctopuce com 133 21 High level API Reference YAPI GetTickCount YAPI yGetTickCount Returns the current value of a monotone millisecond based time counter function yGetTickCount nodejs function GetTickCount function yGetTickCount u64 yGetTickCount u64 yGetTickCount function yGetTickCount u64 vo _ function yGetTickCount As Long ulong GetTickCount long GetTickCount def GetTickCount This counter can be used to compute delays in relation with Yoctopuce devices which also uses the millisecond as timebase Returns a long integer corresponding to the millisecond counter 134 www yoctopuce com 21 High level API Reference YAPI HandleEvents YAPI yHandleEvents Maintains the device to library communication channel function yHandleEvents errmsg function HandleEvents errmsg function yHandleEvents amp errmsg YRETCODE yHandleEvents string amp errmsg
268. te with one another using a local IP address of the 192 168 xxx yyy type and contact Internet servers through their public address However seen from the outside you have only one official IP address assigned to the DSL router only and you cannot reach your network appliances directly from the outside It is rather restrictive but it is a relatively efficient protection against intrusions response Responses from request from LAN machines are routed 46 www yoctopuce com 10 Using Yocto Amp with PHP request i But requests from the outside are blocked Seeing Internet without being seen provides an enormous security advantage However this signifies that you cannot a priori set up your own web server at home to control a home automation installation from the outside A solution to this problem advised by numerous home automation system dealers consists in providing outside visibility to your home automation server itself by adding a routing rule in the NAT configuration of the DSL router The issue of this solution is that it exposes the home automation server to external attacks The HTTP callback API solves this issue without having to modify the DSL router configuration The module control script is located on an external site and it is the VirtualHub which is in charge of calling it a regular intervals yoctocontrol php The HTTP callback API uses the VirtualHub which initiates the requests C
269. ternating current For this reason the Yocto Amp provides measures in the shape of a measure of the direct current DC coupled with a measure of the alternating current AC When you measure a current with a Yocto Amp several distinct cases can occur Anon null DC value and a null AC value you are measuring a direct current e A non null AC value and an almost null DC value your are measuring a symmetrical alternating current e Anon null AC value and a non null DC value you are measuring an asymmetrical alternating current Anon null stable DC value and a completely random AC value the appliance connected to the circuit you are measuring does not have a regular consumption The Yocto Amp has a 2 mA 1 v accuracy for direct current However its accuracy for alternating current is less good take into account an error of more or less 5 mA 3 at 50 60hz Below 30Hz the lower the frequency is the less stable the measure is Above 80Hz the higher the frequency is the more underestimated the measure is Note that the AC measure given by the Yocto Amp does not correspond to the current peak amplitude but to the RMS value 10 www yoctopuce com 5 First steps When reading this chapter your Yocto Amp should be connected to your computer which should have recognized it It is time to make it work Go to the Yoctopuce web site and download the Virtual Hub software It is available for Windows Linux and Mac OS X Normal
270. text editor copy the code sample below save it in the same directory as the Yoctopuce library files and then use your preferred web browser to access this page The code is also provided in the directory Examples Doc GettingStarted Yocto Amp of the Yoctopuce library In this example you will recognize the functions explained above but this time used with all side materials needed to make it work nicely as a small demo The example is coded to be used either from a web server or directly by opening the file on the local machine Note that this latest solution does not work with some versions of Internet Explorer in particular IE 9 on Windows 7 which is not able to open network connections when working on a local file In order to use Internet Explorer you should load the example from a web server No such problem exists with Chrome Firefox or Safari 4 if you do not have a text editor use Notepad rather than Microsoft Word 34 www yoctopuce com 9 Using Yocto Amp with Javascript If your Yocto Amp is not connected on the host running the browser replace in the example the address 127 0 0 1 by the IP address of the host on which the Yocto Amp is connected and where you run the VirtualHub lt HTML gt lt HEAD gt lt TITLE gt Hello World lt TITLE gt lt SCRIPT type text javascript src yocto_api js gt lt SCRIPI gt lt SCRIPT type text javascript sre yocto_current js gt lt SCRIPI gt lt SCRIPT language javasc
271. the returned value is not null Below a short example listing the connected modules 88 www yoctopuce com 16 Using the Yocto Amp with Python usr bin python if ae ONS Oea import os sys irom yoctofapi import i errmsg YRefParam Setup the API to use local USB devices if YAPI RegisterHub usb errmsg YAPI SUCCESS sys exit init error str errmsg print Device Mast module YModule FirstModule while module is not None print module get_serialNumber t tmodule get productName module module nextModule E 16 5 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completel
272. the web site or even to install PHP scripts receiving data from a POST HTTP In this case place the PHP script in a subdirectory Limitations This method that allows you to go through NAT filters cheaply has nevertheless a price Communications being initiated by the VirtualHub at a more or less regular interval reaction time to an event is clearly longer than if the Yoctopuce modules were driven directly You can configure the reaction time in the specific window of the Virtua Hub but it is at least of a few seconds in the best case The HTTP callback Yocto API mode is currently available in PHP and Node JS only 10 5 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases Y
273. therwise 222 www yoctopuce com 21 High level API Reference current isOnline_async YCurrent Checks if the current sensor is currently reachable without raising any error asynchronous version function isOnline_async callback context function isOnline_async callback context If there is a cached value for the current sensor in cache that has not yet expired the device is considered reachable No exception is raised if there is an error while trying to contact the device hosting the requested function This asynchronous version exists only in Javascript It uses a callback instead of a return value in order to avoid blocking the Javascript virtual machine Parameters callback callback function that is invoked when the result is known The callback function receives three arguments the caller specific context object the receiving function object and the boolean result context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback www yoctopuce com 223 21 High level API Reference current load YCurrent Preloads the current sensor cache with a specified validity duration is__ function load msValidity node js function load msValidity php function load msValidity YRETCODE load int msValidity YRETCODE load int msValidity function load msValidity integer YRETCODE function load
274. tivate the localization beacon lt HTML gt lt HEAD gt lt TITLE gt Module Control lt TITLE gt lt SCRIPT type text javascript sre yocto_api js gt lt SCRIPI gt lt SCRIPT language javascriptl 5 type text JavaScript gt Shs Use explicit error handling rather than exceptions yDisableExceptions Setup the API to use the VirtualHub on local machine if yRegisterHub http 127 0 0 1 4444 YAPI_ SUCCESS ales ti ticannor Contacti VelrtvlalHubmoneliZ7 ORO mat E www yoctopuce com 35 9 Using Yocto Amp with Javascript var module function refresh var serial document getElementById serial value if serial Detect any conected module suitable for the demo module yFirstModule nextModule if module serial module get_serialNumber document getElementBylId serial value serial module yFindModule serial if module isOnline document getHlementBylId msg value Var sem ser lall se emocdullc geese ra clNumioers O lt pri html logical name module get_logicalName lt br gt html luminosity t module get_luminosity lt br gt html beacon if module get_beacon Y_BEACON_ ON html 0N lt a href javascript beacon Y BEACON OFF gt switch off lt a gt lt br gt else html OFF lt a href javascript beacon Y BEACON ON gt switch on lt a gt lt br gt html upTime parseInt module get_upT
275. to the current measured value On failure throws an exception or returns Y_CURRENTVALUE_INVALID YCurrent 204 www yoctopuce com 21 High level API Reference current get_errorMessage YCurrent current errorMessage Returns the error message of the latest error with the current sensor function get_errorMessage function get_errorMessage function get_errorMessage string get_errorMessage NSString errorMessage function get_errorMessage string function get_errorMessage As String string get_errorMessage String get_errorMessage def get_errorMessage This method is mostly useful when using the Yoctopuce library with exceptions disabled Returns a string corresponding to the latest error message that occured while using the current sensor object www yoctopuce com 205 21 High level API Reference current get_errorType YCurrent current errorType Returns the numerical error code of the latest error with the current sensor function get_errorType function get_errorType function get_errorType YRETCODE get_errorType function get_errorType YRETCODE function get_errorType As YRETCODE YRETCODE get_errorType int get_errorType def get_errorType This method is mostly useful when using the Yoctopuce library with exceptions disabled Returns a number corresponding to the code of the latest error that occured while usin
276. topuce com 11 5 First steps See YAMPMK01 045A1 is a 20x56mm board with an isolated current sensor aka ammeter Kernel Serial YAMPMKO1 045A1 Product name Yocto Amp Logical name Product release 1 Firmware 6361 Consumption 89 mA Beacon Inactive mon Luminosity 50 Sensors DC AC Current current OmA 0 mA Min current 0 mA 0 mA Max current OmA 0 mA Misc Open API browser pop up Get user manual from yoctopuce com close Properties of the Yocto Amp module This windows allows you among other things to play with your module to check that it is working correctly as measured values are displayed in real time 5 3 Configuration When in the module list you click on the configure button corresponding to your module the configuration window is displayed YAMPMK01 045A1 Edit parameters for device YAMPMK01 045A1 and click on the Save button Serial YAMPMKO1 045A1 Product name Yocto Amp Firmware 6361 Grade Logical name Luminosity i signal leds only Device functions Each function of the device has a physical name and a logical name You can change the logical name using the rename button YAMPMK01 045A1 current1 YAMPMK01 045A1 current2 YAMPMK01 045A1 dataLogger A nar H 3 2 Save Cancel Yocto Amp module configuration Firmware The module firmware can easily be updated with the help of the interface To do so you must
277. tring get_logFrequency def get_logFrequency YCurrent target get_logFrequency Returns a string corresponding to the datalogger recording frequency for this function or OFF when measures are not stored in the data logger flash memory On failure throws an exception or returns Y_LOGFREQUENCY_INVALID 212 www yoctopuce com 21 High level API Reference current get_logicalName YCurrent current logicalName Returns the logical name of the current sensor function get_logicalName function get_logicalName function get_logicalName string get_logicalName NSString logicalName function get_logicalName string function get_logicalName As String string get_logicalName String get_logicalName def get_logicalName YCurrent target get_logicalName Returns a string corresponding to the logical name of the current sensor On failure throws an exception or returns Y_LOGICALNAME_INVALID www yoctopuce com 213 21 High level API Reference current get_lowestValue current lowestValue Returns the minimal value observed function get_lowestValue function get_lowestValue function get_lowestValue double get_lowestValue double lowestValue function get_lowestValue function get_lowestValue double get_lowestValue double get_lowestValue def get_lowestValue YCurrent target get_lowestValue double As Double es Returns
278. u can disable either of them individually but if you enable both timed report callbacks and logging for a given function the two will work at the same frequency Retrieving the data To load recorded measures from the Yocto Amp flash memory you must call the get _recordedData method of the desired sensor and specify the time interval for which you want to retrieve measures The time interval is given by the start and stop UNIX timestamp You can also specify 0 if you don t want any start or stop limit The get_recordedData method does not return directly am array of measured values since in some cases it would cause a huge load that could affect the responsiveness of the application Instead this function will return an YDataSet object that can be used to retrieve immediately an overview of the measured data summary and then to load progressively the details when desired Here are the main methods used to retrieve recorded measures dataset sensor get_recordedData 0 0 select the desired time interval dataset loadMore load data from the device progressively dataset get_summary get a single measure summarizing the full time interval dataset get_preview get an array of measures representing a condensed version of the whole set of measures on the selected time interval reduced by a factor of approx 200 dataset get_measures get an array with all detailled measures that grows while loadMo re is being called repeteadly
279. ule ger beacon Dk sw setChecked module getBeacon YModule BEACON_ON field TextView findViewById R id logs ELteldvscihext module gevslasthogsi i catch DIARI METLE E e printStackTrace Override public void onItemSelected AdapterView lt gt parent View view int pos long id String hwid parent getItemAtPosition pos toString module YModule FindModule hwid DisplayModuleInfo Override public void onNothingSelected AdapterView lt gt arg0 public void refreshInfo View view www yoctopuce com 103 18 Using the Yocto Amp with Android DisplayModulelInfo public void toggleBeacon View view if module null eeu my boolean on Switch view isChecked try 3f on ff module setBeacon YModule BEACON_ ON else module setBeacon YModule BEACON OFF leneiela MONETTE InSeyoieakoum i 5 e printStackTrace Each property xxx of the module can be read thanks to a method of type YModule get xxxx and properties which are not read only can be modified with the help of the YModule set xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding YModule set xxx function However this modification is performed only in the random access memory RAM of the module
280. ule get_productName Pecatch VAP Ex cepinlon sex 5 break module module nextModule YAPI FreeAPI 17 4 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library www yoctopuce com 95 17 Using the Yocto Amp with Java The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to i1sOnline and which could crash the software In the Java API error handling is implemented with exceptions Therefore you must catch and handle correctly all exceptions that might be thrown by the API if you do not want your software to crash as soon as you unplug a device 96 www yoctopuce com 18 Using the Yocto A
281. umber of times the module was powered on with the dataLogger enabled at some point On failure throws an exception or returns Y_CURRENTRUNINDEX_INVALID 246 www yoctopuce com 21 High level API Reference datalogger get_dataSets YDataLogger datalogger dataSets Returns a list of YDataSet objects that can be used to retrieve all measures stored by the data logger function get_dataSets function get_dataSets function get_dataSets vector lt YDataSet gt get_dataSets NSMutableArray dataSets function get_dataSets TYDataSetArray function get_dataSets As List List lt YDataSet gt get_dataSets ArrayList lt YDataSet gt get_dataSets def get_dataSets YDataLogger target get_dataSets This function only works if the device uses a recent firmware as YDataSet objects are not supported by firmwares older than version 13000 Returns a list of YDataSet object On failure throws an exception or returns an empty list www yoctopuce com 247 21 High level API Reference datalogger get_dataStreams YDataLogger datalogger dataStreams Builds a list of all data streams hold by the data logger legacy method function get_dataStreams v function get_dataStreams v function get_dataStreams amp v cpp int get_dataStreams int dataStreams NSArray v function get_dataStreams v Tlist integer procedure get_dataStreams ByVal v As List in
282. ument in the userData attribute of the function function set_userData data function set_userData data function set_userData data void set_userData void data void setUserData void data procedure set_userData data Tobject procedure set_userData ByVal data As Object void set_userData object data void set_userData Object data def set_userData data This attribute is never touched by the API and is at disposal of the caller to store a context Parameters data any kind of object to be stored 192 www yoctopuce com 21 High level API Reference module triggerFirmwareUpdate Schedules a module reboot into special firmware update mode function triggerFirmwareUpdate secBeforeReboot function triggerFirmwareUpdate secBeforeReboot function triggerFirmwareUpdate secBeforeReboot int triggerFirmwareUpdate int secBeforeReboot int triggerFirmwareUpdate int secBeforeReboot function triggerFirmwareUpdate secBeforeReboot Longint Longint function triggerFirmwareUpdate As Integer int triggerFirmwareUpdate int secBeforeReboot int triggerFirmwareUpdate int secBeforeReboot def triggerFirmwareUpdate secBeforeReboot YModule target triggerFirmwareUpdate secBeforeReboot YModule Parameters secBeforeReboot number of seconds before rebooting Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code
283. unctionName int functionIndex def functionName functionIndex Parameters functionIndex the index of the function for which the information is desired starting at O for the first function Returns a string corresponding to the logical name of the requested module function On failure throws an exception or returns an empty string www yoctopuce com 159 21 High level API Reference module functionValue YModule Retrieves the advertised value of the nth function on the module function functionValue functionIndex function functionValue functionIndex function functionValue functionIndex string functionValue int functionIndex NSString functionValue int functionIndex function functionValue functionIndex integer string function functionValue ByVal functionIndex As Integer As String string functionValue int functionindex def functionValue functionIndex Parameters functionIndex the index of the function for which the information is desired starting at O for the first function Returns a short string up to 6 characters corresponding to the advertised value of the requested module function On failure throws an exception or returns an empty string 160 www yoctopuce com 21 High level API Reference module get_beacon module gt beacon Returns the state of the localization beacon function get_beacon function get_beacon function get_
284. unning you obtain the list of the connected modules http 127 0 0 1 4444 api services whitePages txt www yoctopuce com 119 20 Using with unsupported languages Note that the result is displayed as text but if you request whitePages xml you obtain an XML result Likewise whitePages json allows you to obtain a JSON result The html extension even allows you to display a rough interface where you can modify values in real time The whole REST API is available in these different formats Driving a module through the REST interface Each Yoctopuce module has its own REST interface available in several variants Let us imagine a Yocto Amp with the YAMPMK01 12345 serial number and the myModule logical name The following URL allows you to know the state of the module http 127 0 0 1 4444 bySerial YAMPMK01 12345 api module txt You can naturally also use the module logical name rather than its serial number http 127 0 0 1 4444 byName myModule api module txt To retrieve the value of a module property simply add the name of the property below module For example if you want to know the signposting led luminosity send the following request http 127 0 0 1 4444 bySerial YAMPMK01 12345 api module luminosity To change the value of a property modify the corresponding attribute Thus to modify the luminosity send the following request http 127 0 0 1 4444 bySerial YAMPMK01 12345 api module luminosity 100 Driving the module
285. usage argv 0 module logicalName newname module saveToFlash NSLog Current name n module logicalName oO es n oO NSLog not connected check identification and USB cable n serial or name 62 www yoctopuce com 12 Using Yocto Amp with Objective C Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the saveToF lash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not NULL Below a short example listing the connected modules import lt Foundation Foundation h gt import yocto_api h int Main Yin arge const cher arg NSError Verro autoreleasepool Setup the API to use local USB devices if yRegisterHub usb amp error YAPT SUCCESS NSLog RegisterHub error n error localizedDescription return 1 NSLog Device list n YModule module
286. value between 0 and 100 Remember to call the saveToFlash method of the module if the modification must be kept Parameters newval an integer corresponding to the luminosity of the module informative leds Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code 190 www yoctopuce com 21 High level API Reference module set_usbBandwidth YModule module setUsbBandwidth Changes the number of USB interfaces used by the module function set_usbBandwidth newval function set_usbBandwidth newval function set_usbBandwidth newval int set_usbBandwidth Y_USBBANDWIDTH_enum newval int setUsbBandwidth Y_USBBANDWIDTH_enum newval function set_usbBandwidth newval Integer integer function set_usbBandwidth ByVal newval As Integer As Integer int set_usbBandwidth int newval int set_usbBandwidth int newval def set_usbBandwidth newval YModule target set_usbBandwidth newval You must reboot the module after changing this setting Parameters newval either Y_USBBANDWIDTH_SIMPLE or Y_USBBANDWIDTH_DOUBLE according to the number of USB interfaces used by the module Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 191 21 High level API Reference module set_userData YModule module setUserData Stores a user context provided as arg
287. veToFlash function saveToFlash function saveToFlash int saveToFlash int saveToFlash function saveToFlash Longint function saveToFlash As Integer int saveToFlash int saveToFlash def saveToFlash YModule target saveToFlash YModule Warning the number of allowed save operations during a module life is limited about 100000 cycles Do not call this function within a loop Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 187 21 High level API Reference module set_beacon YModule module setBeacon Turns on or off the module localization beacon function set_beacon newval function set_beacon newval function set_beacon newval int set_beacon Y_BEACON_enum newval int setBeacon Y_BEACON_enum newval function set_beacon newval Integer integer v function set_beacon ByVal newval As Integer As Integer int set_beacon int newval int set_beacon int newval def set_beacon newval YModule target set_beacon newval Parameters newval either Y_BEACON_OFF or Y_BEACON_ON Returns YAPI SUCCESS if the call succeeds On failure throws an exception or returns a negative error code 188 www yoctopuce com 21 High level API Reference module set_logicalName YModule module gt setLogicalName Changes the logical name of the module fu
288. was obtained through yapiGetAllDevices infos points to a data structure in which the result is stored This data structure has the following format Name Type bytes Pescription vendorid int 4 Yoctopuce USB ID deviceid int 4 Module USB ID devrelease int 4 Module version nbinbterfaces int 4 Number of USB interfaces used by the module manufacturer char 20 Yoctopuce null terminated productname char 28 Model null terminated serial char 20 Serial number null terminated logicalname char 20 Logical name null terminated firmware char 22 Firmware version null terminated beacon byte 1 Beacon state 0 1 The errmsg parameter must point to a 255 character buffer to retrieve a potential error message Here is a sample program written in pascal using the yapi di DLL to list the connected modules device description structure type yDeviceSt packed record vendorid word deviceid word devrelease Word nbinbterfaces word manufacturer Tarca ile 5 iUS wae Euaisalelnener productname Tarca MOG aA Tene ans ehar serial ar cay ils SRo ansieae logicalname Tar cay Onm Tomor ane echar firmware Aar cay O elokans ehan beacon EOCEEN end DII function import function function function function var errmsgBu dataBuff errmsg d neededsi devinfos begin errmsg hf APT if yapi begin write yapilInitAPI mode integer errmsg pansichar integer cdecl external yapi dill name
289. way the errors indicated by the library The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to i1sOnline and which could crash the software In the Java API for Android error handling is implemented with exceptions Therefore you must catch and handle correctly all exceptions that might be thrown by the API if you do not want your software to crash soon as you unplug a device www yoctopuce com 107 108 www yoctopuce com 19 Advanced programming The preceding chapters have introduced in each available language the basic programming functions which can be used with your Yocto Amp module This chapter presents in a more generic manner a more advanced use of your module Examples are provided in the language which is the most popular among Yoctopuce customers that is C Nevertheless you can find complete examples illustrating the concepts presented here in the programming libraries of each language To remain as concise as possible examples provided in this chapter do not perform any error handling Do not copy them as i
290. xt to the Yoctopuce Library YAPI EnableUSBHost this Pacatch YAP TER xceptaon 1e i Log e Yocto e getLocalizedMessage Autorun It is possible to register your application as a default application for a USB module In this case as soon as a module is connected to the system the application is automatically launched You must add lt action android name android hardware usb action USB_DEVICE_ATTACHED gt in the section lt intent filter gt of the main activity The section lt activity gt must have a pointer to an XML file containing the list of USB modules which can run the application lt manifest xmlns android http schemas android com apk res android lt uses feature android name android hardware usb host gt lt application lt activity android name MainActivity gt lt intent filter gt lt action android name android intent action MAIN gt lt action android name android hardware usb action USB DEVICE ATTACHED gt lt category android name android intent category LAUNCHER gt lt intent filter gt lt meta data android name android hardware usb action USB DEVICE ATTACHED android resource xml device filter gt 7 E lt activity gt lt application gt lt manifest gt The XML file containing the list of modules allowed to run the application must be saved in the res xml directory This file contains a list of USB vendorld and devicelD in decimal The following exam
291. y refValues function calibrateFromPoints rawValues TDoubleArray refValues TDoubleArray LongInt procedure calibrateFromPoints int calibrateFromPoints List lt double gt rawValues List lt double gt refValues int calibrateFromPoints ArrayList lt Double gt rawValues ArrayList lt Double gt refValues def calibrateFromPoints rawValues refValues Y Current target calibrateFromPoints rawValues refValues It is possible to configure up to five correction points Correction points must be provided in ascending order and be in the range of the sensor The device will automatically perform a linear interpolation of the error correction between specified points Remember to call the saveToFlash method of the module if the modification must be kept For more information on advanced capabilities to refine the calibration of sensors please contact support yoctopuce com Parameters rawValues array of floating point numbers corresponding to the raw values returned by the sensor for the correction points refValues array of floating point numbers corresponding to the corrected 200 www yoctopuce com 21 High level API Reference current describe YCurrent Returns a short text that describes the current sensor in the form TYPE NAME SERIAL FUNCTIONID function describe function describe function describe string describe NSString describe function describe string function d
292. y exclude an error which would occur after the call to isOnline and which could crash the software The only way to prevent this is to implement one of the two error handling techniques described below The method recommended by most programming languages for unpredictable error handling is the use of exceptions By default it is the behavior of the Yoctopuce library If an error happens while you try to access a module the library throws an exception In this case there are three possibilities e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the most desirable the Yoctopuce library offers another possibility for error handling allowing you to create a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get _state method returns a Y STATE INVALID value
293. y so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software The only way to prevent this is to implement one of the two error handling techniques described below The method recommended by most programming languages for unpredictable error handling is the use of exceptions By default it is the behavior of the Yoctopuce library If an error happens while you try to access a module the library throws an exception In this case there are three possibilities e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the most desirable the Yoctopuce library offers another possibility for error handling allowing you to create a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each fun
294. yUnregisterHub url Setup the Yoctopuce library to no more use modules connected on a previously registered machine with RegisterHub yUpdateDeviceList errmsg Triggers a re detection of connected Yoctopuce modules yUpdateDeviceList_async callback context Triggers a re detection of connected Yoctopuce modules www yoctopuce com 127 21 High level API Reference YAPI CheckLogicalName YAPI yCheckLogicalName Checks if a given string is valid as logical name for a module or a function function yCheckLogicalName name node js function CheckLogicalName name function yCheckLogicalName name bool yCheckLogicalName const string amp name BOOL yCheckLogicalName NSSiring name function yCheckLogicalName name string boolean function yCheckLogicalName ByVal name As String As Boolean bool CheckLogicalName string name boolean CheckLogicalName String name def CheckLogicalName name A valid logical name has a maximum of 19 characters allamongA 2Z a z 0 9 _ and If you try to configure a logical name with an incorrect string the invalid characters are ignored Parameters name a string containing the name to check Returns true if the name is valid false otherwise 128 www yoctopuce com 21 High level API Reference YAPI DisableExceptions YAPI yDisableExceptions Disables the use of exceptions to report runtime errors function yDisableExceptions function
295. yapialInitAPI yapiUpdateDeviceList force integer errmsg pansichar integer cdecl external yapi dll name yapiUpdateDeviceList yapiGetAllDevices buffer pointer marsoire Integer var neededsize amteger errmsg ipansi chank integer edecls external yapi diMi name yapirGetAlNDevicest apiGetDeviceInfo d integer var infos yDeviceSt errmsg pansuchar ianteqes sedeci external yapi dill name yapiGetDevicelInfo Prerak array Oo o2ekei Cie ans tehar er array oiler tehie aluslicteveisie max of 128 USB devices ata pansichar ze i integer yDeviceSt errmsgBuffer initialization InitAPI 1 errmsg lt 0 then in errmsg www yoctopuce com 123 20 Using with unsupported languages Halt end forces a device inventory if yapiUpdateDeviceList 1 errmsg lt 0 then begin writeln errmsg Walt end loads all device handles into dataBuffer if yapiGetAllDevices dataBuffer sizeof dataBuffer neededsize errmsg lt 0 then begin writeln errmsg halt end gets device info from each handle for i 0 to neededsize div sizeof integer 1 do begin if apiGetDevicelInfo dataBuffer i devinfos errmsg lt 0 then begin writeln errmsg halt end writeln pansichar devinfos serial tpansichar devinfos productname end end 20 4 Porting the high level library As all the sources of the Yoctopuce API are fully provided you can very well por
Download Pdf Manuals
Related Search
Related Contents
Universal Remote Control UR5U-BH8000 User's Manual Softstarter EURA® HFR-1000 Dacor ERWD27 Food Warmer User Manual Architectures à vivre هبتنإ - Uğur Soğutma Makineleri m - Thebaïde Geneva Mountech AJL22B mounting kit User Manual - PlayBetter.com Copyright © All rights reserved.
Failed to retrieve file