Reklama
Reklama
Yocto-Amp, User's guide
Table of contents
1. Introduction
..............................................................................................................................
1
.................................................................................................................
1.2. Electrocution Prevention Advices
.........................................................................................
......................................................................................................
2. Presentation
.............................................................................................................................
5
................................................................................................................
..................................................................................................................
...................................................................................................................
............................................................................................................
3. Direct current vs. alternating current
.........................................................................
9
4. First steps
...............................................................................................................................
11
.......................................................................................................................
....................................................................................................
.........................................................................................................................
..............................................................................................................
............................................................................................................................................
5. Assembly and connections
..........................................................................................
15
..................................................................................................................................
........................................................................................................................
...............................................................................................................................
.......................................................................................................
6. Programming, general concepts
................................................................................
19
......................................................................................................
......................................................................................................
.....................................................................................................
6.4. Current function interface
...................................................................................................
6.5. DataLogger function interface
.............................................................................................
6.6. What interface: Native, DLL or Service ?
............................................................................
6.7. Programming, where to start?
.............................................................................................
7. Using the Yocto-Amp in command line
..................................................................
29
..............................................................................................................................
.....................................................................................................
7.3. Control of the Current function
............................................................................................
7.4. Control of the module part
..................................................................................................
...........................................................................................................................
8. Using Yocto-Amp with JavaScript / EcmaScript
...............................................
33
8.1. Blocking I/O versus Asynchronous I/O in JavaScript
..........................................................
8.2. Using Yoctopuce library for JavaScript / EcmaScript 2017
.................................................
8.3. Control of the Current function
............................................................................................
8.4. Control of the module part
..................................................................................................
.....................................................................................................................
9. Using Yocto-Amp with PHP
..........................................................................................
43
......................................................................................................................
9.2. Control of the Current function
............................................................................................
9.3. Control of the module part
..................................................................................................
9.4. HTTP callback API and NAT filters
.....................................................................................
.....................................................................................................................
10. Using Yocto-Amp with C++
........................................................................................
53
10.1. Control of the Current function
..........................................................................................
10.2. Control of the module part
................................................................................................
...................................................................................................................
10.4. Integration variants for the C++ Yoctopuce library
............................................................
11. Using Yocto-Amp with Objective-C
.......................................................................
61
11.1. Control of the Current function
..........................................................................................
11.2. Control of the module part
................................................................................................
...................................................................................................................
12. Using Yocto-Amp with Visual Basic .NET
..........................................................
67
.........................................................................................................................
12.2. Using the Yoctopuce API in a Visual Basic project
...........................................................
12.3. Control of the Current function
..........................................................................................
12.4. Control of the module part
................................................................................................
...................................................................................................................
13. Using Yocto-Amp with C#
...........................................................................................
73
.........................................................................................................................
13.2. Using the Yoctopuce API in a Visual C# project
...............................................................
13.3. Control of the Current function
..........................................................................................
13.4. Control of the module part
................................................................................................
...................................................................................................................
14. Using Yocto-Amp with Delphi
...................................................................................
81
.......................................................................................................................
14.2. Control of the Current function
..........................................................................................
14.3. Control of the module part
................................................................................................
...................................................................................................................
15. Using the Yocto-Amp with Python
.........................................................................
87
.......................................................................................................................
.................................................................................................................
15.3. Control of the Current function
..........................................................................................
15.4. Control of the module part
................................................................................................
...................................................................................................................
16. Using the Yocto-Amp with Java
...............................................................................
93
....................................................................................................................
16.2. Control of the Current function
..........................................................................................
16.3. Control of the module part
................................................................................................
...................................................................................................................
17. Using the Yocto-Amp with Android
.......................................................................
99
17.1. Native access and VirtualHub
...........................................................................................
....................................................................................................................
.....................................................................................................................
17.4. Activating the USB port under Android
...........................................................................
17.5. Control of the Current function
........................................................................................
17.6. Control of the module part
..............................................................................................
.................................................................................................................
18. Advanced programming
............................................................................................
111
........................................................................................................
...............................................................................................................
...........................................................................................................
19. Firmware Update
............................................................................................................
121
19.1. The VirtualHub or the YoctoHub
.....................................................................................
19.2. The command line library
................................................................................................
19.3. The Android application Yocto-Firmware
........................................................................
19.4. Updating the firmware with the programming library
......................................................
.........................................................................................................
20. Using with unsupported languages
....................................................................
125
.................................................................................................................
.............................................................................................
...................................................................................................
20.4. Porting the high level library
...........................................................................................
21. High-level API Reference
..........................................................................................
131
............................................................................................................
21.2. Module control interface
.................................................................................................
21.3. Current function interface
...............................................................................................
21.4. DataLogger function interface
.........................................................................................
................................................................................................
..............................................................................................................
22. Troubleshooting
.............................................................................................................
343
...............................................................................................................
................................................................................................................
22.3. ARM Platforms: HF and EL
.............................................................................................
22.4. Powered module but invisible for the OS
........................................................................
22.5. Another process named xxx is already using yAPI
.........................................................
22.6. Disconnections, erratic behavior
.....................................................................................
.............................................................................................................
23. Characteristics
................................................................................................................
347
...................................................................................................................................
Index
.............................................................................................................................................
351
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 measuring part is electrically isolated from the USB part. This makes it possible to measure electric loads that do not share the same ground reference as the computer USB bus.
When mounted in a proper protective enclosure, the Yocto-Amp can eve be used to measure the current consumption on appliances connected directly to the mains, because it features a safety insulation of 3kV between the USB interface and the measuring part. Caution, make sure to read carefully the safety recommendations below and the section describing the electric insulation before connecting the Yocto-Amp to a mains powered appliance.
The Yocto-Amp module
The Yocto-Amp is intended to be used as laboratory equipment, or as industrial process-control equipment, but also for similar applications in domestic and commercial environments
1
.
Yoctopuce thanks you for 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
1 i.e. the scope of IEC 61010-1:2010 international standard
www.yoctopuce.com
1
1. Introduction
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
2
.
1.1. Safety Information
Caution: The Yocto-Amp is not certified for use in hazardous locations, explosive environments, or life-threatening applications.
Caution: The Yocto-Amp is not certified for use in medical environments or lifesupport applications.
Hot surface When large currents flow through the device, the PCB and some components may become hot. Touching the device may result in bodily injury.
When continuous exposure to large currents is expected, pay attention to burns and fire hazard prevention. A fan may be used to help cooling, but the system should remain safe even with the fan inoperative.
Electrical shock Voltages at or above 60 V DC or 30 V AC r.m.s. create electrocution hazards. Since the Yocto-Amp has bare contacts, you should not connect it to hazardous voltage without using a proper enclosure, electrically insulated from human contact. A few extra precautions are required, that we have summarized in the paragraph below.
1.2. Electrocution Prevention Advices
The Yocto-Amp can be used without risk with voltages up to 250 V AC r.m.s., as long as you adhere to a few safety guidelines and apply common sense. In order to help you to avoid an embarrassing nomination to the Darwin Awards or a charge for negligent homicide, we have summarized a few recommendations below:
• To attach the device, use non-conductive plastic screw and spacers. Fixing holes are under the safety clearance distance, so metal screw would be dangerous.
• Put the Yocto-Amp in a proper insulated enclosure before applying hazardous voltage. Doing it afterwards is no more possible. Conversely, make sure all hazardous wires are not live
before opening the enclosure.
• Ensure that no object or liquid may accidentally enter into the enclosure.
• Ensure that all wires are firmly hold in the terminal block, and that no strand escapes from the terminal block in case you use stranded cable.
• Check that all circuit connections are in accordance to the isolation voltage levels described in the Yocto-Amp description (see next chapter). USB and Ethernet wires are well separated from any wire with a hazardous voltage.
• Don't work if you are tired. Brilliant decisions taken at 2 a.m. tend to lose their shine at first light.
• Don't work alone. If things go bad, you can then hope to be rescued fast enough.
• Use your head, your luck won't last forever.
• Hazardous voltage wiring is subject to local electrical standards. Some tasks may only be performed by qualified personnel.
2
www.yoctopuce.com
1. Introduction
1.3. Environmental conditions
The safety isolation of the Yocto-Amp has been designed for indoor use in a standard office or laboratory environment (IEC 60664 pollution degree 2): air pollution is expected to be limited and mainly non-conductive. Relative humidity is expected to be between 10% and 90% RH, non
condensing. Use in environment with significant solid pollution or conductive pollution is not safe, unless the device is protected from such pollution using an IP67 or IP68 enclosure, which should only be opened in an unpolluted environment.
The Yocto-Amp can be used on the whole specified voltage and current range without risk under normal temperature conditions according to IEC61010-1, i.e. 5°C to 40°C. The Yocto-Amp is also designed to be usable on an extended temperature range, from -30°C to 85°C, but only when specific conditions are met to ensure safety: when the temperature sinks, there must not be condensing humidity on the device; when the temperature rise, in case the device is used with strong voltages, the ambiant temperature around heat dissipating elements must stay stable.
The Yocto-Amp is designed to protect from electrocution hazards caused by temporary overvoltage expected on wall outlets (Overvoltage Category II). It has not been designed for use in fixed installation and for industrial use with permanent connection to the fixed distribution circuit.
The Yocto-Amp safety isolation was designed for use up to altitude 2000m.
www.yoctopuce.com
3
4 www.yoctopuce.com
2. Presentation
1: Micro-B USB socket 4: Measure resistance
2: Yocto-button
3: Yocto-led
5: Measure input (negative)
6: Measure input (positive)
2.1. Common elements
All Yocto-modules share a number of common 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 UI-based method to update the firmware, but this one works even in case of severely damaged firmware.
www.yoctopuce.com
5
2. Presentation
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.
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 localization 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
2
.
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 YAMPMK01. 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 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 .
To measure the current, the Yocto-Amp uses a metal shunt (a 5 mOhm resistor
3
), located between the two connectors. As the current increases, the temperature of the shunt rises as well. The shunt is designed to be self-cooled by convective heat transfer. At 16 Amps, the PCB and shunt temperature may rise above 60°C
4
. This is the expected behaviour for the shunt to dissipate power. However, for the convective heat transfer to work properly with high amperage, you should make sure that the
Yocto-Amp is kept in a position such that air can easily flow. If you use the device in an enclosure, make sure the enclosure is properly vented, to ensure proper operation of the device and prevent fire hazards. For a continuous use above 10 Amps, the use of a small fan is recommended. But don't forget that in any case your system should be designed to prevent any fire risk even in case of failure of the fan (single abnormal condition).
6
1 short-short-short long-long-long short-short-short
3
5 mOhm shunt starting from Revision B. Earlier revisions used a 10 mOhm shunt.
4
60°C starting from Revision B. The shunt temperature on earlier revisions may rise above 120°C.
www.yoctopuce.com
2. Presentation
2.3. Safety insulation
The Yocto-Amp is designed as two distincts electrical circuits, separated by a reinforced insulation
5
.
This insulation plays an essential role for the safety of system users.
Yocto-Amp safety insulation
On the one side of the insulation where the USB connector can be found, components connectors and cables connected to the system can be accessible to the user without risk: the circuit power supply is floating, protected by a double insulation or a reinforced insulation, and voltage levels are below 6V (Safety Extra Low Voltage).
On the other side with the terminal blocks, connected cables may carry hazardous live voltage, depending on the application. So unless you are only connecting to non-hazardous voltage, make sur that no conductive object is brought nearer than 3mm from the hazardous side of the
device, even accidentally. Pay attention to the following items:
• To fix the Yocto-Amp on the hazardous side, use insulating plastic screw and spacers
only. You will find PPS / PEEK screw and spacers on Yoctopuce shop, that are resistant to high temperatures.
• If you intend to use a metal enclosure, make sure it does not come nearer than 3mm from the dangerous side of the Yocto-Amp.
The specifications of the safety insulation are as follows:
• Test voltage: 3kV
• Clearance distance: 3mm
• Creepage distance: 3mm
• Material group: Cat I (SHENGYI S1600, CTI > 600)
2.4. 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 favorite 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 3mm assembly holes, with a screw head no larger than 8mm. 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 in 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
5
This description of the insulation applies starting at revision B of the product. Earlier revisions of the product only had a functional insulation.
www.yoctopuce.com
7
2. Presentation
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, YoctoHub-Wireless and YoctoHub-GSM
You can add network connectivity to your Yocto-Amp, thanks to the YoctoHub-Ethernet, the
YoctoHub-Wireless and the YoctoHub-GSM which provides repectiveley Ethernet, WiFi and GSM connectivity. All of them can drive up to three devices and behave exactly like a regular computer running a VirtualHub.
1.27mm (or 1.25mm) connectors
In case you wish to connect your Yocto-Amp to a Micro-hub USB or a YoctoHub without using a bulky USB connector, you can use the four 1.27mm pads just behind the USB connector. There are two options.
You can mount the Yocto-Amp directly on the hub using screw and spacers, and connect it using
1.27mm board-to-board connectors. To prevent shortcuts, it is best to solder the female connector on the hub and the male connector on the Yocto-Amp.
You can also use a small 4-wires cable with a 1.27mm connector. 1.25mm works as well, it does not make a difference for 4 pins. This makes it possible to move the device a few inches away. Don't put it too far away if you use that type of cable, because as the cable is not shielded, it may cause undesirable electromagnetic emissions.
Enclosure
Your Yocto-Amp has been designed to be installed as is in your project. Nevertheless, Yoctopuce sells enclosures specifically designed for Yoctopuce devices. More details are available on the
Yoctopuce web site
6
. 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
8
6 http://www.yoctopuce.com/EN/products/category/enclosures
www.yoctopuce.com
3. 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
9
3. Direct current vs. alternating current
Asymmetrical alternating current. It's the sum of a direct current and an alternating 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:
• A non null DC value and a null AC value: you are measuring a direct current.
• A non null AC value and an almost null DC value: your are measuring a symmetrical alternating current.
• A non null AC value and a non null DC value: you are measuring an asymmetrical alternating current.
• A non 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
4. First steps
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.
4.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
1
provided with every operating system.
Windows versions currently supported are: Windows XP, Windows 2003, Windows Vista, Windows
7, Windows 8 and Windows 10. Both 32 bit and 64 bit versions are supported. Yoctopuce is frequently testing its modules on Windows 7 and Windows 10.
Mac OS X versions currently supported are: 10.9 (Maverick), 10.10 (Yosemite), 10.11 (El Capitan) and 10.12 (Sierra). Yoctopuce is frequently testing its modules on Mac OS X 10.11.
Linux kernels currently supported are the 2.6 branch, the 3.0 branch and the 4.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 3.19.
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
1
The HID driver is the one that takes care of the mouse, the keyboard, etc.
www.yoctopuce.com
11
4. First steps
connect mobile phones, as long as they do not exhibit an apple logo. All USB modules manufactured by Yoctopuce use micro size connectors.
The most common USB 2 connectors: A, B, Mini B, Micro A, Micro B.
2
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 name 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.
4.2. Testing USB connectivity
At this point, 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
3
. It is available for Windows,
Linux, and Mac OS X. Normally, 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
4
. 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.
12
2
Although they existed for some time, Mini A connectors are not available anymore http://www.usb.org/developers/
Deprecation_Announcement_052507.pdf
3
4 www.yoctopuce.com/EN/virtualhub.php
The interface is tested on Chrome, FireFox, Safari, Edge et IE 11.
www.yoctopuce.com
4. First steps
Module list as displayed in your web bowser.
4.3. 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.
4.4. 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.
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.
4.5. Configuration
When, in the module list, you click on the configure button corresponding to your module, the configuration window is displayed.
www.yoctopuce.com
Yocto-Amp module configuration.
13
4. First steps
Firmware
The module firmware can easily be updated with the help of the interface. 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.
5
However, it is always possible to reprogram the module correctly by using the Virtual Hub software in command line
6
.
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, if 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.
14
5 www.yoctopuce.com/EN/virtualhub.php
6
More information available in the virtual hub documentation
www.yoctopuce.com
5. 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.
5.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 contains 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 insulating tape should be enough.
www.yoctopuce.com
15
5. Assembly and connections
5.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 ...
16
... but in series. This is important.
5.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 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.
www.yoctopuce.com
5. Assembly and connections
Heat of the measuring resistance depending on the measured current
5.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 selfpowered 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 savings 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
6. Programming, general concepts
The Yoctopuce API was designed to be at the same time 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.
6.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.
Structure of the Yoctopuce API.
The YSensor class
Each Yoctopuce sensor function has its dedicated class: YTemperature to measure the temperature,
YVoltage to measure a voltage, YRelay to drive a relay, etc. However there is a special class that can do more: YSensor.
www.yoctopuce.com
19
6. Programming, general concepts
The YSensor class is the parent class for all Yoctopuce sensors, and can provide access to any sensor, regardless of its type. It includes methods to access all common functions. This makes it easier to create applications that use many different sensors. Moreover, if you create an application based on YSensor, it will work with all Yoctopuce sensors, even those which do no yet exist.
Programmation
In the Yoctopuce API, priority was put on the ease of access to the module functions by offering the possibility to make abstractions 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.
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.
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.
20 www.yoctopuce.com
6. Programming, general concepts
Functions/Module interaction
From the 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.
6.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.
module : Module attribute
productName serialNumber logicalName productId productRelease firmwareRelease persistentSettings luminosity beacon upTime usbCurrent rebootCountdown userVar
type
String
String
modifiable ?
read-only read-only
String modifiable
Hexadecimal number read-only
Hexadecimal number read-only
String
Enumerated
0..100%
On/Off
Time
Used current (mA)
Integer
Integer read-only modifiable modifiable modifiable read-only read-only modifiable modifiable
current1 : Current current2 : Current attribute
logicalName advertisedValue
String unit currentValue lowestValue
type
String
String
Fixed-point number
Fixed-point number highestValue
Fixed-point number currentRawValue
Fixed-point number logFrequency
Frequency sensorState enabled
modifiable ?
modifiable modifiable read-only read-only modifiable modifiable read-only modifiable reportFrequency
Frequency modifiable calibrationParam
Calibration parameters modifiable resolution
Fixed-point number modifiable
Integer
Boolean read-only modifiable
dataLogger : DataLogger attribute
logicalName advertisedValue currentRunIndex timeUTC recording autoStart beaconDriven clearHistory
type
String
String
Integer
UTC time
Enumerated
On/Off
On/Off
Boolean
modifiable ?
modifiable modifiable read-only modifiable modifiable modifiable modifiable modifiable
www.yoctopuce.com
21
6. Programming, general concepts
22
6.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 YAMPMK01. You can use the serial number to access a given module by software.
logicalName
Character string containing the logical name of the module, 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 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
-
.
productId
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.
userVar
32bit integer variable available for user storage.
www.yoctopuce.com
6. Programming, general concepts
6.4. Current function interface
The Yoctopuce class YCurrent allows you to read and configure Yoctopuce current sensors. It inherits from YSensor class the core functions to read measurements, to register callback functions, to access the autonomous datalogger.
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 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 current value of the current.
unit
Short character string representing the measuring unit for the current.
currentValue
Current value of the current, in mA, as a floating point number.
lowestValue
Minimal value of the current, in mA, as a floating point number.
highestValue
Maximal value of the current, in mA, as a floating point number.
currentRawValue
Uncalibrated, unrounded raw value returned by the sensor, as a floating point number.
logFrequency
Datalogger recording frequency, or "OFF" when measures should not be stored 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).
sensorState
Sensor health state (zero when a current measure is available).
www.yoctopuce.com
23
6. Programming, general concepts
6.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).
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. When the datalogger is enabled but not yet ready to record data, its state is set to PENDING.
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.
beaconDriven
Synchronize the sate of the localization beacon and the state of the data logger. If this attribute is set, it is possible to start the recording with the Yocto-button or the attribute beacon
of the function
YModule. In the same way, if the attribute recording
is changed, the sate of the localization beacon is updated. Note: when this attribute is set the localization beacon pulses slower than usual.
clearHistory
Attribute that can be set to true to clear recorded data.
6.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.
24 www.yoctopuce.com
6. Programming, general concepts
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 DLL. 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.
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 VirtualHub
1
. 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 VirtualHub. The end users will have to start the VirtualHub before running the project control software itself, unless they decide to install the hub as a service/deamon, in which case the VirtualHub starts automatically when the machine starts up.
1 www.yoctopuce.com/EN/virtualhub.php
www.yoctopuce.com
25
6. Programming, general concepts
The application connects itself to the VirtualHub to gain access to the module
The service control method comes 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 machines running VirtualHub.
26
When a VirtualHub 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
C++
Objective-C
Delphi
Python
VisualBasic .Net
C# .Net
EcmaScript / JavaScript
PHP
Java
Java for Android
Command line
Native Native with DLL Virtual hub
✔ ✔ ✔
✔
-
-
-
-
-
-
-
✔
✔
✔
✔
✔
✔
✔
-
-
-
-
-
Support methods for different languages
✔
✔
✔
✔
✔
✔
✔
✔
✔
✔
www.yoctopuce.com
6. Programming, general concepts
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 devices through a
VirtualHub software. The modification is trivial: it is just a matter of parameter change in the yRegisterHub()
call.
6.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
2
. 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
www.yoctopuce.com
27
28 www.yoctopuce.com
7. 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 executables are provided pre-compiled for all the Yoctopuce officially supported platforms/OS. Naturally, the executable sources are also provided
1
.
7.1. Installing
Download the command line API
2
. 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:
C:\> 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.
7.2. Use: general description
All the command line API executables work on the same principle. They must be called the following way
C:\> 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.
1
If you want to recompile the command line API, you also need the C++ API.
2 http://www.yoctopuce.com/EN/libraries.php
www.yoctopuce.com
29
7. 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:
C:\> executable
/help
to know the list of available commands for a given command line API executable, or even:
C:\> executable command
/help
to obtain a detailed description of the parameters of a command.
7.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:
C:\> 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 defined only once, to avoid any ambiguity).
C:\> YCurrent YAMPMK01-123456.current1 describe
C:\> YCurrent YAMPMK01-123456.MyFunction describe
C:\> YCurrent MyModule.current1 describe
C:\> YCurrent MyModule.MyFunction describe
C:\> YCurrent MyFunction describe
To work on all the Current functions at the same time, use the "all" target.
C:\> YCurrent all describe
For more details on the possibilities of the
YCurrent
executable, use:
C:\> YCurrent
/help
7.4. Control of the module part
Each module can be controlled in a similar way with the help of the example, to obtain the list of all the connected modules, use:
YModule
executable. For
30
C:\> YModule inventory
You can also use the following command to obtain an even more detailed list of the connected modules:
www.yoctopuce.com
7. Using the Yocto-Amp in command line
C:\> 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 example: set_xxx()
command. For
C:\> YModule YAMPMK01-12346 set_logicalName MonPremierModule
C:\> YModule YAMPMK01-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 nonvolatile memory. To do so, use the saveToFlash
command. Inversely, it is possible to force the module to forget its current settings by using the revertFromFlash
method.
For example:
C:\> YModule YAMPMK01-12346 set_logicalName MonPremierModule
C:\> YModule YAMPMK01-12346 saveToFlash
Note that you can do the same thing in a single command with the
-s
option.
C:\> 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.
7.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
3 concerned machine, and use the executables of the command line API with the example, if you use:
-r
on the
option. For
C:\> 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, this does not work. But if you run a Virtual Hub, and you give your command in the form:
C:\> 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
8. Using Yocto-Amp with JavaScript / EcmaScript
EcmaScript is the official name of the standardized version of the web-oriented programming language commonly referred to as JavaScript. This Yoctopuce library take advantages of advanced features introduced in EcmaScript 2017. It has therefore been named Library for JavaScript /
EcmaScript 2017 to differentiate it from the previous Library for JavaScript, now deprecated in favor of this new version.
This library provides access to Yoctopuce devices for modern JavaScript engines. It can be used within a browser as well as with Node.js. The library will automatically detect upon initialization whether the runtime environment is a browser or a Node.js virtual machine, and use the most appropriate system libraries accordingly.
Asynchronous communication with the devices is handled across the whole library using Promise objects, leveraging the new EcmaScript 2017 async
/ await
non-blocking syntax for asynchronous
I/O (see below). This syntax is now available out-of-the-box in most Javascript engines. No transpilation is needed: no Babel, no jspm, just plain Javascript. Here is your favorite engines minimum version needed to run this code. All of them are officially released at the time we write this document.
• Node.js v7.6 and later
• Firefox 52
• Opera 42 (incl. Android version)
• Chrome 55 (incl. Android version)
• Safari 10.1 (incl. iOS version)
• Android WebView 55
• Google V8 Javascript engine v5.5
If you need backward-compatibility with older releases, you can always run Babel to transpile your code and the library to older standards, as described a few paragraphs below.
We don't suggest using jspm 0.17
anymore since that tool is still in Beta after 18 month, and having to use an extra tool to implement our library is pointless now that async
/ await
are part of the standard.
8.1. Blocking I/O versus Asynchronous I/O in JavaScript
JavaScript is single-threaded by design. That means, if a program is actively waiting for the result of a network-based operation such as reading from a sensor, the whole program is blocked. In browser environments, this can even completely freeze the user interface. For this reason, the use of blocking
I/O in JavaScript is strongly discouraged nowadays, and blocking network APIs are getting deprecated everywhere.
www.yoctopuce.com
33
8. Using Yocto-Amp with JavaScript / EcmaScript
Instead of using parallel threads, JavaScript relies on asynchronous I/O to handle operations with a possible long timeout: whenever a long I/O call needs to be performed, it is only triggered and but then the code execution flow is terminated. The JavaScript engine is therefore free to handle other pending tasks, such as UI. Whenever the pending I/O call is completed, the system invokes a callback function with the result of the I/O call to resume execution of the original execution flow.
When used with plain callback functions, as pervasive in Node.js libraries, asynchronous I/O tend to produce code with poor readability, as the execution flow is broken into many disconnected callback functions. Fortunately, new methods have emerged recently to improve that situation. In particular, the use of Promise objects to abstract and work with asynchronous tasks helps a lot. Any function that makes a long I/O operation can return a Promise, which can be used by the caller to chain subsequent operations in the same flow. Promises are part of EcmaScript 2015 standard.
Promise objects are good, but what makes them even better is the new async
/ await
keywords to handle asynchronous I/O:
• a function declared async will automatically encapsulate its result as a Promise
• within an async function, any function call prefixed with by await will chain the Promise returned by the function with a promise to resume execution of the caller
• any exception during the execution of an async function will automatically invoke the Promise failure continuation
Long story made short, async and await make it possible to write EcmaScript code with all benefits of asynchronous I/O, but without breaking the code flow. It is almost like multi-threaded execution, except that control switch between pending tasks only happens at places where the await keyword appears.
We have therefore chosen to write our new EcmaScript library using Promises and async functions, so that you can use the friendly await syntax. To keep it easy to remember, all public methods of the EcmaScript library are async, i.e. return a Promise object, except:
•
•
GetTickCount()
, because returning a time stamp asynchronously does not make sense...
FindModule()
,
FirstModule()
, nextModule()
, ... because device detection and enumeration always work on internal device lists handled in background, and does not require immediate asynchronous I/O.
8.2. Using Yoctopuce library for JavaScript / EcmaScript 2017
JavaScript is one of those languages which do not generally allow you to directly access the hardware layers of your computer. Therefore the library can only be used to access network-enabled devices (connected through a YoctoHub), or USB devices accessible through Yoctopuce TCP/IP to
USB gateway, named VirtualHub.
Go to the Yoctopuce web site and download the following items:
• The Javascript / EcmaScript 2017 programming library
1
• The VirtualHub software
2
for Windows, Mac OS X or Linux, depending on your OS
Extract the library files in a folder of your choice, you will find many of examples in it. Connect your modules and start the VirtualHub software. You do not need to install any driver.
Using the official Yoctopuce library for node.js
Start by installing the latest Node.js version (v7.6 or later) on your system. It is very easy. You can download it from the official web site: http://nodejs.org
. Make sure to install it fully, including npm, and add it to the system path.
34
1 www.yoctopuce.com/EN/libraries.php
2 www.yoctopuce.com/EN/virtualhub.php
www.yoctopuce.com
8. Using Yocto-Amp with JavaScript / EcmaScript
To give it a try, go into one of the example directory (for instance example_nodejs/Doc-Inventory).
You will see that it include an application description file (package.json) and a source file (demo.js).
To download and setup the libraries needed by this example, just run: npm install
Once done, you can start the example file using: node demo.js
Using a local copy of the Yoctopuce library with node.js
If for some reason you need to make changes to the Yoctopuce library, you can easily configure your project to use the local copy in the lib/
subdirectory rather than the official npm package. In order to do so, simply type the following command in your project directory: npm link ../../lib
Using the Yoctopuce library within a browser (HTML)
For HTML examples, it is even simpler: there is nothing to install. Each example is a single HTML file that you can open in a browser to try it. In this context, loading the Yoctopuce library is no different from any standard HTML script include tag.
Using the Yoctoluce library on older JavaScript engines
If you need to run this library on older JavaScript engines, you can use Babel
3
to transpile your code and the library into older JavaScript standards. To install Babel with typical settings, simply use: npm instal -g babel-cli npm instal babel-preset-env
You would typically ask Babel to put the transpiled files in another directory, named instance. Your files and all files of the Yoctopuce library should be transpiled, as follow: compat
for babel --presets env demo.js --out-dir compat/ babel --presets env ../../lib --out-dir compat/
Although this approach is based on node.js toolchain, it actually works as well for transpiling
JavaScript files for use in a browser. The only thing that you cannot do so easily is transpiling
JavaScript code embedded directly in an HTML page. You have to use an external script file for using EcmaScript 2017 syntax with Babel.
Babel has many smart features, such as a watch mode that will automatically refresh transpiled files whenever the source file is changed, but this is beyond the scope of this note. You will find more in
Babel documentation.
Backward-compatibility with the old JavaScript library
This new library is not fully backward-compatible with the old JavaScript library, because there is no way to transparently map the old blocking API to the new asynchronous API. The method names however are the same, and old synchronous code can easily be made asynchronous just by adding the proper await
keywords before the method calls. For instance, simply replace: by beaconState = module.
get_beacon () ;
3 http://babeljs.io
www.yoctopuce.com
35
8. Using Yocto-Amp with JavaScript / EcmaScript
36
beaconState = await module.
get_beacon () ;
Apart from a few exceptions, most
XXX_async
redundant methods have been removed as well, as they would have introduced confusion on the proper way of handling asynchronous behaviors. It is however very simple to get an async method to invoke a callback upon completion, using the returned Promise object. For instance, you can replace: by module.
get_beacon_async ( callback, myContext ) ; module.
get_beacon () .
then (function( res ) { callback ( myContext, module, res ) ; }) ;
In some cases, it might be desirable to get a sensor value using a method identical to the old synchronous methods (without using Promises), even if it returns a slightly outdated cached value since I/O is not possible. For this purpose, the EcmaScript library introduce new classes called
synchronous proxies. A synchronous proxy is an object that mirrors the most recent state of the connected class, but can be read using regular synchronous function calls. For instance, instead of writing: async function logInfo ( module )
{
console.
log ( 'Name: ' + await module.
get_logicalName ()) ;
console.
log ( 'Beacon: ' + await module.
get_beacon ()) ;
}
...
logInfo ( myModule ) ;
...
you can use: function logInfoProxy ( moduleSyncProxy )
{
console.
log ( 'Name: ' +moduleProxy.
get_logicalName ()) ;
console.
log ( 'Beacon: ' +moduleProxy.
get_beacon ()) ;
} logInfoSync (await myModule.
get_syncProxy ()) ;
You can also rewrite this last asynchronous call as: myModule.
get_syncProxy () .
then ( logInfoProxy ) ;
8.3. 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.
// For Node.js, we use function require()
// For HTML, we would use <script src="...">
require ( 'yoctolib-es2017/yocto_api.js' ) ; require ( 'yoctolib-es2017/yocto_current.js' ) ;
// Get access to your device, through the VirtualHub running locally
await YAPI.
RegisterHub ( '127.0.0.1' ) ; var current = YCurrent.
FindCurrent ( "YAMPMK01-123456.current1" ) ;
// Check that the module is online to handle hot-plug
if(await current.
isOnline ())
{
// Use current.get_currentValue()
[ ...
]
www.yoctopuce.com
8. Using Yocto-Amp with JavaScript / EcmaScript
}
Let us look at these lines in more details.
yocto_api and yocto_current import
These two import provide access to functions allowing you to manage Yoctopuce modules. yocto_api
is always needed, yocto_current
is necessary to manage modules containing a current sensor, such as Yocto-Amp. Other imports can be useful in other cases, such as
YModule which can let you enumerate any type of Yoctopuce device.
YAPI.RegisterHub
The
RegisterHub
method 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, or of a YoctoHub. If the host cannot be reached, this function will trigger an exception.
YCurrent.FindCurrent
The
FindCurrent
method 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 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.MaFonction" ) current = YCurrent.
FindCurrent ( "MonModule.current1" ) current = YCurrent.
FindCurrent ( "MonModule.MaFonction" ) current = YCurrent.
FindCurrent ( "MaFonction" )
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 corresponding module is present and in working order.
FindCurrent
allows you to know if the
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, for Node.js
Open a command window (a terminal, a shell...) and go into the directory example_nodejs/Doc-
GettingStarted-Yocto-Amp within Yoctopuce library for JavaScript / EcmaScript 2017. In there, you will find a file named demo.js
with the sample code below, which uses the functions explained above, but this time used with all side materials needed to make it work nicely as a small demo.
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.
"use strict" ; require ( 'yoctolib-es2017/yocto_api.js' ) ; require ( 'yoctolib-es2017/yocto_current.js' ) ; let dcAmp, acAmp;
www.yoctopuce.com
37
8. Using Yocto-Amp with JavaScript / EcmaScript
38
async function startDemo ()
{ await YAPI.
LogUnhandledPromiseRejections () ; await YAPI.
DisableExceptions () ;
// Setup the API to use the VirtualHub on local machine
let errmsg = new YErrorMsg () ; if(await YAPI.
RegisterHub ( '127.0.0.1' , errmsg ) != YAPI.
SUCCESS ) {
console.
log ( 'Cannot contact VirtualHub on 127.0.0.1: ' +errmsg.
msg ) ; return ;
}
// Select specified device, or use first available one
let serial = process.
argv [ process.
argv .
length 1 ] ; if( serial [ 8 ] != '-' ) {
// by default use any connected module suitable for the demo
let anysensor = YCurrent.
FirstCurrent () ; if( anysensor ) { let module = await anysensor.
module () ;
serial = await module.
get_serialNumber () ;
} else {
console.
log ( 'No matching sensor connected, check cable !' ) ; return ;
}
}
console.
log ( 'Using device ' +serial ) ;
dcAmp = YCurrent.
FindCurrent ( serial+ ".current1" ) ;
acAmp = YCurrent.
FindCurrent ( serial+ ".current2" ) ;
refresh () ;
} async function refresh ()
{ if (await dcAmp.
isOnline ()) {
console.
log ( 'DC current : ' + (await dcAmp.
get_currentValue ()) + (await dcAmp.
get_unit ())) ;
console.
log ( 'AC current : ' + (await acAmp.
get_currentValue ()) + (await acAmp.
get_unit ())) ;
} else {
console.
log ( 'Module not connected' ) ;
} setTimeout ( refresh, 500 ) ;
} startDemo () ;
As explained at the beginning of this chapter, you need to have Node.js v7.6 or later installed to try this example. When done, you can type the following two commands to automatically download and install the dependencies for building this example: npm install
You can the start the sample code within Node.js using the following command, replacing the [...] by the arguments that you want to pass to the demo code: node demo.js [ ...
]
Same example, but this time running in a browser
If you want to see how to use the library within a browser rather than with Node.js, switch to the directory example_html/Doc-GettingStarted-Yocto-Amp. You will find there a single HTML file, with a JavaScript section similar to the code above, but with a few changes since it has to interact through an HTML page rather than through the JavaScript console.
<!DOCTYPE html>
< html >
< head >
< meta charset ="UTF-8">
< title > Hello World </ title >
< script src ="../../lib/yocto_api.js"></ script >
www.yoctopuce.com
8. Using Yocto-Amp with JavaScript / EcmaScript
< script src ="../../lib/yocto_current.js"></ script >
< script >
async function startDemo()
{
await YAPI.LogUnhandledPromiseRejections();
await YAPI.DisableExceptions();
// Setup the API to use the VirtualHub on local machine
let errmsg = new YErrorMsg();
if(await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS) {
alert('Cannot contact VirtualHub on 127.0.0.1: '+errmsg.msg);
}
refresh();
}
async function refresh()
{
let serial = document.getElementById('serial').value;
if(serial == '') {
// by default use any connected module suitable for the demo
let anysensor = YCurrent.FirstCurrent();
if(anysensor) {
let module = await anysensor.module();
serial = await module.get_serialNumber();
document.getElementById('serial').value = serial;
}
}
let dcAmp = YCurrent.FindCurrent(serial+".current1");
let acAmp = YCurrent.FindCurrent(serial+".current2");
if (await dcAmp.isOnline()) {
document.getElementById('msg').value = '';
document.getElementById("dcAmp").value = (await dcAmp.get_currentValue()) + (await dcAmp.get_unit());
document.getElementById("acAmp").value = (await acAmp.get_currentValue()) + (await acAmp.get_unit());
} else {
document.getElementById('msg').value = 'Module not connected';
}
setTimeout(refresh, 500);
}
startDemo();
</ script >
</ head >
< body >
Module to use: < input id ='serial'>
< input id ='msg' style ='color:red;border:none;' readonly>< br >
DC current : < input id ='dcAmp' readonly>< br >
AC current : < input id ='acAmp' readonly>< br >
</ body >
</ html >
No installation is needed to run this example, all you have to do is open the HTML file using a web browser,
8.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.
"use strict" ; require ( 'yoctolib-es2017/yocto_api.js' ) ; async function startDemo ( args )
{ await YAPI.
LogUnhandledPromiseRejections () ;
// Setup the API to use the VirtualHub on local machine
let errmsg = new YErrorMsg () ; if(await YAPI.
RegisterHub ( '127.0.0.1' , errmsg ) != YAPI.
SUCCESS ) {
console.
log ( 'Cannot contact VirtualHub on 127.0.0.1: ' +errmsg.
msg ) ; return ;
www.yoctopuce.com
39
8. Using Yocto-Amp with JavaScript / EcmaScript
40
}
// Select the relay to use
let module = YModule.
FindModule ( args [ 0 ]) ; if(await module.
isOnline ()) { if( args.
length > 1 ) { if( args [ 1 ] == 'ON' ) { await module.
set_beacon ( YModule.
BEACON_ON ) ;
} else { await module.
set_beacon ( YModule.
BEACON_OFF ) ;
}
}
console.
log ( 'serial: ' + await module.
get_serialNumber ()) ;
console.
log ( 'logical name: ' + await module.
get_logicalName ()) ;
console.
log ( 'luminosity: ' + await module.
get_luminosity () + '%' ) ;
console.
log ( 'beacon: ' + (await module.
get_beacon () ==YModule.
BEACON_ON
?
'ON' : 'OFF' )) ;
console.
log ( 'upTime: ' + parseInt (await module.
get_upTime () / 1000 ) + ' sec' ) ;
console.
log ( 'USB current: ' + await module.
get_usbCurrent () + ' mA' ) ;
console.
log ( 'logs:' ) ;
console.
log (await module.
get_lastLogs ()) ;
} else {
console.
log ( "Module not connected (check identification and USB cable) \n" ) ;
} await YAPI.
FreeAPI () ;
} if( process.
argv .
length < 2 ) {
console.
log ( "usage: node demo.js <serial or logicalname> [ ON | OFF ]" ) ;
} else {
startDemo ( process.
argv .
slice ( 2 )) ;
}
Each property xxx
of the module can be read thanks to a method of type properties which are not read-only can be modified with the help of the get_xxxx() set_xxx()
, and
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.
"use strict" ; require ( 'yoctolib-es2017/yocto_api.js' ) ; async function startDemo ( args )
{ await YAPI.
LogUnhandledPromiseRejections () ;
// Setup the API to use the VirtualHub on local machine
let errmsg = new YErrorMsg () ; if(await YAPI.
RegisterHub ( '127.0.0.1' , errmsg ) != YAPI.
SUCCESS ) {
console.
log ( 'Cannot contact VirtualHub on 127.0.0.1: ' +errmsg.
msg ) ; return ;
}
// Select the relay to use
let module = YModule.
FindModule ( args [ 0 ]) ; if(await module.
isOnline ()) { if( args.
length > 1 ) { let newname = args [ 1 ] ; if ( !
await YAPI.
CheckLogicalName ( newname )) {
console.
log ( "Invalid name (" + newname + ")" ) ;
process.
exit ( 1 ) ;
} await module.
set_logicalName ( newname ) ; await module.
saveToFlash () ;
}
www.yoctopuce.com
8. Using Yocto-Amp with JavaScript / EcmaScript
console.
log ( 'Current name: ' + await module.
get_logicalName ()) ;
} else {
console.
log ( "Module not connected (check identification and USB cable) \n" ) ;
} await YAPI.
FreeAPI () ;
} if( process.
argv .
length < 2 ) {
console.
log ( "usage: node demo.js <serial> [newLogicalName]" ) ;
} else {
startDemo ( process.
argv .
slice ( 2 )) ;
}
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
YModule.FirstModule() 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.
"use strict" ; require ( 'yoctolib-es2017/yocto_api.js' ) ; async function startDemo ()
{ await YAPI.
LogUnhandledPromiseRejections () ; await YAPI.
DisableExceptions () ;
// Setup the API to use the VirtualHub on local machine
let errmsg = new YErrorMsg () ; if (await YAPI.
RegisterHub ( '127.0.0.1' , errmsg ) != YAPI.
SUCCESS ) {
console.
log ( 'Cannot contact VirtualHub on 127.0.0.1' ) ; return ;
}
refresh () ;
} async function refresh ()
{ try { let errmsg = new YErrorMsg () ; await YAPI.
UpdateDeviceList ( errmsg ) ; let module = YModule.
FirstModule () ; while( module ) { let line = await module.
get_serialNumber () ;
line += '(' + (await module.
get_productName ()) + ')' ;
console.
log ( line ) ;
module = module.
nextModule () ;
} setTimeout ( refresh, 500 ) ;
} catch( e ) {
console.
log ( e ) ;
}
} try {
startDemo () ;
} catch( e ) {
console.
log ( e ) ;
}
www.yoctopuce.com
41
8. Using Yocto-Amp with JavaScript / EcmaScript
8.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 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:
• If your code catches the exception and handles it, everything goes well.
• 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.
• 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
YAPI.DisableExceptions()
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.
42 www.yoctopuce.com
9. 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, 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
1
, 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.
9.1. Getting ready
Go to the Yoctopuce web site and download the following items:
• The PHP programming library
• The VirtualHub software
3
2
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.
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 PHP code snipplet to use the Current function.
include( 'yocto_api.php' ) ; include( 'yocto_current.php' ) ;
1
A couple of free PHP servers: easyPHP for Windows, MAMP for Mac OS X.
2 www.yoctopuce.com/EN/libraries.php
3 www.yoctopuce.com/EN/virtualhub.php
www.yoctopuce.com
43
9. Using Yocto-Amp with PHP
// Get access to your device, through the VirtualHub running locally
yRegisterHub ( 'http://127.0.0.1:4444/' ,$errmsg ) ;
$current = yFindCurrent ( "YAMPMK01-123456.current1" ) ;
// Check that the module is online to handle hot-plug
if( current-> isOnline ())
{
// Use current->get_currentValue(), ...
}
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 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 = 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 corresponding module is present and in working order.
yFindCurrent
allows you to know if the
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
4
, 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.
44
4
If you do not have a text editor, use Notepad rather than Microsoft Word.
www.yoctopuce.com
9. Using Yocto-Amp with PHP
<HTML>
<HEAD>
<TITLE>Hello World</TITLE>
</HEAD>
<BODY>
<?php
include( 'yocto_api.php' ) ; include( 'yocto_current.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/' ,$errmsg ) != YAPI_SUCCESS ) { die ( "Cannot contact VirtualHub on 127.0.0.1" ) ;
}
@$serial = $_GET [ 'serial' ] ; if ( $serial != '' ) {
// Check if a specified module is available online
$sensor= yFindCurrent ( " $serial .current1" ) ; if ( !$sensor-> isOnline ()) { die ( "Module not connected (check serial and USB cable)" ) ;
}
} else {
// or use any connected module suitable for the demo
$sensor = yFirstCurrent () ; if( is_null ( $sensor )) { die ( "No module connected (check USB cable)" ) ;
} else {
$serial = $sensor-> module () -> get_serialnumber () ;
}
}
Print( "Module to use: <input name='serial' value=' $serial '><br>" ) ; if ( $sensor-> isOnline ())
{ $sensorDC = yFindCurrent ( $serial.
".current1" ) ;
$sensorAC = yFindCurrent ( $serial.
".current2" ) ;
$DC = $sensorDC-> get_currentValue () ;
$AC = $sensorAC-> get_currentValue () ;
Print( "Current, DC : $DC mA AC : $AC mA <br>" ) ;
}
yFreeAPI () ;
// trigger auto-refresh after one second
Print( "<script language='javascript1.5' type='text/JavaScript'>
\n"
) ;
Print( "setTimeout('window.location.reload()',1000);" ) ;
Print( "</script> \n" ) ;
?>
</BODY>
</HTML>
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 activate the localization beacon.
<HTML>
<HEAD>
<TITLE>Module Control</TITLE>
</HEAD>
<BODY>
<FORM method='get'>
<?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/' ,$errmsg ) != YAPI_SUCCESS ) { die ( "Cannot contact VirtualHub on 127.0.0.1 : " .$errmsg ) ;
}
www.yoctopuce.com
45
9. Using Yocto-Amp with PHP
46
@$serial = $_GET [ 'serial' ] ; if ( $serial != '' ) {
// Check if a specified module is available online
$module = yFindModule ( " $serial " ) ; if ( !$module-> isOnline ()) { die ( "Module not connected (check serial and USB cable)" ) ;
}
} else {
// or use any connected module suitable for the demo
$module = yFirstModule () ; if( $module ) {
// skip VirtualHub
$module = $module-> nextModule () ;
} if( is_null ( $module )) { die ( "No module connected (check USB cable)" ) ;
} else {
$serial = $module-> get_serialnumber () ;
}
}
Print( "Module to use: <input name='serial' value=' $serial '><br>" ) ; if ( isset ( $_GET [ 'beacon' ])) { if ( $_GET [ 'beacon' ] == 'ON' )
$module-> set_beacon ( Y_BEACON_ON ) ; else
$module-> set_beacon ( Y_BEACON_OFF ) ;
} printf ( 'serial: %s<br>' ,$module-> get_serialNumber ()) ; printf ( 'logical name: %s<br>' ,$module-> get_logicalName ()) ; printf ( 'luminosity: %s<br>' ,$module-> get_luminosity ()) ; print( 'beacon: ' ) ; if( $module-> get_beacon () == Y_BEACON_ON ) { printf ( "<input type='radio' name='beacon' value='ON' checked>ON " ) ; printf ( "<input type='radio' name='beacon' value='OFF'>OFF<br>" ) ;
} else { printf ( "<input type='radio' name='beacon' value='ON'>ON " ) ; printf ( "<input type='radio' name='beacon' value='OFF' checked>OFF<br>" ) ;
} printf ( 'upTime: %s sec<br>' , intVal ( $module-> get_upTime () / 1000 )) ; printf ( 'USB current: %smA<br>' ,$module-> get_usbCurrent ()) ; printf ( 'logs:<br><pre>%s</pre>' ,$module-> get_lastLogs ()) ;
yFreeAPI () ;
?>
<input type='submit' value='refresh'>
</FORM>
</BODY>
</HTML>
Each property xxx
of the module can be read thanks to a method of type properties which are not read-only can be modified with the help of the get_xxxx() set_xxx()
, and
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.
<HTML>
<HEAD>
<TITLE>save settings</TITLE>
<BODY>
<FORM method='get'>
<?php
include( 'yocto_api.php' ) ;
// Use explicit error handling rather than exceptions
yDisableExceptions () ;
www.yoctopuce.com
9. Using Yocto-Amp with PHP
// Setup the API to use the VirtualHub on local machine
if( yRegisterHub ( 'http://127.0.0.1:4444/' ,$errmsg ) != YAPI_SUCCESS ) { die ( "Cannot contact VirtualHub on 127.0.0.1" ) ;
}
@$serial = $_GET [ 'serial' ] ; if ( $serial != '' ) {
// Check if a specified module is available online
$module = yFindModule ( " $serial " ) ; if ( !$module-> isOnline ()) { die ( "Module not connected (check serial and USB cable)" ) ;
}
} else {
// or use any connected module suitable for the demo
$module = yFirstModule () ; if( $module ) {
// skip VirtualHub
$module = $module-> nextModule () ;
} if( is_null ( $module )) { die ( "No module connected (check USB cable)" ) ;
} else {
$serial = $module-> get_serialnumber () ;
}
}
Print( "Module to use: <input name='serial' value=' $serial '><br>" ) ; if ( isset ( $_GET [ 'newname' ])){
$newname = $_GET [ 'newname' ] ; if ( !yCheckLogicalName
( $newname )) die ( 'Invalid name' ) ;
$module-> set_logicalName ( $newname ) ;
$module-> saveToFlash () ;
} printf ( "Current name: %s <br>" , $module-> get_logicalName ()) ; print( "New name: <input name='newname' value='' maxlength=19><br>" ) ;
yFreeAPI () ;
?>
<input type='submit'>
</FORM>
</BODY>
</HTML>
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() object to find the following modules, and this as long as the returned value is not
function of this
NULL
. Below a short example listing the connected modules.
<HTML>
<HEAD>
<TITLE>inventory</TITLE>
</HEAD>
<BODY>
<H1>Device list</H1>
<TT>
<?php
include( 'yocto_api.php' ) ;
yRegisterHub ( "http://127.0.0.1:4444/" ) ;
$module = yFirstModule () ; while ( !
is_null ( $module )) { printf ( " %s ( %s )<br>" , $module-> get_serialNumber () ,
$module-> get_productName ()) ;
$module=$module-> nextModule () ;
}
yFreeAPI () ;
?>
</TT>
www.yoctopuce.com
47
9. Using Yocto-Amp with PHP
</BODY>
</HTML>
9.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.
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 communicate 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.
48
Responses from request from LAN machines are routed.
www.yoctopuce.com
9. Using Yocto-Amp with PHP
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.
The HTTP callback API uses the VirtualHub which initiates the requests.
Configuration
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 VirtualHub itself
4. Click on the edit button of the Outgoing callbacks section
Click on the "configure" button on the first line
www.yoctopuce.com
49
9. Using Yocto-Amp with PHP
Click on the "edit" button of the "Outgoing callbacks" section
50
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 of using an IP address, you must use the callback string (or http://callback which is equivalent).
include( "yocto_api.php" ) ; yRegisterHub ( "callback" ) ;
The remainder of the code stays strictly identical. On the VirtualHub 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 VirtualHub. 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.
www.yoctopuce.com
9. 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 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 VirtualHub, but it is at least of a few seconds in the best case.
The HTTP callback Yocto-API mode is currently available in PHP, EcmaScript (Node.JS) and Java only.
9.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 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:
• If your code catches the exception and handles it, everything goes well.
• 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.
• 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
YAPI.DisableExceptions()
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
www.yoctopuce.com
51
9. Using Yocto-Amp with PHP
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.
52 www.yoctopuce.com
10. 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
1
. 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
2
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.
10.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 the Current function.
#include "yocto_api.h"
#include "yocto_current.h"
[ ...
]
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
2 www.yoctopuce.com/EN/libraries.php
www.yoctopuce.com
53
10. Using Yocto-Amp with C++
54
// 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.
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 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.
YCurrent *current = yFindCurrent ( "YAMPMK01-123456.current1" ) ;
YCurrent *current = yFindCurrent ( "YAMPMK01-123456.MyFunction" ) ;
YCurrent *current = yFindCurrent ( "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 corresponding module is present and in working order.
yFindCurrent
allows you to know if the
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, but this time used with all side materials needed to make it work nicely as a small demo.
#include "yocto_api.h"
#include "yocto_current.h"
#include <iostream>
#include <stdlib.h> using namespace std;
www.yoctopuce.com
10. Using Yocto-Amp with C++
static void usage (void)
{ cout << "usage: demo <serial_number> " << endl ; cout << " demo <logical_name>" << endl ; cout << " demo any (use any discovered device)" << endl ; u64 now = yGetTickCount () ; while ( yGetTickCount () - now < 3000 ) {
// wait 3 sec to show the message
} exit ( 1 ) ;
} int main ( int argc, const char * argv [])
{ string errmsg; string target;
YCurrent *sensor;
YCurrent *sensorAC;
YCurrent *sensorDC;
YModule *m; if ( argc < 2 ) usage () ;
target = ( string ) argv [ 1 ] ;
YAPI:: DisableExceptions () ;
// Setup the API to use local USB devices
if ( YAPI:: RegisterHub ( "usb" , errmsg ) != YAPI_SUCCESS ) { cerr << "RegisterHub error: " << errmsg << endl ; return 1 ;
} if ( target == "any" ) {
// retreive any voltage sensor (can be AC or DC)
sensor = YCurrent:: FirstCurrent () ; if ( sensor == NULL ) { cerr << "No module connected (Check cable)" << endl ; exit ( 1 ) ;
}
} else {
sensor = YCurrent:: FindCurrent ( target + ".current1" ) ;
}
// we need to retreive both DC and AC voltage from the device.
if ( sensor-> isOnline ()) {
m = sensor-> get_module () ;
sensorDC = YCurrent:: FindCurrent ( m-> get_serialNumber () + ".current1" ) ;
sensorAC = YCurrent:: FindCurrent ( m-> get_serialNumber () + ".current2" ) ;
} else { cerr << "No module connected (Check cable)" << endl ; exit ( 1 ) ;
} while( 1 ) { if ( !sensorDC-> isOnline ()) { cout << "Module disconnected" << endl ; break ;
} cout << "Current, DC : " << sensorDC-> get_currentValue () << " mA" ; cout << " AC : " << sensorAC-> get_currentValue () << " mA" ; cout << " (press Ctrl-C to exit)" << endl ;
YAPI:: Sleep ( 1000 , errmsg ) ;
} ;
yFreeAPI () ; return 0 ;
}
10.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.
www.yoctopuce.com
55
10. Using Yocto-Amp with C++
56
#include <iostream>
#include <stdlib.h>
#include "yocto_api.h" using namespace std; static void usage (const char *exe )
{ cout << "usage: " << exe << " <serial or logical name> [ON/OFF]" << endl ; exit ( 1 ) ;
} int main ( int argc, const char * argv [])
{ string errmsg;
// Setup the API to use local USB devices
if( yRegisterHub ( "usb" , errmsg ) != YAPI_SUCCESS ) { cerr << "RegisterHub error: " << errmsg << endl ; return 1 ;
} if( argc < 2 )
usage ( argv [ 0 ]) ;
YModule *module = yFindModule ( argv [ 1 ]) ;
// use serial or logical name
if ( module-> isOnline ()) { if ( argc > 2 ) { if ( string ( argv [ 2 ]) == "ON" )
module-> set_beacon ( Y_BEACON_ON ) ; else
module-> set_beacon ( Y_BEACON_OFF ) ;
} cout << "serial: " << module-> get_serialNumber () << endl ; cout << "logical name: " << module-> get_logicalName () << endl ; cout << "luminosity: " << module-> get_luminosity () << endl ; cout << "beacon: " ; if ( module-> get_beacon () == Y_BEACON_ON ) cout << "ON" << endl ; else cout << "OFF" << endl ; cout << "upTime: " << module-> get_upTime () / 1000 << " sec" << endl ; cout << "USB current: " << module-> get_usbCurrent () << " mA" << endl ; cout << "Logs:" << endl << module-> get_lastLogs () << endl ;
} else { cout << argv [ 1 ] << " not connected (check identification and USB cable)"
<< endl ;
}
yFreeAPI () ; return 0 ;
}
Each property xxx
of the module can be read thanks to a method of type properties which are not read-only can be modified with the help of the get_xxxx() set_xxx()
, and
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.
#include <iostream>
#include <stdlib.h>
#include "yocto_api.h"
www.yoctopuce.com
10. Using Yocto-Amp with C++
using namespace std; static void usage (const char *exe )
{ cerr << "usage: " << exe << " <serial> <newLogicalName>" << endl ; exit ( 1 ) ;
} int main ( int argc, const char * argv [])
{ string errmsg;
// Setup the API to use local USB devices
if( yRegisterHub ( "usb" , errmsg ) != YAPI_SUCCESS ) { cerr << "RegisterHub error: " << errmsg << endl ; return 1 ;
} if( argc < 2 )
usage ( argv [ 0 ]) ;
YModule *module = yFindModule ( argv [ 1 ]) ;
// use serial or logical name
if ( module-> isOnline ()) { if ( argc >= 3 ) { string newname = argv [ 2 ] ; if ( !yCheckLogicalName
( newname )) { cerr << "Invalid name (" << newname << ")" << endl ;
usage ( argv [ 0 ]) ;
}
module-> set_logicalName ( newname ) ;
module-> saveToFlash () ;
} cout << "Current name: " << module-> get_logicalName () << endl ;
} else { cout << argv [ 1 ] << " not connected (check identification and USB cable)"
<< endl ;
}
yFreeAPI () ; return 0 ;
}
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() object to find the following modules, and this as long as the returned value is not
function of this
NULL
. Below a short example listing the connected modules.
#include <iostream>
#include "yocto_api.h" using namespace std; int main ( int argc, const char * argv [])
{ string errmsg;
// Setup the API to use local USB devices
if( YAPI:: RegisterHub ( "usb" , errmsg ) != YAPI_SUCCESS ) { cerr << "RegisterHub error: " << errmsg << endl ; return 1 ;
} cout << "Device list: " << endl ;
YModule *module = YModule:: FirstModule () ;
www.yoctopuce.com
57
10. Using Yocto-Amp with C++
while ( module != NULL ) { cout << module-> get_serialNumber () << " " ; cout << module-> get_productName () << endl ;
module = module-> nextModule () ;
}
yFreeAPI () ; return 0 ;
}
10.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 library throws an exception. In this case, there are three possibilities:
• If your code catches the exception and handles it, everything goes well.
• 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.
• 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
YAPI.DisableExceptions()
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.
10.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.
58 www.yoctopuce.com
10. Using Yocto-Amp with C++
Integration in source format
Integrating all the sources of the library into your projects has several advantages:
• It guaranties the respect of the compilation conventions of your project (32/64 bits, inclusion of debugging symbols, unicode or ASCII characters, etc.);
• It facilitates debugging if you are looking for the cause of a problem linked to the Yoctopuce library;
• 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;
• 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 subdirectory yapi
) to your project.
For 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
• For Mac OS X: IOKit.framework and CoreFoundation.framework
• 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 corresponding to your operating system into your libPath.
Binaries/...
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
• 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: gcc (...) -Wl,-Bstatic -lyocto-static -Wl,-Bdynamic -lm -lpthread -lusb-1.0 -lstdc++
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 corresponding to your operating system into your LibPath.
Binaries/...
www.yoctopuce.com
59
10. Using Yocto-Amp with C++
Then, for you project to build correctly, you need to link with your project the dynamic Yoctopuce library and the prerequisite system libraries:
• For Windows: yocto.lib
• For Mac OS X: libyocto, IOKit.framework, and CoreFoundation.framework
• For Linux: libyocto, libm, libpthread, libusb1.0, and libstdc++.
With GCC, the command line to compile is simply: gcc (...) -lyocto -lm -lpthread -lusb-1.0 -lstdc++
60 www.yoctopuce.com
11. Using Yocto-Amp with Objective-C
Objective-C is language of choice 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
1
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
2
with video shots showing how to integrate the library into your projects.
11.1. Control of the Current function
Launch Xcode 4.2 and open the corresponding sample project provided in the directory Examples/
Doc-GettingStarted-Yocto-Amp of the Yoctopuce library.
#import <Foundation/Foundation.h>
#import "yocto_api.h"
#import "yocto_current.h" static void usage (void)
{
NSLog ( @"usage: demo <serial_number> " ) ;
NSLog ( @" demo <logical_name>" ) ;
NSLog ( @" demo any (use any discovered device)" ) ; exit ( 1 ) ;
} int main ( int argc, const char * argv [])
{
1 www.yoctopuce.com/EN/libraries.php
2 www.yoctopuce.com/EN/article/new-objective-c-library-for-mac-os-x
www.yoctopuce.com
61
11. Using Yocto-Amp with Objective-C
NSError *error;
YCurrent *sensor;
YCurrent *sensorAC;
YCurrent *sensorDC;
YModule *m; if ( argc < 2 ) {
usage () ;
}
@autoreleasepool {
NSString *target = [ NSString stringWithUTF8String:argv [ 1 ]] ;
// Setup the API to use local USB devices
if([ YAPI RegisterHub: @"usb" : &error ] != YAPI_SUCCESS ) {
NSLog ( @"RegisterHub error: %@" , [ error localizedDescription ]) ; return 1 ;
} if ([ target isEqualToString: @"any" ]) {
// retreive any current sensor (can be AC or DC)
sensor = [ YCurrent FirstCurrent ] ; 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 stringByAppendingString: @".current1"
]] ;
sensorAC = [ YCurrent FindCurrent: [ m.serialNumber stringByAppendingString: @".current2"
]] ;
} else {
NSLog ( @"No module connected (check USB cable)" ) ; return 1 ;
} while( 1 ) { if ( !
[ m isOnline ]) {
NSLog ( @"No module connected (check identification and USB cable)" ) ; return 1 ;
}
NSLog ( @"Current DC : %f mA" , [ sensorDC currentValue ]) ;
NSLog ( @" AC : %f mA" , [ sensorAC currentValue ]) ;
NSLog ( @" (press Ctrl-C to exit)" ) ;
[ YAPI Sleep: 1000 : NULL ] ;
}
[ YAPI FreeAPI ] ;
} return 0 ;
}
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.
[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.
62 www.yoctopuce.com
11. Using Yocto-Amp with Objective-C
[Current FindCurrent]
The
[Current 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.
YCurrent *current = [ Current FindCurrent: @"YAMPMK01-123456.current1" ] ;
YCurrent *current = [ Current FindCurrent: @"YAMPMK01-123456.MyFunction" ] ;
YCurrent *current = [ Current FindCurrent: @"MyModule.current1" ] ;
YCurrent *current = [ Current FindCurrent: @"MyModule.MyFunction" ] ;
YCurrent *current = [ Current FindCurrent: @"MyFunction" ] ;
[Current 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
[Current 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.
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.
#import <Foundation/Foundation.h>
#import "yocto_api.h" static void usage ( const char *exe )
{
NSLog ( @"usage: %s <serial or logical name> [ON/OFF] \n" , exe ) ; exit ( 1 ) ;
} int main ( int argc, const char * argv [])
{
NSError *error;
@autoreleasepool {
// Setup the API to use local USB devices
if([ YAPI RegisterHub: @"usb" : &error ] != YAPI_SUCCESS ) {
NSLog ( @"RegisterHub error: %@" , [ error localizedDescription ]) ; return 1 ;
} if( argc < 2 )
usage ( argv [ 0 ]) ;
NSString *serial_or_name = [ NSString stringWithUTF8String:argv [ 1 ]] ;
// use serial or logical name
YModule *module = [ YModule FindModule:serial_or_name ] ; if ([ module isOnline ]) { if ( argc > 2 ) { if ( strcmp ( argv [ 2 ] , "ON" ) == 0 )
[ module setBeacon:Y_BEACON_ON ] ; else
[ module setBeacon:Y_BEACON_OFF ] ;
}
NSLog ( @"serial: %@ \n" , [ module serialNumber ]) ;
NSLog ( @"logical name: %@ \n" , [ module logicalName ]) ;
NSLog ( @"luminosity: %d
\n"
, [ module luminosity ]) ;
NSLog ( @"beacon: " ) ;
www.yoctopuce.com
63
11. Using Yocto-Amp with Objective-C
64
if ([ module beacon ] == Y_BEACON_ON )
NSLog ( @"ON \n" ) ; else
NSLog ( @"OFF \n" ) ;
NSLog ( @"upTime: %ld 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 ) ;
}
[ YAPI FreeAPI ] ;
} return 0 ;
Each property xxx
of the module can be read thanks to a method of type properties which are not read-only can be modified with the help of the get_xxxx set_xxx:
, and
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 allows you to modify the logical name of a module.
method. The short example below
#import <Foundation/Foundation.h>
#import "yocto_api.h" static void usage ( const char *exe )
{
NSLog ( @"usage: %s <serial> <newLogicalName> \n" , exe ) ; exit ( 1 ) ;
} int main ( int argc, const char * argv [])
{
NSError *error;
@autoreleasepool {
// Setup the API to use local USB devices
if([ YAPI RegisterHub: @"usb" :&error ] != YAPI_SUCCESS ) {
NSLog ( @"RegisterHub error: %@" , [ error localizedDescription ]) ; return 1 ;
} if( argc < 2 )
usage ( argv [ 0 ]) ;
NSString *serial_or_name = [ NSString stringWithUTF8String:argv [ 1 ]] ;
// use serial or logical name
YModule *module = [ YModule FindModule:serial_or_name ] ; if ( module.isOnline
) { if ( argc >= 3 ) {
NSString *newname = [ NSString stringWithUTF8String:argv [ 2 ]] ; if ( !
[ YAPI CheckLogicalName:newname ]) {
NSLog ( @"Invalid name (%@) \n" , newname ) ;
usage ( argv [ 0 ]) ;
}
module.logicalName = newname;
[ module saveToFlash ] ;
}
NSLog ( @"Current name: %@ \n" , module.logicalName
) ;
} else {
NSLog ( @"%@ not connected (check identification and USB cable) \n" ,
serial_or_name ) ;
}
[ YAPI FreeAPI ] ;
www.yoctopuce.com
11. Using Yocto-Amp with Objective-C
} return 0 ;
}
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() object to find the following modules, and this as long as the returned value is not
function of this
NULL
. Below a short example listing the connected modules.
#import <Foundation/Foundation.h>
#import "yocto_api.h" int main ( int argc, const char * argv [])
{
NSError *error;
@autoreleasepool {
// Setup the API to use local USB devices
if([ YAPI RegisterHub: @"usb" :&error ] != YAPI_SUCCESS ) {
NSLog ( @"RegisterHub error: %@ \n" , [ error localizedDescription ]) ; return 1 ;
}
NSLog ( @"Device list: \n" ) ;
YModule *module = [ YModule FirstModule ] ; while ( module != nil ) {
NSLog ( @"%@ %@" , module.serialNumber, module.productName
) ;
module = [ module nextModule ] ;
}
[ YAPI FreeAPI ] ;
} return 0 ;
}
11.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 library throws an exception. In this case, there are three possibilities:
• If your code catches the exception and handles it, everything goes well.
www.yoctopuce.com
65
11. Using Yocto-Amp with Objective-C
• 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.
• 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
YAPI.DisableExceptions()
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.
66 www.yoctopuce.com
12. 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
1
.
12.1. Installation
Download the Visual Basic Yoctopuce library from the Yoctopuce web site
2
. 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.
12.2. Using the Yoctopuce API in a Visual Basic project
The Visual Basic.NET Yoctopuce library is composed 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
3
. 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 project managing Yoctopuce modules.
sources
directory to create a
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 Solution 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
2 www.yoctopuce.com/EN/libraries.php
3
The sources of this DLL are available in the C++ API
www.yoctopuce.com
67
12. Using Yocto-Amp with Visual Basic .NET
Then add in the same manner the yapi.dll
DLL, located in the
Sources/dll
directory
4
. 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.
12.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.
[ ...
]
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 is easy: just check that the device is online
If ( current.
isOnline ()) Then
REM Use current.get_currentValue(), ...
End If
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 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 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 = 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 corresponding module is present and in working order.
yFindCurrent
allows you to know if the
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.
68
4
Remember to change the filter of the selection window, otherwise the DLL will not show.
www.yoctopuce.com
12. Using Yocto-Amp with Visual Basic .NET
A real example
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 time used with all side materials needed to make it work nicely as a small demo.
Module Module1
Private Sub Usage ()
Dim execname As String = System .
AppDomain .
CurrentDomain .
FriendlyName
Console .
WriteLine ( "Usage:" )
Console .
WriteLine ( execname + " demo <serial_number>" )
Console .
WriteLine ( execname + " demo <logical_name>" )
Console .
WriteLine ( execname + " demo any " )
System.
Threading .
Thread .
Sleep ( 2500 )
End
End Sub
Sub Die (ByVal msg As String )
Console .
WriteLine ( msg + "(check USB cable)" )
End
End Sub
Sub Main ()
Dim argv () As String = System .
Environment .
GetCommandLineArgs ()
Dim errmsg As String = ""
Dim target As String
Dim sensor As YCurrent
Dim sensorDC As YCurrent = Nothing
Dim sensorAC As YCurrent = Nothing
Dim m As YModule = Nothing
If argv.
Length < 2 Then Usage ()
target = argv ( 1 )
REM Setup the API to use local USB devices
If ( yRegisterHub ( "usb" , errmsg ) <> YAPI_SUCCESS ) Then
Console .
WriteLine ( "RegisterHub error: " + errmsg )
End
End If
If target = "any" Then
REM retreive any voltage sensor (can be AC or DC)
sensor = yFirstCurrent ()
If sensor Is Nothing Then Die ( "No module connected" )
Else
sensor = yFindCurrent ( target + ".voltage1" )
End If
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" )
sensorAC = yFindCurrent ( m.
get_serialNumber () + ".current2" )
Else
Die ( "Module not connected" )
End If
While ( True )
If Not ( m.
isOnline ()) Then Die ( "Module not connected" )
Console .
Write( "DC: " + sensorDC.
get_currentValue () .
ToString () + " mA " )
Console .
Write( "AC: " + sensorAC.
get_currentValue () .
ToString () + " mA " )
Console .
WriteLine ( " (press Ctrl-C to exit)" )
ySleep ( 1000 , errmsg )
End While
yFreeAPI ()
End Sub
End Module
www.yoctopuce.com
69
12. Using Yocto-Amp with Visual Basic .NET
12.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.
IO
Imports System .
Environment
Module Module1
Sub usage ()
Console .
WriteLine ( "usage: demo <serial or logical name> [ON/OFF]" )
End
End Sub
Sub Main ()
Dim argv () As String = System .
Environment .
GetCommandLineArgs ()
Dim errmsg As String = ""
Dim m As ymodule
If ( yRegisterHub ( "usb" , errmsg ) <> YAPI_SUCCESS ) Then
Console .
WriteLine ( "RegisterHub error:" + errmsg )
End
End If
If argv.
Length < 2 Then usage ()
m = yFindModule ( argv ( 1 ))
REM use serial or logical name
If ( m.
isOnline ()) Then
If argv.
Length > 2 Then
If argv ( 2 ) = "ON" Then m.
set_beacon ( Y_BEACON_ON )
If argv ( 2 ) = "OFF" Then m.
set_beacon ( Y_BEACON_OFF )
End If
Console .
WriteLine ( "serial: " + m.
get_serialNumber ())
Console .
WriteLine ( "logical name: " + m.
get_logicalName ())
Console .
WriteLine ( "luminosity: " + Str ( m.
get_luminosity ()))
Console .
Write( "beacon: " )
If ( m.
get_beacon () = Y_BEACON_ON ) Then
Console .
WriteLine ( "ON" )
Else
Console .
WriteLine ( "OFF" )
End If
Console .
WriteLine ( "upTime: " + Str ( m.
get_upTime () / 1000 ) + " sec" )
Console .
WriteLine ( "USB current: " + Str ( m.
get_usbCurrent ()) + " mA" )
Console .
WriteLine ( "Logs:" )
Console .
WriteLine ( m.
get_lastLogs ())
Else
Console .
WriteLine ( argv ( 1 ) + " not connected (check identification and USB cable)" )
End If
yFreeAPI ()
End Sub
End Module
Each property xxx
of the module can be read thanks to a method of type properties which are not read-only can be modified with the help of the get_xxxx() set_xxx()
, and
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.
Module Module1
70 www.yoctopuce.com
12. Using Yocto-Amp with Visual Basic .NET
Sub usage ()
Console .
WriteLine ( "usage: demo <serial or logical name> <new logical name>" )
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 <> 3 ) Then usage ()
REM Setup the API to use local USB devices
If yRegisterHub ( "usb" , errmsg ) <> 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= " + m.
get_serialNumber )
Console .
Write( " / name= " + m.
get_logicalName ())
Else
Console .
Write( "not connected (check identification and USB cable" )
End If
yFreeAPI ()
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 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
Nothing
. Below a short example listing the connected modules.
Module Module1
Sub Main ()
Dim M As ymodule
Dim errmsg As String = ""
REM Setup the API to use local USB devices
If yRegisterHub ( "usb" , errmsg ) <> YAPI_SUCCESS Then
Console .
WriteLine ( "RegisterHub error: " + errmsg )
End
End If
Console .
WriteLine ( "Device list" )
M = yFirstModule ()
While M IsNot Nothing
Console .
WriteLine ( M.
get_serialNumber () + " (" + M.
get_productName () + ")" )
M = M.
nextModule ()
End While
yFreeAPI ()
End Sub
www.yoctopuce.com
71
12. Using Yocto-Amp with Visual Basic .NET
End Module
12.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 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:
• If your code catches the exception and handles it, everything goes well.
• 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.
• 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
YAPI.DisableExceptions()
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.
72 www.yoctopuce.com
13. Using Yocto-Amp with C#
C# (pronounced C-Sharp) is an object-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
1
.
13.1. Installation
Download the Visual C# Yoctopuce library from the Yoctopuce web site
2
. 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.
13.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
3
. 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
Yoctopuce modules.
sources
directory to create a project managing
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 click 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
2 www.yoctopuce.com/EN/libraries.php
3
The sources of this DLL are available in the C++ API
www.yoctopuce.com
73
13. Using Yocto-Amp with C#
Then add in the same manner the yapi.dll
DLL, located in the
Sources/dll
directory
4
. 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 C# code snipplet to use the Current function.
[ ...
] 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 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.
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.
74
4
Remember to change the filter of the selection window, otherwise the DLL will not show.
www.yoctopuce.com
13. 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 System.Collections.Generic
; using System.Linq
; using System.Text
; namespace ConsoleApplication1
{ class Program
{ static void usage ()
{ string execname = System .
AppDomain .
CurrentDomain .
FriendlyName ;
Console .
WriteLine ( "Usage" ) ;
Console .
WriteLine ( execname + " <serial_number>" ) ;
Console .
WriteLine ( execname + " <logical_name>" ) ;
Console .
WriteLine ( execname + " any " ) ;
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 = "" ; string target;
YCurrent sensor;
YCurrent sensorDC = null ;
YCurrent sensorAC = null ;
YModule m = null ; if ( args.
Length < 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 + ".current1" ) ;
// we need to retreive both DC and AC voltage from the device.
if ( sensor.
isOnline ()) {
m = sensor.
get_module () ;
sensorDC = YCurrent.
FindCurrent ( m.
get_serialNumber () + ".current1" ) ;
sensorAC = YCurrent.
FindCurrent ( m.
get_serialNumber () + ".current2" ) ;
} else die ( "Module not connected" ) ; if ( !m.
isOnline ())
die ( "Module not connected" ) ;
www.yoctopuce.com
75
13. Using Yocto-Amp with C#
76
while ( m.
isOnline ()) {
Console .
Write ( "DC: " + sensorDC.
get_currentValue () .
ToString () + " mA " ) ;
Console .
Write ( "AC: " + sensorAC.
get_currentValue () .
ToString () + " mA " ) ;
Console .
WriteLine ( " (press Ctrl-C to exit)" ) ;
YAPI.
Sleep ( 1000 , ref errmsg ) ;
}
YAPI.
FreeAPI () ;
}
}
}
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.
using System ; using System.Collections.Generic
; using System.Linq
; using System.Text
; namespace ConsoleApplication1
{ class Program
{ static void usage ()
{ string execname = System .
AppDomain .
CurrentDomain .
FriendlyName ;
Console .
WriteLine ( "Usage:" ) ;
Console .
WriteLine ( execname + " <serial or logical name> [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 ) ;
} if ( args.
Length < 1 ) usage () ;
m = YModule.
FindModule ( args [ 0 ]) ;
// use serial or logical name
if ( m.
isOnline ()) { if ( args.
Length >= 2 ) { if ( args [ 1 ] .
ToUpper () == "ON" ) {
m.
set_beacon ( YModule.
BEACON_ON ) ;
} if ( args [ 1 ] .
ToUpper () == "OFF" ) {
m.
set_beacon ( YModule.
BEACON_OFF ) ;
}
}
Console .
WriteLine ( "serial: " + m.
get_serialNumber ()) ;
Console .
WriteLine ( "logical name: " + m.
get_logicalName ()) ;
Console .
WriteLine ( "luminosity: " + m.
get_luminosity () .
ToString ()) ;
Console .
Write ( "beacon: " ) ; if ( m.
get_beacon () == YModule.
BEACON_ON )
Console .
WriteLine ( "ON" ) ; else
Console .
WriteLine ( "OFF" ) ;
Console .
WriteLine ( "upTime: " + ( m.
get_upTime () / 1000 ) .
ToString () + " sec" ) ;
Console .
WriteLine ( "USB current: " + m.
get_usbCurrent () .
ToString () + " mA" ) ;
Console .
WriteLine ( "Logs: \r\n" + m.
get_lastLogs ()) ;
www.yoctopuce.com
13. Using Yocto-Amp with C#
} else {
Console .
WriteLine ( args [ 0 ] + " not connected (check identification and USB cable)" ) ;
}
YAPI.
FreeAPI () ;
}
}
}
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()
The short example below allows you to modify the logical name of a module.
method. using System ; using System.Collections.Generic
; using System.Linq
; using System.Text
; namespace ConsoleApplication1
{ class Program
{ static void usage ()
{ string execname = System .
AppDomain .
CurrentDomain .
FriendlyName ;
Console .
WriteLine ( "Usage:" ) ;
Console .
WriteLine ( "usage: demo <serial or logical name> <new logical name>" ) ;
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 ()) ;
} else {
Console .
Write ( "not connected (check identification and USB cable" ) ;
}
YAPI.
FreeAPI () ;
}
}
www.yoctopuce.com
77
13. 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 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.Linq
; using System.Text
; namespace ConsoleApplication1
{ class Program
{ 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 ) ;
}
Console .
WriteLine ( "Device list" ) ;
m = YModule.
FirstModule () ; while ( m != null ) {
Console .
WriteLine ( m.
get_serialNumber () + " (" + m.
get_productName () + ")" ) ;
m = m.
nextModule () ;
}
YAPI.
FreeAPI () ;
}
}
}
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 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.
78 www.yoctopuce.com
13. 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:
• If your code catches the exception and handles it, everything goes well.
• 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.
• 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
YAPI.DisableExceptions()
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.
www.yoctopuce.com
79
80 www.yoctopuce.com
14. 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
1
.
Delphi libraries are provided not as VCL components, but directly as source files. These files are compatible with most Delphi versions.
2
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.
14.1. Preparation
Go to the Yoctopuce web site and download the Yoctopuce Delphi libraries
3
. Uncompress everything in a directory of your choice, add the subdirectory sources in the list of directories of Delphi libraries.
4
By default, the Yoctopuce Delphi library uses the yapi.dll 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.
14.2. Control of the Current 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;
{$APPTYPE CONSOLE} uses
SysUtils,
Windows,
yocto_api,
yocto_current;
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
3
Delphi libraries are regularly tested with Delphi 5 and Delphi XE2.
4 www.yoctopuce.com/EN/libraries.php
Use the Tools / Environment options menu.
www.yoctopuce.com
81
14. Using Yocto-Amp with Delphi
Procedure usage () ; var
execname : string ; begin
execname := ExtractFileName ( paramstr ( 0 )) ; writeln ( execname+ ' <serial_number>' ) ; writeln ( execname+ ' <logical_name>' ) ; writeln ( execname+ ' any ' ) ; sleep ( 2500 ) ; halt ; end ;
Procedure die ( msg: string ) ; begin writeln ( msg + ' (check USB cable)' ) ; halt ; end ; var
errmsg : string ;
target : string ;
sensor : TYCurrent;
sensorDC : TYCurrent;
sensorAC : TYCurrent;
m : TyModule; begin if ( paramcount< 1 ) then usage () ;
target:= paramstr ( 1 ) ;
// Setup the API to use local USB devices
If ( yRegisterHub ( 'usb' , errmsg ) <> YAPI_SUCCESS ) Then 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 module connected' ) ; end else
sensor:= yFindCurrent ( target + '.current1' ) ;
m := nil ;
sensorDC := nil ;
sensorAC := nil ;
// we need to retreive both DC and AC voltage from the device.
If ( sensor.
isOnline ()) Then begin
m := sensor.
get_module () ;
sensorDC := yFindCurrent ( m.
get_serialNumber () + '.current1' ) ;
sensorAC := yFindCurrent ( m.
get_serialNumber () + '.current2' ) ; end else Die ( 'Module not connected' ) ;
// let's poll
repeat
If Not( m.
isOnline ()) Then Die ( 'Module not connected' ) ;
Write ( 'DC: ' + FloatToStr ( sensorDC.
get_currentValue ()) + ' mA ' ) ;
Write ( 'AC: ' + FloatToStr ( sensorAC.
get_currentValue ()) + ' mA ' ) ;
Writeln ( ' (press Ctrl-C to exit)' ) ;
ySleep ( 1000 , errmsg ) ; until ( false ) ;
yFreeAPI () ; end .
There are only a few really important lines in this sample example. We will look at them in details.
82 www.yoctopuce.com
14. 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 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 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 current1 function the name "MyFunction". The following five calls are strictly equivalent, as long as
"MyFunction" is defined only once.
current := yFindCurrent ( "YAMPMK01123456 .
current1 " ) ; current := yFindCurrent ( "YAMPMK01123456 .
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 corresponding module is present and in working order.
yFindCurrent
allows you to know if the
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.
14.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.
program modulecontrol;
{$APPTYPE CONSOLE} uses
SysUtils,
yocto_api; const
serial = 'YAMPMK01-123456' ;
// use serial number or logical name
procedure refresh ( module:Tymodule ) ; begin if ( module.
isOnline ()) then begin
Writeln ( '' ) ;
Writeln ( 'Serial : ' + module.
get_serialNumber ()) ;
Writeln ( 'Logical name : ' + module.
get_logicalName ()) ;
Writeln ( 'Luminosity : ' + intToStr ( module.
get_luminosity ())) ;
Write ( 'Beacon :' ) ; if ( module.
get_beacon () =Y_BEACON_ON ) then Writeln ( 'on' ) else Writeln ( 'off' ) ;
Writeln ( 'uptime : ' + intToStr ( module.
get_upTime () div 1000 ) + 's' ) ;
Writeln ( 'USB current : ' + intToStr ( module.
get_usbCurrent ()) + 'mA' ) ;
www.yoctopuce.com
83
14. Using Yocto-Amp with Delphi
84
Writeln ( 'Logs : ' ) ;
Writeln ( module.
get_lastlogs ()) ;
Writeln ( '' ) ;
Writeln ( 'r : 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;
c : char ;
errmsg : string ; begin
// Setup the API to use local USB devices
if yRegisterHub ( 'usb' , errmsg ) <>YAPI_SUCCESS then begin
Write ( 'RegisterHub error: ' +errmsg ) ; exit ; end ;
module := yFindModule ( serial ) ;
refresh ( module ) ; repeat read ( c ) ; case c of
'r' : refresh ( module ) ;
'b' : beacon ( module,Y_BEACON_ON ) ;
' ' : beacon ( module,Y_BEACON_OFF ) ; end ; until c = 'x' ;
yFreeAPI () ; end .
Each property xxx
of the module can be read thanks to a method of type properties which are not read-only can be modified with the help of the get_xxxx() set_xxx()
, and
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;
{$APPTYPE CONSOLE} uses
SysUtils,
yocto_api; const
serial = 'YAMPMK01-123456' ;
// use serial number or logical name
var
module : TYModule;
errmsg : string ;
newname : string ; begin
// Setup the API to use local USB devices
if yRegisterHub ( 'usb' , errmsg ) <>YAPI_SUCCESS then begin
Write ( 'RegisterHub error: ' +errmsg ) ;
www.yoctopuce.com
14. Using Yocto-Amp with Delphi
exit ; end ;
module := yFindModule ( serial ) ; if (not( module.
isOnline )) then begin writeln ( 'Module not connected (check identification and USB cable)' ) ; exit ; end ;
Writeln ( 'Current logical name : ' +module.
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 () ;
yFreeAPI () ;
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;
{$APPTYPE CONSOLE} uses
SysUtils,
yocto_api; var
module : TYModule;
errmsg : string ; begin
// Setup the API to use local USB devices
if yRegisterHub ( 'usb' , errmsg ) <>YAPI_SUCCESS then begin
Write ( 'RegisterHub error: ' +errmsg ) ; exit ; end ;
Writeln ( 'Device list' ) ;
module := yFirstModule () ; while module<> nil do begin
Writeln ( module.
get_serialNumber () + ' (' +module.
get_productName () + ')' ) ;
module := module.
nextModule () ; end ;
yFreeAPI () ; end .
www.yoctopuce.com
85
14. Using Yocto-Amp with Delphi
14.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 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:
• If your code catches the exception and handles it, everything goes well.
• 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.
• 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
YAPI.DisableExceptions()
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.
86 www.yoctopuce.com
15. 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
1
.
15.1. Source files
The Yoctopuce library classes
2
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 automatically finds the API source files.
15.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.
15.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/
2 www.yoctopuce.com/EN/libraries.php
www.yoctopuce.com
87
15. Using the Yocto-Amp with Python
88
[ ...
] errmsg=YRefParam ()
#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 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.
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 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 *
www.yoctopuce.com
15. Using the Yocto-Amp with Python
def usage () :
scriptname = os .
path .
basename ( sys .
argv [ 0 ]) print( "Usage:" ) print( scriptname + ' <serial_number>' ) print( scriptname + ' <logical_name>' ) print( scriptname + ' any ' ) sys .
exit () def die ( msg ) : sys .
exit ( msg + ' (check USB cable)' ) errmsg = YRefParam () if len ( sys .
argv ) < 2 :
usage () target = sys .
argv [ 1 ]
# 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 sensor is None :
die ( 'No module connected' ) else :
sensor = YCurrent.
FindCurrent ( target + '.current1' )
# we need to retreive both DC and AC voltage from the device.
if not sensor.
isOnline () :
die ( 'Module not connected' ) m = sensor.
get_module () sensorDC = YCurrent.
FindCurrent ( m.
get_serialNumber () + '.current1' ) sensorAC = YCurrent.
FindCurrent ( m.
get_serialNumber () + '.current2' ) while sensor.
isOnline () : print( 'DC: ' + str ( sensorDC.
get_currentValue ()) + ' mA ' + \
'AC: ' + str ( sensorAC.
get_currentValue ()) + ' mA ' ) print( ' (press Ctrl-C to exit)' )
YAPI.
Sleep ( 1000 , errmsg )
YAPI.
FreeAPI ()
15.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 from yocto_api import * def usage () : sys .
exit ( "usage: demo <serial or logical name> [ON/OFF]" ) errmsg = YRefParam () if YAPI.
RegisterHub ( "usb" , errmsg ) != YAPI.
SUCCESS : sys .
exit ( "RegisterHub error: " + str ( errmsg )) if len ( sys .
argv ) < 2 :
usage () m = YModule.
FindModule ( sys .
argv [ 1 ])
# # use serial or logical name
www.yoctopuce.com
89
15. Using the Yocto-Amp with Python
if m.
isOnline () : if len ( sys .
argv ) > 2 : if sys .
argv [ 2 ] .
upper () == "ON" :
m.
set_beacon ( YModule.
BEACON_ON ) if sys .
argv [ 2 ] .
upper () == "OFF" :
m.
set_beacon ( YModule.
BEACON_OFF ) print( "serial: " + m.
get_serialNumber ()) print( "logical name: " + m.
get_logicalName ()) print( "luminosity: " + str ( m.
get_luminosity ())) if m.
get_beacon () == YModule.
BEACON_ON : print( "beacon: ON" ) else : print( "beacon: OFF" ) print( "upTime: " + str ( m.
get_upTime () / 1000 ) + " sec" ) print( "USB current: " + str ( m.
get_usbCurrent ()) + " mA" ) print( "logs: \n" + m.
get_lastLogs ()) else : print( sys .
argv [ 1 ] + " not connected (check identification and USB cable)" )
YAPI.
FreeAPI ()
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()
The short example below allows you to modify the logical name of a module.
method.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os , sys from yocto_api import * def usage () : sys .
exit ( "usage: demo <serial or logical name> <new logical name>" ) 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
if m.
isOnline () :
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 ( "not connected (check identification and USB cable" )
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.
90 www.yoctopuce.com
15. Using the Yocto-Amp with Python
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.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os , sys from yocto_api import * 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 list' ) module = YModule.
FirstModule () while module is not None : print( module.
get_serialNumber () + ' (' + module.
get_productName () + ')' )
module = module.
nextModule ()
YAPI.
FreeAPI ()
15.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 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:
• If your code catches the exception and handles it, everything goes well.
• 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.
• 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
YAPI.DisableExceptions()
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.
www.yoctopuce.com
91
15. Using the Yocto-Amp with Python
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.
92 www.yoctopuce.com
16. 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.
16.1. Getting ready
Go to the Yoctopuce web site and download the following items:
• The Java programming library
• The VirtualHub software
2
1
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.
16.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.
[ ...
]
// Get access to your device, connected locally on USB for instance
YAPI.
RegisterHub ( "127.0.0.1" ) ; 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
93
16. Using the Yocto-Amp with Java
94
}
[ ...
]
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 devices. 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 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.
isOnline
The isOnline()
method of the object returned by
YCurrent.FindCurrent
know if the corresponding module is present and in working order.
allows you to
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 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 sensorDC = YCurrent.
FindCurrent ( dc_hardwareid ) ;
YCurrent sensorAC = YCurrent.
FindCurrent ( ac_hardwareid ) ; while ( true ) { try {
System .
out .
println ( "DC: " + sensorDC.
get_currentValue () + " mA " ) ;
System .
out .
println ( "AC: " + sensorAC.
get_currentValue () + " mA " ) ;
System .
out .
println ( " (press Ctrl-C to exit)" ) ;
YAPI.
Sleep ( 1000 ) ;
} catch ( YAPI_Exception ex ) {
System .
out .
println ( "Module " +sensorDC.
module () + " is not connected" ) ; return ;
www.yoctopuce.com
16. Using the Yocto-Amp with Java
}
}
} public static void main ( String [] args )
{ try {
// setup the API to use local VirtualHub
YAPI.
RegisterHub ( "127.0.0.1" ) ;
} catch ( YAPI_Exception ex ) {
System .
out .
println ( "Cannot contact VirtualHub on 127.0.0.1 (" + ex.
getLocalizedMessage () + ")" ) ;
System .
out .
println ( "Ensure that the VirtualHub application is running" ) ;
System .
exit ( 1 ) ;
}
String serial= "" ; if ( args.
length > 0 ) {
serial = args [ 0 ] ;
} else {
YCurrent sensor = YCurrent.
FirstCurrent () ; if ( sensor == null ) {
System .
out .
println ( "No module connected (check USB cable)" ) ;
System .
exit ( 1 ) ;
} try {
serial = sensor.
module () .
get_serialNumber () ;
} catch ( YAPI_Exception ex ) {
System .
out .
println ( "No module connected (check USB cable)" ) ;
System .
exit ( 1 ) ;
}
}
Demo.
demo ( serial + ".current1" ,serial + ".current2" ) ;
YAPI.
FreeAPI () ;
}
}
16.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 )
{ try {
// setup the API to use local VirtualHub
YAPI.
RegisterHub ( "127.0.0.1" ) ;
} catch ( YAPI_Exception ex ) {
System .
out .
println ( "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
95
16. Using the Yocto-Amp with Java
96
try { if ( args.
length > 1 ) { if ( args [ 1 ] .
equalsIgnoreCase ( "ON" )) {
module.
setBeacon ( YModule.
BEACON_ON ) ;
} else {
module.
setBeacon ( YModule.
BEACON_OFF ) ;
}
}
System .
out .
println ( "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 .
println ( "beacon: ON" ) ;
} else {
System .
out .
println ( "beacon: OFF" ) ;
}
System .
out .
println ( "upTime: " + module.
get_upTime () / 1000 + " sec" ) ;
System .
out .
println ( "USB current: " + module.
get_usbCurrent () + " mA" ) ;
System .
out .
println ( "logs: \n" + module.
get_lastLogs ()) ;
} catch ( YAPI_Exception ex ) {
System .
out .
println ( args [ 1 ] + " not connected (check identification and USB cable)" ) ;
}
YAPI.
FreeAPI () ;
}
}
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.
import com.yoctopuce.YoctoAPI.* ; public class Demo { public static void main ( String [] args )
{ try {
// setup the API to use local VirtualHub
YAPI.
RegisterHub ( "127.0.0.1" ) ;
} catch ( YAPI_Exception ex ) {
System .
out .
println ( "Cannot contact VirtualHub on 127.0.0.1 (" + ex.
getLocalizedMessage () + ")" ) ;
System .
out .
println ( "Ensure that the VirtualHub application is running" ) ;
System .
exit ( 1 ) ;
} if ( args.
length != 2 ) {
System .
out .
println ( "usage: demo <serial or logical name> <new logical name>" ) ;
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 .
println ( "Invalid name (" + newname + ")" ) ;
System .
exit ( 1 ) ;
www.yoctopuce.com
16. Using the Yocto-Amp with Java
}
m.
set_logicalName ( newname ) ;
m.
saveToFlash () ;
// do not forget this
System .
out .
println ( "Module: serial= " + m.
get_serialNumber ()) ;
System .
out .
println ( " / name= " + m.
get_logicalName ()) ;
} catch ( YAPI_Exception ex ) {
System .
out .
println ( "Module " + args [ 0 ] + "not connected (check identification and USB cable)" ) ;
System .
out .
println ( 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 { public static void main ( String [] args )
{ try {
// setup the API to use local VirtualHub
YAPI.
RegisterHub ( "127.0.0.1" ) ;
} catch ( YAPI_Exception ex ) {
System .
out .
println ( "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 ( "Device list" ) ;
YModule module = YModule.
FirstModule () ; while ( module != null ) { try {
System .
out .
println ( module.
get_serialNumber () + " (" + module.
get_productName () + ")" ) ;
} catch ( YAPI_Exception ex ) { break ;
}
module = module.
nextModule () ;
}
YAPI.
FreeAPI () ;
}
}
16.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
97
16. 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 could crash the software.
isOnline
and which
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.
98 www.yoctopuce.com
17. Using the Yocto-Amp 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.
17.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.
17.2. Getting ready
Go to the Yoctopuce web site and download the Java for Android programming library
1
. 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 the Java for Android library.
17.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
99
17. 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 Android 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:
• Samsung Galaxy S3
• Samsung Galaxy Note 2
• Google Nexus 5
• Google Nexus 7
• Acer Iconia Tab A200
• Asus Tranformer Pad TF300T
• 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
2
.
17.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
<uses-feature android:name="android.hardware.usb.host" />
tag in the manifest
section.
<manifest ...>
...
<uses-feature android:name= "android.hardware.usb.host" />;
...
</manifest>
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 http:// www.yoctopuce.com/EN/products/category/extensions-and-networking
100 www.yoctopuce.com
17. 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);
in the method onCreate
of your application. If the object passed as parameter is not of the correct type, a exception is generated.
YAPI_Exception
...
@Override public void onCreate ( Bundle savedInstanceState ) { super .
onCreate ( savedInstanceState ) ; try {
// Pass the application Context to the Yoctopuce Library
YAPI.
EnableUSBHost (this) ;
} catch ( YAPI_Exception e ) {
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 <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"/> in the section <intent-filter> of the main activity. The section <activity> must have a pointer to an XML file containing the list of USB modules which can run the application.
<manifest xmlns:android= "http://schemas.android.com/apk/res/android"
...
<uses-feature android:name= "android.hardware.usb.host" />
...
<application ... >
<activity
android:name= ".MainActivity" >
<intent-filter>
<action android:name= "android.intent.action.MAIN" />
<action android:name= "android.hardware.usb.action.USB_DEVICE_ATTACHED" />
<category android:name= "android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name= "android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource= "@xml/device_filter" />
</activity>
</application>
</manifest>
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 vendorId and deviceID in decimal. The following example runs the application as soon as a Yocto-Relay or a YoctoPowerRelay is connected. You can find the vendorID and the deviceID of Yoctopuce modules in the characteristics section of the documentation.
<?xml version= "1.0" encoding= "utf-8" ?>
<resources>
<usb-device vendor-id= "9440" product-id= "12" />
<usb-device vendor-id= "9440" product-id= "13" />
</resources>
www.yoctopuce.com
101
17. Using the Yocto-Amp with Android
17.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.
[ ...
]
// 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 ())
{
//Use current.get_currentValue()
...
}
[ ...
]
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 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 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.
isOnline
The isOnline()
method of the object returned by
YCurrent.FindCurrent
know if the corresponding module is present and in working order.
allows you to
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.
102 www.yoctopuce.com
17. 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<String> aa; private String serial = "" ; private Handler handler = null ;
@Override public void onCreate ( Bundle savedInstanceState )
{ super .
onCreate ( savedInstanceState ) ;
setContentView ( R.
layout .
gettingstarted_yocto_amp ) ;
Spinner my_spin = ( Spinner ) findViewById ( R.
id .
spinner1 ) ;
my_spin.
setOnItemSelectedListener (this) ;
aa = new ArrayAdapter<String> (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 ()
{ super .
onStart () ; try {
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 () ;
}
} catch ( YAPI_Exception e ) {
e.
printStackTrace () ;
}
aa.
notifyDataSetChanged () ;
handler.
postDelayed ( r, 500 ) ;
}
@Override protected void onStop ()
{ super .
onStop () ;
handler.
removeCallbacks ( r ) ;
YAPI.
FreeAPI () ;
}
www.yoctopuce.com
103
17. Using the Yocto-Amp with Android
@Override public void onItemSelected ( AdapterView<?> parent, View view, int pos, long id )
{
serial = parent.
getItemAtPosition ( pos ) .
toString () ;
}
@Override public void onNothingSelected ( AdapterView<?> arg0 )
{
} final Runnable r = new Runnable ()
{ public void run ()
{ if ( serial != null ) {
YCurrent dc_sensor = YCurrent.
FindCurrent ( serial + ".current1" ) ; try {
TextView view = ( TextView ) findViewById ( R.
id .
dcfield ) ;
view.
setText ( String .
format ( "%.1f %s" , dc_sensor.
getCurrentValue () , dc_sensor.
getUnit ())) ;
} catch ( YAPI_Exception e ) {
e.
printStackTrace () ;
}
YCurrent ac_sensor = YCurrent.
FindCurrent ( serial + ".current2" ) ; try {
TextView view = ( TextView ) findViewById ( R.
id .
acfield ) ;
view.
setText ( String .
format ( "%.1f %s" , ac_sensor.
getCurrentValue () , ac_sensor.
getUnit ())) ;
} catch ( YAPI_Exception e ) {
e.
printStackTrace () ;
}
}
handler.
postDelayed (this , 1000 ) ;
}
} ;
}
17.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.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<String> aa; private YModule module = null ;
@Override public void onCreate ( Bundle savedInstanceState )
{ super .
onCreate ( savedInstanceState ) ;
setContentView ( R.
layout .
modulecontrol ) ;
Spinner my_spin = ( Spinner ) findViewById ( R.
id .
spinner1 ) ;
104 www.yoctopuce.com
17. Using the Yocto-Amp with Android
my_spin.
setOnItemSelectedListener (this) ;
aa = new ArrayAdapter<String> (this , android.
R .
layout .
simple_spinner_item ) ;
aa.
setDropDownViewResource ( android.
R .
layout .
simple_spinner_dropdown_item ) ;
my_spin.
setAdapter ( aa ) ;
}
@Override protected void onStart ()
{ super .
onStart () ; try {
aa.
clear () ;
YAPI.
EnableUSBHost (this) ;
YAPI.
RegisterHub ( "usb" ) ;
YModule r = YModule.
FirstModule () ; while ( r != null ) {
String hwid = r.
get_hardwareId () ;
aa.
add ( hwid ) ;
r = r.
nextModule () ;
}
} catch ( YAPI_Exception e ) {
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 ) return ; 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 ( "%d%%" , 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 ) ;
sw.
setChecked ( module.
getBeacon () == YModule.
BEACON_ON ) ;
field = ( TextView ) findViewById ( R.
id .
logs ) ;
field.
setText ( module.
get_lastLogs ()) ;
} catch ( YAPI_Exception e ) {
e.
printStackTrace () ;
}
}
@Override public void onItemSelected ( AdapterView<?> parent, View view, int pos, long id )
{
String hwid = parent.
getItemAtPosition ( pos ) .
toString () ;
module = YModule.
FindModule ( hwid ) ;
DisplayModuleInfo () ;
}
@Override public void onNothingSelected ( AdapterView<?> arg0 )
{
} public void refreshInfo ( View view )
{
DisplayModuleInfo () ;
}
www.yoctopuce.com
105
17. Using the Yocto-Amp with Android
public void toggleBeacon ( View view )
{ if ( module == null ) return ; boolean on = ((Switch) view ) .
isChecked () ; try { if ( on ) {
module.
setBeacon ( YModule.
BEACON_ON ) ;
} else {
module.
setBeacon ( YModule.
BEACON_OFF ) ;
}
} catch ( YAPI_Exception e ) {
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: 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()
The short example below allows you to modify the logical name of a module.
method. 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<String> 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.
setOnItemSelectedListener (this) ;
aa = new ArrayAdapter<String> (this , android.
R .
layout .
simple_spinner_item ) ;
aa.
setDropDownViewResource ( android.
R .
layout .
simple_spinner_dropdown_item ) ;
my_spin.
setAdapter ( aa ) ;
}
@Override protected void onStart ()
{ super .
onStart () ; try {
106 www.yoctopuce.com
17. Using the Yocto-Amp with Android
aa.
clear () ;
YAPI.
EnableUSBHost (this) ;
YAPI.
RegisterHub ( "usb" ) ;
YModule r = YModule.
FirstModule () ; while ( r != null ) {
String hwid = r.
get_hardwareId () ;
aa.
add ( hwid ) ;
r = r.
nextModule () ;
}
} catch ( YAPI_Exception e ) {
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 ) return ; try {
YAPI.
UpdateDeviceList () ;
// fixme
field = ( TextView ) findViewById ( R.
id .
logicalnamefield ) ;
field.
setText ( module.
getLogicalName ()) ;
} catch ( YAPI_Exception e ) {
e.
printStackTrace () ;
}
}
@Override public void onItemSelected ( AdapterView<?> parent, View view, int pos, long id )
{
String hwid = parent.
getItemAtPosition ( pos ) .
toString () ;
module = YModule.
FindModule ( hwid ) ;
DisplayModuleInfo () ;
}
@Override public void onNothingSelected ( AdapterView<?> arg0 )
{
} public void saveName ( View view )
{ if ( module == null ) return ;
}
EditText edit = ( EditText ) findViewById ( R.
id .
newname ) ;
String newname = edit.
getText () .
toString () ; try { if ( !YAPI.
CheckLogicalName ( newname )) {
Toast.
makeText ( getApplicationContext () , "Invalid name (" + newname + ")" ,
Toast.
LENGTH_LONG ) .
show () ; return ;
}
module.
set_logicalName ( newname ) ;
module.
saveToFlash () ;
// do not forget this
edit.
setText ( "" ) ;
} catch ( YAPI_Exception ex ) {
ex.
printStackTrace () ;
}
DisplayModuleInfo () ;
}
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
www.yoctopuce.com
107
17. Using the Yocto-Amp with Android
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.util.TypedValue
; 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
; public class Inventory extends Activity
{
@Override public void onCreate ( Bundle savedInstanceState )
{ super .
onCreate ( savedInstanceState ) ;
setContentView ( R.
layout .
inventory ) ;
} public void refreshInventory ( View view )
{
LinearLayout layout = ( LinearLayout ) findViewById ( R.
id .
inventoryList ) ;
layout.
removeAllViews () ; try {
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 ) ;
tx.
setTextSize ( TypedValue.
COMPLEX_UNIT_SP , 20 ) ;
layout.
addView ( tx ) ;
module = module.
nextModule () ;
}
} catch ( YAPI_Exception e ) {
e.
printStackTrace () ;
}
}
@Override protected void onStart ()
{ super .
onStart () ; try {
YAPI.
EnableUSBHost (this) ;
YAPI.
RegisterHub ( "usb" ) ;
} catch ( YAPI_Exception e ) {
e.
printStackTrace () ;
}
refreshInventory ( null ) ;
}
@Override protected void onStop ()
{ super .
onStop () ;
YAPI.
FreeAPI () ;
}
108 www.yoctopuce.com
17. Using the Yocto-Amp with Android
}
17.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 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.
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
109
110 www.yoctopuce.com
18. 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 is" in a production application.
18.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 Yoctopuce 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
111
18. 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
You only need to call
UpdateDeviceList()
UpdateDeviceList()
function is running.
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
YAPI.
UpdateDeviceList (ref errmsg ) ;
// non active waiting time managing other callbacks
YAPI.
Sleep ( 500 , ref errmsg ) ;
}
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 programming 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
YAPI.HandleEvents()
from this thread.
112 www.yoctopuce.com
18. 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.
1 static void valueChangeCallback ( YCurrent fct, string value )
{
Console .
WriteLine ( fct.
get_hardwareId () + "=" + 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 callback 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 )
{
Console .
WriteLine ( fct.
get_hardwareId () + "=" +
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 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 following example sets up a timed report callback 4 times per minute for t he first available
Current function.
YCurrent f = YCurrent.
FirstCurrent () ; f.
set_reportFrequency ( "4/m" ) ;
1
The value passed as parameter is the same as the value returned by the get_advertisedValue()
method.
www.yoctopuce.com
113
18. 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.
18.2. The data logger
Your Yocto-Amp is equipped 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 l = YDataLogger.
FirstDataLogger () ; l.
set_recording ( YDataLogger.
RECORDING_ON ) ;
It is possible to make the data recording start automatically as soon as the module is powered on.
YDataLogger l = YDataLogger.
FirstDataLogger () ; l.
set_autoStart ( YDataLogger.
AUTOSTART_ON ) ; l.
get_module () .
saveToFlash () ;
// do not forget to 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 l = YDataLogger.
FirstDataLogger () ; l.
forgetAllDataStreams () ;
114 www.yoctopuce.com
18. 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 () ; sensor.
set_logFrequency ( "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. You 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:
1. dataset = sensor.get_recordedData(0,0): select the desired time interval
2. dataset.loadMore(): load data from the device, progressively
3. dataset.get_summary(): get a single measure summarizing the full time interval
4. 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)
5. dataset.get_measures(): get an array with all detailled measures (that grows while loadMore
is being called repeteadly)
Measures are instances of
YMeasure
2
. 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
YDataSet dataset = sensor.
get_recordedData ( 0 , 0 ) ;
// 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 ())) ;
2
The
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
115
18. Advanced programming
// Next calls to loadMore() will retrieve measures
Console .
WriteLine ( "loading details" ) ; int progress; do {
Console .
Write ( "." ) ;
progress = dataset.
loadMore () ;
} while( progress < 100 ) ;
// All measures have now been loaded
List<YMeasure> details = dataset.
get_measures () ; foreach ( YMeasure m in details ) {
Console .
WriteLine ( String.
Format ( logFmt,
m.
get_startTimeUTC_asDateTime () .
ToString ( timeFmt ) ,
m.
get_endTimeUTC_asDateTime () .
ToString ( timeFmt ) ,
m.
get_averageValue () , sensor.
get_unit ())) ;
}
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:
• 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.
• 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
• 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 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%).
18.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.
116 www.yoctopuce.com
18. 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 current1 function returns b.
Measure correction with 1 calibration point, here (5,10)
The application is very simple: you only need to call the calibrateFromPoints() method of the function 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
117
18. Advanced programming
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.
FirstCurrent () ; 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.
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 = {} ;
Double [] ValuesAfter = {} ;
YCurrent f = YCurrent.
FirstCurrent () ;
118 www.yoctopuce.com
18. 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.
public 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
119
120 www.yoctopuce.com
19. Firmware Update
There are multiples way to update the firmware of a Yoctopuce module..
19.1. The VirtualHub or the YoctoHub
It is possible to update the firmware directly from the web interface of the VirtualHub or the
YoctoHub. The configuration panel of the module has an "upgrade" button to start a wizard that will guide you through the firmware update procedure.
In case the firmware update fails for any reason, and the module does no start anymore, simply unplug the module then plug it back while maintaining the Yocto-button down. The module will boot in "firmware update" mode and will appear in the VirtualHub interface below the module list.
19.2. The command line library
All the command line tools can update Yoctopuce modules thanks to the downloadAndUpdate command. The module selection mechanism works like for a traditional command. The [target] is the name of the module that you want to update. You can also use the "any" or "all" aliases, or even a name list, where the names are separated by commas, without spaces.
C:\> Executable [options] [target] command [parameters]
The following example updates all the Yoctopuce modules connected by USB.
C:\> YModule all downloadAndUpdate ok: Yocto-PowerRelay RELAYHI1-266C8 ( rev=15430 ) is up to date.
ok: 0 / 0 hubs in 0.000000s.
ok: 0 / 0 shields in 0.000000s.
ok: 1 / 1 devices in 0.130000s 0.130000s per device.
ok: All devices are now up to date.
C:\>
19.3. The Android application Yocto-Firmware
You can update your module firmware from your Android phone or tablet with the Yocto-Firmware application. This application lists all the Yoctopuce modules connected by USB and checks if a more recent firmware is available on www.yoctopuce.com. If a more recent firmware is available, you can
www.yoctopuce.com
121
19. Firmware Update
update the module. The application is responsible for downloading and installing the new firmware while preserving the module parameters.
Please note: while the firmware is being updated, the module restarts several times. Android interprets a USB device reboot as a disconnection and reconnection of the USB device and asks the authorization to use the USB port again. The user must click on OK for the update process to end successfully.
19.4. Updating the firmware with the programming library
If you need to integrate firmware updates in your application, the libraries offer you an API to update your modules.
1
Saving and restoring parameters
The get_allSettings()
method returns a binary buffer enabling you to save a module persistent parameters. This function is very useful to save the network configuration of a YoctoHub for example.
YWireless wireless = YWireless.
FindWireless ( "reference" ) ;
YModule m = wireless.
get_module () ; byte [] default_config = m.
get_allSettings () ; saveFile ( "default.bin" , default_config ) ;
...
You can then apply these parameters to other modules with the set_allSettings()
method.
byte [] default_config = loadFile ( "default.bin" ) ;
YModule m = YModule.
FirstModule () ; while ( m != null ) { if ( m.
get_productName () == "YoctoHub-Wireless" ) {
m.
set_allSettings ( default_config ) ;
}
m = m.
next () ;
}
Finding the correct firmware
The first step to update a Yoctopuce module is to find which firmware you must use. The checkFirmware(path, onlynew)
method of the YModule object does exactly this. The method checks that the firmware given as argument ( path
) is compatible with the module. If the onlynew
parameter is set, this method checks that the firmware is more recent than the version currently used by the module. When the file is not compatible (or if the file is older than the installed version), this method returns an empty string. In the opposite, if the file is valid, the method returns a file access path.
The following piece of code checks that the c:\tmp\METEOMK1.17328.byn
is compatible with the module stored in the m variable .
YModule m = YModule.
FirstModule () ;
...
...
string path = "c: \\tmp\METEOMK1.17328.byn" ; string newfirm = m.
checkFirmware ( path, false ) ; if ( newfirm != "" ) {
Console .
WriteLine ( "firmware " + newfirm + " is compatible" ) ;
}
...
1
The JavaScript, Node.js, and PHP libraries do not yet allow you to update the modules. These functions will be available in a next build.
122 www.yoctopuce.com
19. Firmware Update
The argument can be a directory (instead of a file). In this case, the method checks all the files of the directory recursively and returns the most recent compatible firmware. The following piece of code checks whether there is a more recent firmware in the c:\tmp\
directory.
YModule m = YModule.
FirstModule () ;
...
...
string path = "c: \\tmp" ; string newfirm = m.
checkFirmware ( path, true ) ; if ( newfirm != "" ) {
Console .
WriteLine ( "firmware " + newfirm + " is compatible and newer" ) ;
}
...
You can also give the "www.yoctopuce.com" string as argument to check whether there is a more recent published firmware on Yoctopuce's web site. In this case, the method returns the firmware
URL. You can use this URL to download the firmware on your disk or use this URL when updating the firmware (see below). Obviously, this possibility works only if your machine is connected to
Internet.
YModule m = YModule.
FirstModule () ;
...
...
string url = m.
checkFirmware ( "www.yoctopuce.com" , true ) ; if ( url != "" ) {
Console .
WriteLine ( "new firmware is available at " + url ) ;
}
...
Updating the firmware
A firmware update can take several minutes. That is why the update process is run as a background task and is driven by the user code thanks to the
YFirmwareUdpate
class.
To update a Yoctopuce module, you must obtain an instance of the
YFirmwareUdpate
class with the updateFirmware
method of a YModule object. The only parameter of this method is the path of the firmware that you want to install. This method does not immediately start the update, but returns a
YFirmwareUdpate
object configured to update the module.
string newfirm = m.
checkFirmware ( "www.yoctopuce.com" , true ) ;
.....
YFirmwareUpdate fw_update = m.
updateFirmware ( newfirm ) ;
The startUpdate()
method starts the update as a background task. This background task automatically takes care of
1. saving the module parameters
2. restarting the module in "update" mode
3. updating the firmware
4. starting the module with the new firmware version
5. restoring the parameters
The get_progress()
and get_progressMessage()
methods enable you to follow the progression of the update. update complete). get_progress() get_progressMessage()
returns the progression as a percentage (100 =
returns a character string describing the current operation (deleting, writing, rebooting, ...). If the get_progress
method returns a negative value, the update process failed. In this case, the get_progressMessage()
returns an error message.
The following piece of code starts the update and displays the progress on the standard output.
YFirmwareUpdate fw_update = m.
updateFirmware ( newfirm ) ;
....
int status = fw_update.
startUpdate () ; while ( status < 100 && status >= 0 ) {
www.yoctopuce.com
123
19. Firmware Update
int newstatus = fw_update.
get_progress () ; if ( newstatus != status ) {
Console .
WriteLine ( status + "% "
+ fw_update.
get_progressMessage ()) ;
}
YAPI.
Sleep ( 500 , ref errmsg ) ;
status = newstatus;
} if ( status < 0 ) {
Console .
WriteLine ( "Firmware Update failed: "
+ fw_update.
get_progressMessage ()) ;
} else {
Console .
WriteLine ( "Firmware Updated Successfully!" ) ;
}
An Android characteristic
You can update a module firmware using the Android library. However, for modules connected by
USB, Android asks the user to authorize the application to access the USB port.
During firmware update, the module restarts several times. Android interprets a USB device reboot as a disconnection and a reconnection to the USB port, and prevents all USB access as long as the user has not closed the pop-up window. The use has to click on OK for the update process to continue correctly. You cannot update a module connected by USB to an Android device
without having the user interacting with the device.
19.5. The "update" mode
If you want to erase all the parameters of a module or if your module does not start correctly anymore, you can install a firmware from the "update" mode.
To force the module to work in "update" mode, disconnect it, wait a few seconds, and reconnect it while maintaining the Yocto-button down. This will restart the module in "update" mode. This update mode is protected against corruptions and is always available.
In this mode, the module is not detected by the YModule objects anymore. To obtain the list of connected modules in "update" mode, you must use the
YAPI.GetAllBootLoaders()
function.
This function returns a character string array with the serial numbers of the modules in "update" mode.
List< string > allBootLoader = YAPI.
GetAllBootLoaders () ;
The update process is identical to the standard case (see the preceding section), but you must manually instantiate the
YFirmwareUpdate
object instead of calling module.updateFirmware()
. The constructor takes as argument three parameters: the module serial number, the path of the firmware to be installed, and a byte array with the parameters to be restored at the end of the update (or null
to restore default parameters).
YFirmwareUpdateupdate fw_update; fw_update = new YFirmwareUpdate ( allBootLoader [ 0 ] , newfirm, null ) ; int status = fw_update.
startUpdate () ;
.....
124 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. 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 VirtualHub. 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 VirtualHub is running, you obtain the list of the connected modules.
http://127.0.0.1:4444/api/services/whitePages.txt
www.yoctopuce.com
125
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 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:
126 www.yoctopuce.com
20. Using with unsupported languages
http://127.0.0.1:4444/bySerial/YAMPMK01-12345/dataLogger.json?id=current &utc=1389801080
20.3. Using dynamic 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
libyapi.dylib
libyapi-amd64.so
libyapi-armel.so
Platform
Max OS X
Linux Intel (64 bits)
Linux ARM EL libyapi-armhf.so
libyapi-i386.so
yapi64.dll
Linux ARM HL
Linux Intel (32 bits)
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: int yapiInitAPI ( int connection_type, char *errmsg ) ; int yapiUpdateDeviceList ( int forceupdate, char *errmsg ) ; int yapiHTTPRequest ( char *device, char *request, char * buffer, int buffsize, int *fullsize, char *errmsg ) ;
The yapiInitAPI 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 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 yapiHTTPRequest 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 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.dll DLL to read and then update the luminosity of a module.
www.yoctopuce.com
127
20. Using with unsupported languages
// Dll functions import
function yapiInitAPI ( mode: integer ;
errmsg : pansichar ) : integer ; cdecl ; external 'yapi.dll' name 'yapiInitAPI' ; function yapiUpdateDeviceList ( force: integer ;errmsg : pansichar ) : integer ; cdecl ; external 'yapi.dll' name 'yapiUpdateDeviceList' ; function yapiHTTPRequest ( device: pansichar ;url: pansichar ; buffer: pansichar ;
buffsize: integer ; var fullsize: integer ;
errmsg : pansichar ) : integer ; cdecl ; external 'yapi.dll' name 'yapiHTTPRequest' ; var
errmsgBuffer : array [ 0 ..
256 ] of ansichar ;
dataBuffer : array [ 0 ..
1024 ] of ansichar ;
errmsg,data : pansichar ;
fullsize,p : integer ; 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 := @errmsgBuffer;
data := @dataBuffer;
// API initialization
if( yapiInitAPI ( 1 ,errmsg ) < 0 ) then begin writeln ( errmsg ) ; halt ; end ;
// forces a device inventory
if( yapiUpdateDeviceList ( 1 ,errmsg ) < 0 ) then begin writeln ( errmsg ) ; halt ; end ;
// requests the module luminosity
if ( yapiHTTPRequest ( serial,getValue,data, sizeof ( dataBuffer ) ,fullsize,errmsg ) < 0 ) then begin writeln ( errmsg ) ; halt ; end ;
// searches for the HTTP header end
p := pos ( #13#10#13#10 ,data ) ;
// displays the response minus the HTTP header
writeln ( copy ( data,p+ 4 , length ( data ) -p3 )) ;
// changes the luminosity
if ( yapiHTTPRequest ( serial,setValue,data, sizeof ( dataBuffer ) ,fullsize,errmsg ) < 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
128 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 was obtained through
yapiGetAllDevices. infos points to a data structure in which the result is stored. This data structure has the following format:
Name
vendorid deviceid devrelease
Type
int int int
Size
(bytes)
Description
4
4
4
Yoctopuce USB ID
Module USB ID
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.dll DLL to list the connected modules.
// device description structure
type yDeviceSt = packed record
vendorid : word ;
deviceid : word ;
devrelease : word ;
nbinbterfaces : word ;
manufacturer : array [ 0 ..
19 ] of ansichar ;
productname : array [ 0 ..
27 ] of ansichar ;
serial : array [ 0 ..
19 ] of ansichar ;
logicalname : array [ 0 ..
19 ] of ansichar ;
firmware : array [ 0 ..
21 ] of ansichar ;
beacon : byte ; end ;
// Dll function import
function yapiInitAPI ( mode: integer ;
errmsg : pansichar ) : integer ; cdecl ; external 'yapi.dll' name 'yapiInitAPI' ; function yapiUpdateDeviceList ( force: integer ;errmsg : pansichar ) : integer ; cdecl ; external 'yapi.dll' name 'yapiUpdateDeviceList' ; function yapiGetAllDevices ( buffer: pointer ;
maxsize: integer ; var neededsize: integer ;
errmsg : pansichar ) : integer ; cdecl ; external 'yapi.dll' name 'yapiGetAllDevices' ; function apiGetDeviceInfo ( d: integer ; var infos:yDeviceSt;
errmsg : pansichar ) : integer ; cdecl ; external 'yapi.dll' name 'yapiGetDeviceInfo' ; var
errmsgBuffer : array [ 0 ..
256 ] of ansichar ;
dataBuffer : array [ 0 ..
127 ] of integer ;
// max of 128 USB devices
errmsg,data : pansichar ;
neededsize,i : integer ;
devinfos : yDeviceSt; begin
errmsg := @errmsgBuffer;
// API initialization
if( yapiInitAPI ( 1 ,errmsg ) < 0 ) then begin writeln ( errmsg ) ;
www.yoctopuce.com
129
20. Using with unsupported languages
halt ; end ;
// forces a device inventory
if( yapiUpdateDeviceList ( 1 ,errmsg ) < 0 ) then begin writeln ( errmsg ) ; halt ; end ;
// loads all device handles into dataBuffer
if yapiGetAllDevices ( @dataBuffer, sizeof ( dataBuffer ) ,neededsize,errmsg ) < 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 ( apiGetDeviceInfo ( dataBuffer [ i ] , devinfos, errmsg ) < 0 ) then begin writeln ( errmsg ) ; halt ; end ; writeln ( pansichar ( @devinfos.
serial ) + ' (' + pansichar ( @devinfos.
productname ) + ')' ) ; end ; end .
VB6 and yapi.dll
Each entry point from the yapi.dll is duplicated. You will find one regular C-decl version and one
Visual Basic 6 compatible version, prefixed with vb6_.
20.4. Porting the high level library
As all the sources of the Yoctopuce API are fully provided, you can very well port 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.
130 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 values.
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
131
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: js cpp m pas vb cs java uwp py php es
<script type='text/javascript' src='yocto_api.js'></script>
#include "yocto_api.h"
#import "yocto_api.h" uses yocto_api; yocto_api.vb
yocto_api.cs
import com.yoctopuce.YoctoAPI.YModule; import com.yoctopuce.YoctoAPI.YModule; from yocto_api import * require_once('yocto_api.php'); in HTML: <script src="../../lib/yocto_api.js"></script> in node.js: require('yoctolib-es2017/yocto_api.js');
Global functions
name
)
Checks if a given string is valid as logical name for a module or a function.
bool_removeFiles
)
Disables the HTTP callback cache.
Disables the use of exceptions to report runtime errors.
Re-enables the use of exceptions for runtime error handling.
osContext
)
This function is used only on Android.
Frees dynamically allocated memory blocks used by the Yoctopuce library.
Returns the version identifier for the Yoctopuce library in use.
Returns the current value of a monotone millisecond-based time counter.
errmsg
)
Maintains the device-to-library communication channel.
mode
,
errmsg
)
Initializes the Yoctopuce programming library explicitly.
url
,
errmsg
)
Fault-tolerant alternative to RegisterHub().
yRegisterDeviceArrivalCallback(
arrivalCallback
)
Register a callback function, to be called each time a device is plugged.
yRegisterDeviceRemovalCallback(
removalCallback
)
Register a callback function, to be called each time a device is unplugged.
132 www.yoctopuce.com
21. High-level API Reference
url
,
errmsg
)
Setup the Yoctopuce library to use modules connected on a given machine.
yRegisterHubDiscoveryCallback(
hubDiscoveryCallback
)
Register a callback function, to be called each time an Network Hub send an SSDP message.
logfun
)
Registers a log callback function.
arch
)
Select the architecture or the library to be loaded to access to USB.
object
)
(Objective-C only) Register an object that must follow the protocol YDeviceHotPlug .
str_directory
)
Enables the HTTP callback cache.
callback
,
ms_timeout
,
args
)
Invoke the specified callback function after a given timeout.
pktAckDelay
)
Enables the acknowledge of every USB packet received by the Yoctopuce library.
ms_duration
,
errmsg
)
Pauses the execution flow for a specified duration.
url
,
mstimeout
,
errmsg
)
Test if the hub is reachable.
errmsg
)
Force a hub discovery, if a callback as been registered with yRegisterHubDiscoveryCallback it will be called for each net work hub that will respond to the discovery.
url
)
Setup the Yoctopuce library to no more use modules connected on a previously registered machine with
RegisterHub.
errmsg
)
Triggers a (re)detection of connected Yoctopuce modules.
callback
,
context
)
Triggers a (re)detection of connected Yoctopuce modules.
www.yoctopuce.com
133
21. High-level API Reference
YAPI.CheckLogicalName() yCheckLogicalName()
YAPI
Checks if a given string is valid as logical name for a module or a function.
js cpp m pas vb cs java uwp py php es function yCheckLogicalName(
name
) bool yCheckLogicalName( const string&
name
)
+(BOOL) CheckLogicalName :(NSString *)
name
function yCheckLogicalName(
name
: string): boolean function yCheckLogicalName( ByVal
name
As String) As Boolean bool CheckLogicalName( string
name
) boolean CheckLogicalName( String
name
) bool CheckLogicalName( string
name
) def CheckLogicalName(
name
) function yCheckLogicalName(
$name
) function CheckLogicalName(
name
)
A valid logical name has a maximum of 19 characters, all among
A..Z
, 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.
134 www.yoctopuce.com
21. High-level API Reference
YAPI.ClearHTTPCallbackCacheDir() yClearHTTPCallbackCacheDir()
Disables the HTTP callback cache.
php function yClearHTTPCallbackCacheDir(
$bool_removeFiles
)
This method disables the HTTP callback cache, and can additionally cleanup the cache directory.
YAPI
Parameters : bool_removeFiles
True to clear the content of the cache.
Returns :
nothing.
www.yoctopuce.com
135
21. High-level API Reference
YAPI.DisableExceptions() yDisableExceptions()
YAPI
Disables the use of exceptions to report runtime errors.
js cpp m pas vb cs py php es function yDisableExceptions( ) void yDisableExceptions( )
+(void) DisableExceptions procedure yDisableExceptions( ) procedure yDisableExceptions( ) void DisableExceptions( ) def DisableExceptions( ) function yDisableExceptions( ) function 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.
136 www.yoctopuce.com
21. High-level API Reference
YAPI.EnableExceptions() yEnableExceptions()
YAPI
Re-enables the use of exceptions for runtime error handling.
js cpp m pas vb cs py php es function yEnableExceptions( ) void yEnableExceptions( )
+(void) EnableExceptions procedure yEnableExceptions( ) procedure yEnableExceptions( ) void EnableExceptions( ) def EnableExceptions( ) function yEnableExceptions( ) function 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.
www.yoctopuce.com
137
21. High-level API Reference
YAPI.EnableUSBHost() yEnableUSBHost()
YAPI
This function is used only on Android.
java 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.Context (or any subclass). 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).
138 www.yoctopuce.com
21. High-level API Reference
YAPI.FreeAPI() yFreeAPI()
YAPI
Frees dynamically allocated memory blocks used by the Yoctopuce library.
js cpp m pas vb cs java uwp py php es function yFreeAPI( ) void yFreeAPI( )
+(void) FreeAPI procedure yFreeAPI( ) procedure yFreeAPI( ) void FreeAPI( ) void FreeAPI( ) void FreeAPI( ) def FreeAPI( ) function yFreeAPI( ) function 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 yFreeAPI()
, or your program will crash.
www.yoctopuce.com
139
21. High-level API Reference
YAPI.GetAPIVersion() yGetAPIVersion()
YAPI
Returns the version identifier for the Yoctopuce library in use.
js cpp m pas vb cs java uwp py php es function yGetAPIVersion( ) string yGetAPIVersion( )
+(NSString*) GetAPIVersion function yGetAPIVersion( ): string function yGetAPIVersion( ) As String
String GetAPIVersion( )
String GetAPIVersion( ) string GetAPIVersion( ) def GetAPIVersion( ) function yGetAPIVersion( ) function GetAPIVersion( )
The version is a string in the form
"Major.Minor.Build"
, for instance
"1.01.5535"
. For languages using an external DLL (for instance 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.
140 www.yoctopuce.com
21. High-level API Reference
YAPI.GetTickCount() yGetTickCount()
YAPI
Returns the current value of a monotone millisecond-based time counter.
js cpp m pas vb cs java uwp py php es function yGetTickCount( ) u64 yGetTickCount( )
+(u64) GetTickCount function yGetTickCount( ): u64 function yGetTickCount( ) As Long ulong GetTickCount( ) long GetTickCount( ) ulong GetTickCount( ) def GetTickCount( ) function yGetTickCount( ) function 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.
www.yoctopuce.com
141
21. High-level API Reference
YAPI.HandleEvents() yHandleEvents()
YAPI
Maintains the device-to-library communication channel.
js cpp m pas vb cs java uwp py php es function yHandleEvents(
errmsg
)
YRETCODE yHandleEvents( string&
errmsg
)
+(YRETCODE) HandleEvents :(NSError**)
errmsg
function yHandleEvents( var
errmsg
: string): integer function yHandleEvents( ByRef
errmsg
As String) As YRETCODE
YRETCODE HandleEvents( ref string
errmsg
) int HandleEvents( ) async Task<int> HandleEvents( ) def HandleEvents(
errmsg
=None) function yHandleEvents(
&$errmsg
) function HandleEvents(
errmsg
)
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.
142 www.yoctopuce.com
21. High-level API Reference
YAPI.InitAPI() yInitAPI()
YAPI
Initializes the Yoctopuce programming library explicitly.
js cpp m pas vb cs java uwp py php es function yInitAPI(
mode
,
errmsg
)
YRETCODE yInitAPI( int
mode
, string&
errmsg
)
+(YRETCODE) InitAPI :(int)
mode
:(NSError**)
errmsg
function yInitAPI(
mode
: integer, var
errmsg
: string): integer function yInitAPI( ByVal
mode
As Integer, ByRef
errmsg
As String) As Integer int InitAPI( int
mode
, ref string
errmsg
) int InitAPI( int
mode
) async Task<int> InitAPI( int
mode
) def InitAPI(
mode
,
errmsg
=None) function yInitAPI(
$mode
,
&$errmsg
) function InitAPI(
mode
,
errmsg
)
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_DETECT_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.
www.yoctopuce.com
143
21. High-level API Reference
YAPI.PreregisterHub() yPreregisterHub()
YAPI
Fault-tolerant alternative to RegisterHub().
js cpp m pas vb cs java uwp py php es function yPreregisterHub(
url
,
errmsg
)
YRETCODE yPreregisterHub( const string&
url
, string&
errmsg
)
+(YRETCODE) PreregisterHub :(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
) int PreregisterHub( String
url
) async Task<int> PreregisterHub( string
url
) def PreregisterHub(
url
,
errmsg
=None) function yPreregisterHub(
$url
,
&$errmsg
) function PreregisterHub(
url
,
errmsg
)
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.
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.
144 www.yoctopuce.com
21. High-level API Reference
YAPI.RegisterDeviceArrivalCallback() yRegisterDeviceArrivalCallback()
YAPI
Register a callback function, to be called each time a device is plugged.
js cpp m pas vb cs java uwp py php es function yRegisterDeviceArrivalCallback(
arrivalCallback
) void yRegisterDeviceArrivalCallback( yDeviceUpdateCallback
arrivalCallback
)
+(void) RegisterDeviceArrivalCallback :(yDeviceUpdateCallback)
arrivalCallback
procedure yRegisterDeviceArrivalCallback(
arrivalCallback
: yDeviceUpdateFunc) procedure yRegisterDeviceArrivalCallback( ByVal
arrivalCallback
As yDeviceUpdateFunc) void RegisterDeviceArrivalCallback( yDeviceUpdateFunc
arrivalCallback
) void RegisterDeviceArrivalCallback( DeviceArrivalCallback
arrivalCallback
) void RegisterDeviceArrivalCallback( DeviceUpdateHandler
arrivalCallback
) def RegisterDeviceArrivalCallback(
arrivalCallback
) function yRegisterDeviceArrivalCallback(
$arrivalCallback
) function RegisterDeviceArrivalCallback(
arrivalCallback
)
This callback will be invoked while yUpdateDeviceList
is running. You will have to call this function on a regular basis.
Parameters : arrivalCallback
a procedure taking a YModule parameter, or null
www.yoctopuce.com
145
21. High-level API Reference
YAPI.RegisterDeviceRemovalCallback() yRegisterDeviceRemovalCallback()
YAPI
Register a callback function, to be called each time a device is unplugged.
js cpp m pas vb cs java uwp py php es function yRegisterDeviceRemovalCallback(
removalCallback
) void yRegisterDeviceRemovalCallback( yDeviceUpdateCallback
removalCallback
)
+(void) RegisterDeviceRemovalCallback :(yDeviceUpdateCallback)
removalCallback
procedure yRegisterDeviceRemovalCallback(
removalCallback
: yDeviceUpdateFunc) procedure yRegisterDeviceRemovalCallback( ByVal
removalCallback
As yDeviceUpdateFunc) void RegisterDeviceRemovalCallback( yDeviceUpdateFunc
removalCallback
) void RegisterDeviceRemovalCallback( DeviceRemovalCallback
removalCallback
) void RegisterDeviceRemovalCallback( DeviceUpdateHandler
removalCallback
) def RegisterDeviceRemovalCallback(
removalCallback
) function yRegisterDeviceRemovalCallback(
$removalCallback
) function RegisterDeviceRemovalCallback(
removalCallback
)
This callback will be invoked while yUpdateDeviceList
is running. You will have to call this function on a regular basis.
Parameters : removalCallback
a procedure taking a YModule parameter, or null
146 www.yoctopuce.com
YAPI.RegisterHub() yRegisterHub()
Setup the Yoctopuce library to use modules connected on a given machine.
js cpp m pas vb cs java uwp py php es function yRegisterHub(
url
,
errmsg
)
YRETCODE yRegisterHub( const string&
url
, string&
errmsg
)
+(YRETCODE) RegisterHub :(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
) int RegisterHub( String
url
) async Task<int> RegisterHub( string
url
) def RegisterHub(
url
,
errmsg
=None) function yRegisterHub(
$url
,
&$errmsg
) function RegisterHub(
url
,
errmsg
)
The parameter will determine how the API will work. Use the following values:
21. High-level API Reference
YAPI
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 hardware, 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, use the IP address 127.0.0.1.
callback: that keyword 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 or 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 access control has been activated on the hub, virtual or not, you want to reach, the URL parameter should look like: http://username:password@address: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.
www.yoctopuce.com
147
21. High-level API Reference
On failure, throws an exception or returns a negative error code.
148 www.yoctopuce.com
21. High-level API Reference
YAPI.RegisterHubDiscoveryCallback() yRegisterHubDiscoveryCallback()
YAPI
Register a callback function, to be called each time an Network Hub send an SSDP message.
cpp m pas vb cs java uwp py void yRegisterHubDiscoveryCallback( YHubDiscoveryCallback
hubDiscoveryCallback
)
+(void) RegisterHubDiscoveryCallback : (YHubDiscoveryCallback)
hubDiscoveryCallback
procedure yRegisterHubDiscoveryCallback(
hubDiscoveryCallback
: YHubDiscoveryCallback) procedure yRegisterHubDiscoveryCallback( ByVal
hubDiscoveryCallback
As
YHubDiscoveryCallback) void RegisterHubDiscoveryCallback( YHubDiscoveryCallback
hubDiscoveryCallback
) void RegisterHubDiscoveryCallback( HubDiscoveryCallback
hubDiscoveryCallback
) async Task RegisterHubDiscoveryCallback( HubDiscoveryHandler
hubDiscoveryCallback
) def RegisterHubDiscoveryCallback(
hubDiscoveryCallback
)
The callback has two string parameter, the first one contain the serial number of the hub and the second contain the URL of the network hub (this URL can be passed to RegisterHub). This callback will be invoked while yUpdateDeviceList is running. You will have to call this function on a regular basis.
Parameters : hubDiscoveryCallback
a procedure taking two string parameter, the serial
www.yoctopuce.com
149
21. High-level API Reference
YAPI.RegisterLogFunction() yRegisterLogFunction()
YAPI
Registers a log callback function.
cpp m pas vb cs java uwp py void yRegisterLogFunction( yLogFunction
logfun
)
+(void) RegisterLogFunction :(yLogCallback)
logfun
procedure yRegisterLogFunction(
logfun
: yLogFunc) procedure yRegisterLogFunction( ByVal
logfun
As yLogFunc) void RegisterLogFunction( yLogFunc
logfun
) void RegisterLogFunction( LogCallback
logfun
) void RegisterLogFunction( LogHandler
logfun
) def RegisterLogFunction(
logfun
)
This callback will be called each time the API have something to say. Quite useful to debug the API.
Parameters : logfun
a procedure taking a string parameter, or null
150 www.yoctopuce.com
21. High-level API Reference
YAPI.SelectArchitecture() ySelectArchitecture()
YAPI
Select the architecture or the library to be loaded to access to USB.
py 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
SelectArchitecture() before any other call to the library.
Parameters : arch
A string containing the architecture to use. Possibles value are: "armhf" , "armel" ,
"i386" , "x86_64" , "32bit" , "64bit"
Returns :
nothing.
On failure, throws an exception.
www.yoctopuce.com
151
21. High-level API Reference
YAPI.SetDelegate() ySetDelegate()
YAPI
(Objective-C only) Register an object that must follow the protocol
YDeviceHotPlug
.
m
+(void) SetDelegate :(id)
object
T h e m e t h o d s y D e v i c e A r r i v a l
a n d y D e v i c e R e m o v a l
w i l l b e i n v o k e d w h i l e yUpdateDeviceList is running. You will have to call this function on a regular basis.
Parameters : object
an object that must follow the protocol YAPIDelegate , or nil
152 www.yoctopuce.com
21. High-level API Reference
YAPI.SetHTTPCallbackCacheDir() ySetHTTPCallbackCacheDir()
YAPI
Enables the HTTP callback cache.
php function ySetHTTPCallbackCacheDir(
$str_directory
)
When enabled, this cache reduces the quantity of data sent to the PHP script by 50% to 70%. To enable this cache, the method ySetHTTPCallbackCacheDir() must be called before any call to yRegisterHub()
. This method takes in parameter the path of the directory used for saving data between each callback. This folder must exist and the PHP script needs to have write access to it. It is recommended to use a folder that is not published on the Web server since the library will save some data of Yoctopuce devices into this folder.
Note: This feature is supported by YoctoHub and VirtualHub since version 27750.
Parameters : str_directory
the path of the folder that will be used as cache.
Returns :
nothing.
On failure, throws an exception.
www.yoctopuce.com
153
21. High-level API Reference
YAPI.SetTimeout() ySetTimeout()
YAPI
Invoke the specified callback function after a given timeout.
js es function ySetTimeout(
callback
,
ms_timeout
,
args
) function SetTimeout(
callback
,
ms_timeout
,
args
)
This function behaves more or less like Javascript setTimeout
, 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 timeout, in milliseconds.
args
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.
154 www.yoctopuce.com
21. High-level API Reference
YAPI.SetUSBPacketAckMs() ySetUSBPacketAckMs()
YAPI
Enables the acknowledge of every USB packet received by the Yoctopuce library.
java void SetUSBPacketAckMs( int
pktAckDelay
)
This function allows the library to run on Android phones that tend to loose USB packets. By default, this feature is disabled because it doubles the number of packets sent and slows down the API considerably. Therefore, the acknowledge of incoming USB packets should only be enabled on phones or tablets that loose USB packets. A delay of 50 milliseconds is generally enough. In case of doubt, contact Yoctopuce support. To disable USB packets acknowledge, call this function with the value 0.
Note: this feature is only available on Android.
Parameters : pktAckDelay
then number of milliseconds before the module
www.yoctopuce.com
155
21. High-level API Reference
YAPI.Sleep() ySleep()
YAPI
Pauses the execution flow for a specified duration.
js cpp m pas vb cs java uwp py php es function ySleep(
ms_duration
,
errmsg
)
YRETCODE ySleep( unsigned
ms_duration
, string&
errmsg
)
+(YRETCODE) Sleep :(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
) async Task<int> Sleep( ulong
ms_duration
) def Sleep(
ms_duration
,
errmsg
=None) function ySleep(
$ms_duration
,
&$errmsg
) function Sleep(
ms_duration
,
errmsg
)
This function implements a passive waiting loop, meaning that it does not consume CPU cycles significantly. 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, 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.
156 www.yoctopuce.com
21. High-level API Reference
YAPI.TestHub() yTestHub()
YAPI
Test if the hub is reachable.
cpp m pas vb cs java uwp py php es
YRETCODE yTestHub( const string&
url
, int
mstimeout
, string&
errmsg
)
+(YRETCODE) TestHub : (NSString*)
url
: (int)
mstimeout
: (NSError**)
errmsg
function yTestHub(
url
: string,
mstimeout
: integer, var
errmsg
: string): integer function yTestHub( ByVal
url
As String,
ByVal
mstimeout
As Integer,
ByRef
errmsg
As String) As Integer int TestHub( string
url
, int
mstimeout
, ref string
errmsg
) int TestHub( String
url
, int
mstimeout
) async Task<int> TestHub( string
url
, uint
mstimeout
) def TestHub(
url
,
mstimeout
,
errmsg
=None) function yTestHub(
$url
,
$mstimeout
,
&$errmsg
) function TestHub(
url
,
mstimeout
)
This method do not register the hub, it only test if the hub is usable. The url parameter follow the same convention as the
RegisterHub
method. This method is useful to verify the authentication parameters for a hub. It is possible to force this method to return after mstimeout milliseconds.
Parameters : url
a string containing either "usb","callback" or the root URL of the hub to monitor
mstimeout
the number of millisecond available to test the connection.
errmsg
a string passed by reference to receive any error message.
Returns :
YAPI_SUCCESS when the call succeeds.
On failure returns a negative error code.
www.yoctopuce.com
157
21. High-level API Reference
YAPI.TriggerHubDiscovery() yTriggerHubDiscovery()
YAPI
F o r c e a h u b d i s c o v e r y , i f a c a l l b a c k a s b e e n r e g i s t e r e d w i t h yRegisterHubDiscoveryCallback
it will be called for each net work hub that will respond to the discovery.
cpp m pas vb cs java uwp py
YRETCODE yTriggerHubDiscovery( string&
errmsg
)
+(YRETCODE) TriggerHubDiscovery : (NSError**)
errmsg
function yTriggerHubDiscovery( var
errmsg
: string): integer function yTriggerHubDiscovery( ByRef
errmsg
As String) As Integer int TriggerHubDiscovery( ref string
errmsg
) int TriggerHubDiscovery( ) async Task<int> TriggerHubDiscovery( ) def TriggerHubDiscovery(
errmsg
=None)
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.
158 www.yoctopuce.com
21. High-level API Reference
YAPI.UnregisterHub() yUnregisterHub()
YAPI
Setup the Yoctopuce library to no more use modules connected on a previously registered machine with RegisterHub.
js cpp m pas vb cs java uwp py php es function yUnregisterHub(
url
) void yUnregisterHub( const string&
url
)
+(void) UnregisterHub :(NSString *)
url
procedure yUnregisterHub(
url
: string) procedure yUnregisterHub( ByVal
url
As String) void UnregisterHub( string
url
) void UnregisterHub( String
url
) async Task UnregisterHub( string
url
) def UnregisterHub(
url
) function yUnregisterHub(
$url
) function UnregisterHub(
url
)
Parameters : url
a string containing either "usb" or the
www.yoctopuce.com
159
21. High-level API Reference
YAPI.UpdateDeviceList() yUpdateDeviceList()
YAPI
Triggers a (re)detection of connected Yoctopuce modules.
js cpp m pas vb cs java uwp py php es function yUpdateDeviceList(
errmsg
)
YRETCODE yUpdateDeviceList( string&
errmsg
)
+(YRETCODE) UpdateDeviceList :(NSError**)
errmsg
function yUpdateDeviceList( var
errmsg
: string): integer function yUpdateDeviceList( ByRef
errmsg
As String) As YRETCODE
YRETCODE UpdateDeviceList( ref string
errmsg
) int UpdateDeviceList( ) async Task<int> UpdateDeviceList( ) def UpdateDeviceList(
errmsg
=None) function yUpdateDeviceList(
&$errmsg
) function UpdateDeviceList(
errmsg
)
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.
160 www.yoctopuce.com
21. High-level API Reference
YAPI.UpdateDeviceList_async() yUpdateDeviceList_async()
YAPI
Triggers a (re)detection of connected Yoctopuce modules.
js function yUpdateDeviceList_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 is invoked when the result is known. The callback function receives three arguments: the caller-specific context object, the result code ( YAPI_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
161
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: js cpp m pas vb cs java uwp py php es
<script type='text/javascript' src='yocto_api.js'></script>
#include "yocto_api.h"
#import "yocto_api.h" uses yocto_api; yocto_api.vb
yocto_api.cs
import com.yoctopuce.YoctoAPI.YModule; import com.yoctopuce.YoctoAPI.YModule; from yocto_api import * require_once('yocto_api.php'); in HTML: <script src="../../lib/yocto_api.js"></script> in node.js: require('yoctolib-es2017/yocto_api.js');
Global functions
func
)
Allows you to find a module from its serial number or from its logical name.
yctx
,
func
)
Retrieves a module for a given identifier in a YAPI context.
Starts the enumeration of modules currently accessible.
YModule
methods
path
,
onlynew
)
Tests whether the byn file is valid for this module.
Invalidates the cache.
Returns a descriptive text that identifies the module.
pathname
)
Downloads the specified built-in file and returns a binary buffer with its content.
functionIndex
)
Retrieves the base type of the nth function on the module.
Returns the number of functions (beside the "module" interface) available on the module.
functionIndex
)
Retrieves the hardware identifier of the nth function on the module.
functionIndex
)
Retrieves the logical name of the nth function on the module.
functionIndex
)
Retrieves the type of the nth function on the module.
functionIndex
)
Retrieves the advertised value of the nth function on the module.
162 www.yoctopuce.com
21. High-level API Reference
Returns all the settings and uploaded files of the module.
Returns the state of the localization beacon.
Returns the error message of the latest error with this module object.
Returns the numerical error code of the latest error with this module object.
Returns the version of the firmware embedded in the module.
funType
)
Retrieve all hardware identifier that match the type passed in argument.
Returns the unique hardware identifier of the module.
Returns the icon of the module.
Returns a string with last logs of the module.
Returns the logical name of the module.
Returns the luminosity of the module informative leds (from 0 to 100).
Returns the serial number of the YoctoHub on which this module is connected.
Returns the current state of persistent module settings.
Returns the USB device identifier of the module.
Returns the commercial name of the module, as set by the factory.
Returns the hardware release version of the module.
Returns the remaining number of seconds before the module restarts, or zero when no reboot has been scheduled.
Returns the serial number of the module, as set by the factory.
Returns a list of all the modules that are plugged into the current module.
Returns the number of milliseconds spent since the module was powered on.
Returns the URL used to access the module.
Returns the current consumed by the module on the USB bus, in milli-amps.
Returns the value of the userData attribute, as previously stored using method set_userData
.
www.yoctopuce.com
163
21. High-level API Reference
Returns the value previously stored in this attribute.
funcId
)
Tests if the device includes a specific function.
Checks if the module is currently reachable, without raising any error.
callback
,
context
)
Checks if the module is currently reachable, without raising any error.
msValidity
)
Preloads the module cache with a specified validity duration.
msValidity
,
callback
,
context
)
Preloads the module cache with a specified validity duration (asynchronous version).
text
)
Adds a text message to the device logs.
Continues the module enumeration started using yFirstModule() .
secBeforeReboot
)
Schedules a simple module reboot after the given number of seconds.
callback
)
Registers a device log callback function.
Reloads the settings stored in the nonvolatile memory, as when the module is powered on.
Saves current settings in the nonvolatile memory of the module.
settings
)
Restores all the settings of the device.
settings
)
Restores all the settings and uploaded files to the module.
newval
)
Turns on or off the module localization beacon.
newval
)
Changes the logical name of the module.
newval
)
Changes the luminosity of the module informative leds.
data
)
Stores a user context provided as argument in the userData attribute of the function.
newval
)
Stores a 32 bit value in the device RAM.
secBeforeReboot
)
Schedules a module reboot into special firmware update mode.
path
)
Prepares a firmware update of the module.
path
,
force
)
Prepares a firmware update of the module.
callback
,
context
)
164 www.yoctopuce.com
21. High-level API Reference
Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.
www.yoctopuce.com
165
21. High-level API Reference
YModule.FindModule() yFindModule()
YModule
Allows you to find a module from its serial number or from its logical name.
js cpp m pas vb cs java uwp py php es function yFindModule(
func
)
YModule* yFindModule( string
func
)
+(YModule*) FindModule : (NSString*)
func
function yFindModule(
func
: string): TYModule function yFindModule( ByVal
func
As String) As YModule
YModule FindModule( string
func
)
YModule FindModule( String
func
)
YModule FindModule( string
func
) def FindModule(
func
) function yFindModule(
$func
) function FindModule(
func
)
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. If a call to this object's is_online() method returns FALSE although you are certain that the device is plugged, make sure that you did call registerHub() at application initialization time.
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.
166 www.yoctopuce.com
YModule.FindModuleInContext() yFindModuleInContext()
Retrieves a module for a given identifier in a YAPI context.
java uwp es
YModule FindModuleInContext( YAPIContext
yctx
, String
func
)
YModule FindModuleInContext( YAPIContext
yctx
, string
func
) function FindModuleInContext(
yctx
,
func
)
The identifier can be specified using several formats:
21. High-level API Reference
YModule
●
●
●
●
●
FunctionLogicalName
ModuleSerialNumber.FunctionIdentifier
ModuleSerialNumber.FunctionLogicalName
ModuleLogicalName.FunctionIdentifier
ModuleLogicalName.FunctionLogicalName
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 : yctx
a YAPI context
func
a string that uniquely characterizes the module
Returns :
a YModule object allowing you to drive the module.
www.yoctopuce.com
167
21. High-level API Reference
YModule.FirstModule() yFirstModule()
Starts the enumeration of modules currently accessible.
js cpp m pas vb cs java uwp py php es function yFirstModule( )
YModule* yFirstModule( )
+(YModule*) FirstModule function yFirstModule( ): TYModule function yFirstModule( ) As YModule
YModule FirstModule( )
YModule FirstModule( )
YModule FirstModule( ) def FirstModule( ) function yFirstModule( ) function FirstModule( )
Use the method
YModule.nextModule()
to iterate on the next modules.
YModule
Returns :
a pointer to a YModule object, corresponding to the first module currently online, or a null pointer if there are none.
168 www.yoctopuce.com
21. High-level API Reference
module
→
checkFirmware() YModule
Tests whether the byn file is valid for this module.
js cpp m pas vb cs java uwp py php es cmd function checkFirmware(
path
,
onlynew
) string checkFirmware( string
path
, bool
onlynew
)
-(NSString*) checkFirmware : (NSString*)
path
: (bool)
onlynew
function checkFirmware(
path
: string,
onlynew
: boolean): string function checkFirmware( ) As String string checkFirmware( string
path
, bool
onlynew
)
String checkFirmware( String
path
, boolean
onlynew
) async Task<string> checkFirmware( string
path
, bool
onlynew
) def checkFirmware(
path
,
onlynew
) function checkFirmware(
$path
,
$onlynew
) function checkFirmware(
path
,
onlynew
)
YModule
target
checkFirmware
path onlynew
This method is useful to test if the module needs to be updated. It is possible to pass a directory as argument instead of a file. In this case, this method returns the path of the most recent appropriate
.byn
file. If the parameter onlynew
is true, the function discards firmwares that are older or equal to the installed firmware.
Parameters : path
the path of a byn file or a directory that contains byn files
onlynew
returns only files that are strictly newer
Returns :
the path of the byn file to use or a empty string if no byn files matches the requirement
On failure, throws an exception or returns a string that start with "error:".
www.yoctopuce.com
169
21. High-level API Reference
module
→
clearCache() YModule
Invalidates the cache.
js cpp m pas vb cs java py php es function clearCache( ) void clearCache( )
-(void) clearCache procedure clearCache( ) procedure clearCache( ) void clearCache( ) void clearCache( ) def clearCache( ) function clearCache( ) function clearCache( )
Invalidates the cache of the module attributes. Forces the next call to get_xxx() or loadxxx() to use values that come from the device.
170 www.yoctopuce.com
module
→
describe()
Returns a descriptive text that identifies the module.
js cpp m pas vb cs java py php es function describe( ) string describe( )
-(NSString*) describe function describe( ): string function describe( ) As String string describe( )
String describe( ) def describe( ) function describe( ) function describe( )
The text may include either the logical name or the serial number of the module.
21. High-level API Reference
YModule
Returns :
a string that describes the module
www.yoctopuce.com
171
21. High-level API Reference
module
→
download()
Downloads the specified built-in file and returns a binary buffer with its content.
js cpp m pas vb cs java uwp py php es cmd function download(
pathname
) string download( string
pathname
)
-(NSMutableData*) download : (NSString*)
pathname
function download(
pathname
: string): TByteArray function download( ) As Byte byte[] download( string
pathname
) byte[] download( String
pathname
) async Task<byte[]> download( string
pathname
) def download(
pathname
) function download(
$pathname
) function 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 YAPI_INVALID_STRING .
YModule
172 www.yoctopuce.com
module
→
functionBaseType()
Retrieves the base type of the nth function on the module.
js cpp pas vb cs java py php es function functionBaseType(
functionIndex
) string functionBaseType( int
functionIndex
) function functionBaseType(
functionIndex
: integer): string function functionBaseType( ByVal
functionIndex
As Integer) As String string functionBaseType( int
functionIndex
)
String functionBaseType( int
functionIndex
) def functionBaseType(
functionIndex
) function functionBaseType(
$functionIndex
) function functionBaseType(
functionIndex
)
For instance, the base type of all measuring functions is "Sensor".
21. High-level API Reference
YModule
Parameters : functionIndex
the index of the function for which the information is desired, starting at 0 for the first function.
Returns :
a string corresponding to the base type of the function
On failure, throws an exception or returns an empty string.
www.yoctopuce.com
173
21. High-level API Reference
module
→
functionCount()
Returns the number of functions (beside the "module" interface) available on the module.
js cpp m pas vb cs java py php es function functionCount( ) int functionCount( )
-(int) functionCount function functionCount( ): integer function functionCount( ) As Integer int functionCount( ) int functionCount( ) def functionCount( ) function functionCount( ) function functionCount( )
YModule
Returns :
the number of functions on the module
On failure, throws an exception or returns a negative error code.
174 www.yoctopuce.com
module
→
functionId()
Retrieves the hardware identifier of the nth function on the module.
js cpp m pas vb cs java py php es function functionId(
functionIndex
) string functionId( int
functionIndex
)
-(NSString*) functionId : (int)
functionIndex
function functionId(
functionIndex
: integer): string function functionId( ByVal
functionIndex
As Integer) As String string functionId( int
functionIndex
)
String functionId( int
functionIndex
) def functionId(
functionIndex
) function functionId(
$functionIndex
) function functionId(
functionIndex
)
21. High-level API Reference
YModule
Parameters : functionIndex
the index of the function for which the information is desired, starting at 0 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.
www.yoctopuce.com
175
21. High-level API Reference
module
→
functionName()
Retrieves the logical name of the nth function on the module.
js cpp m pas vb cs java py php es 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 functionName( int
functionIndex
)
String functionName( int
functionIndex
) def functionName(
functionIndex
) function functionName(
$functionIndex
) function functionName(
functionIndex
)
YModule
Parameters : functionIndex
the index of the function for which the information is desired, starting at 0 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.
176 www.yoctopuce.com
module
→
functionType()
Retrieves the type of the nth function on the module.
js cpp pas vb cs java py php es function functionType(
functionIndex
) string functionType( int
functionIndex
) function functionType(
functionIndex
: integer): string function functionType( ByVal
functionIndex
As Integer) As String string functionType( int
functionIndex
)
String functionType( int
functionIndex
) def functionType(
functionIndex
) function functionType(
$functionIndex
) function functionType(
functionIndex
)
21. High-level API Reference
YModule
Parameters : functionIndex
the index of the function for which the information is desired, starting at 0 for the first function.
Returns :
a string corresponding to the type of the function
On failure, throws an exception or returns an empty string.
www.yoctopuce.com
177
21. High-level API Reference
module
→
functionValue()
Retrieves the advertised value of the nth function on the module.
js cpp m pas vb cs java py php es 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
)
String functionValue( int
functionIndex
) def functionValue(
functionIndex
) function functionValue(
$functionIndex
) function functionValue(
functionIndex
)
YModule
Parameters : functionIndex
the index of the function for which the information is desired, starting at 0 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.
178 www.yoctopuce.com
21. High-level API Reference
module
→
get_allSettings() module
→
allSettings()
YModule
Returns all the settings and uploaded files of the module.
js cpp m pas vb cs java uwp py php es cmd function get_allSettings( ) string get_allSettings( )
-(NSMutableData*) allSettings function get_allSettings( ): TByteArray function get_allSettings( ) As Byte byte[] get_allSettings( ) byte[] get_allSettings( ) async Task<byte[]> get_allSettings( ) def get_allSettings( ) function get_allSettings( ) function get_allSettings( )
YModule
target
get_allSettings
Useful to backup all the logical names, calibrations parameters, and uploaded files of a device.
Returns :
a binary buffer with all the settings.
On failure, throws an exception or returns an binary object of size 0.
www.yoctopuce.com
179
21. High-level API Reference
module
→
get_beacon() module
→
beacon()
Returns the state of the localization beacon.
js cpp m pas vb cs java uwp py php es cmd function get_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( ) async Task<int> get_beacon( ) def get_beacon( ) function get_beacon( ) function get_beacon( )
YModule
target
get_beacon
Returns :
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 .
YModule
180 www.yoctopuce.com
21. High-level API Reference
module
→
get_errorMessage() module
→
errorMessage()
Returns the error message of the latest error with this module object.
js cpp m pas vb cs java py php es 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( ) function get_errorMessage( ) function 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
www.yoctopuce.com
181
21. High-level API Reference
module
→
get_errorType() module
→
errorType()
Returns the numerical error code of the latest error with this module object.
js cpp pas vb cs java py php es function get_errorType( )
YRETCODE get_errorType( ) function get_errorType( ): YRETCODE function get_errorType( ) As YRETCODE
YRETCODE get_errorType( ) int get_errorType( ) def get_errorType( ) function get_errorType( ) function get_errorType( )
This method is mostly useful when using the Yoctopuce library with exceptions disabled.
YModule
Returns :
a number corresponding to the code of the latest error that occurred while using this module object
182 www.yoctopuce.com
module
→
get_firmwareRelease() module
→
firmwareRelease()
Returns the version of the firmware embedded in the module.
js cpp m pas vb cs java uwp py php es cmd function get_firmwareRelease( ) string get_firmwareRelease( )
-(NSString*) firmwareRelease function get_firmwareRelease( ): string function get_firmwareRelease( ) As String string get_firmwareRelease( )
String get_firmwareRelease( ) async Task<string> get_firmwareRelease( ) def get_firmwareRelease( ) function get_firmwareRelease( ) function 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_FIRMWARERELEASE_INVALID
.
21. High-level API Reference
YModule
www.yoctopuce.com
183
21. High-level API Reference
module
→
get_functionIds() module
→
functionIds()
Retrieve all hardware identifier that match the type passed in argument.
js cpp m pas vb cs java uwp py php es cmd function get_functionIds(
funType
) vector<string> get_functionIds( string
funType
)
-(NSMutableArray*) functionIds : (NSString*)
funType
function get_functionIds(
funType
: string): TStringArray function get_functionIds( ) As List
List<string> get_functionIds( string
funType
)
ArrayList<String> get_functionIds( String
funType
) async Task<List<string>> get_functionIds( string
funType
) def get_functionIds(
funType
) function get_functionIds(
$funType
) function get_functionIds(
funType
)
YModule
target
get_functionIds
funType
Parameters : funType
The type of function (Relay, LightSensor, Voltage,...)
Returns :
an array of strings.
YModule
184 www.yoctopuce.com
21. High-level API Reference
module
→
get_hardwareId() module
→
hardwareId()
YModule
Returns the unique hardware identifier of the module.
js cpp m vb cs java py php es function get_hardwareId( ) string get_hardwareId( )
-(NSString*) hardwareId function get_hardwareId( ) As String string get_hardwareId( )
String get_hardwareId( ) def get_hardwareId( ) function get_hardwareId( ) function get_hardwareId( )
The 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
185
21. High-level API Reference
module
→
get_icon2d() module
→
icon2d()
Returns the icon of the module.
js cpp m pas vb cs java uwp py php es cmd function get_icon2d( ) string get_icon2d( )
-(NSMutableData*) icon2d function get_icon2d( ): TByteArray function get_icon2d( ) As Byte byte[] get_icon2d( ) byte[] get_icon2d( ) async Task<byte[]> get_icon2d( ) def get_icon2d( ) function get_icon2d( ) function get_icon2d( )
YModule
target
get_icon2d
The icon is a PNG image and does not exceeds 1536 bytes.
YModule
Returns :
a binary buffer with module icon, in png format. On failure, throws an exception or returns
YAPI_INVALID_STRING .
186 www.yoctopuce.com
module
→
get_lastLogs() module
→
lastLogs()
Returns a string with last logs of the module.
js cpp m pas vb cs java uwp py php es cmd function get_lastLogs( ) string get_lastLogs( )
-(NSString*) lastLogs function get_lastLogs( ): string function get_lastLogs( ) As String string get_lastLogs( )
String get_lastLogs( ) async Task<string> get_lastLogs( ) def get_lastLogs( ) function get_lastLogs( ) function get_lastLogs( )
YModule
target
get_lastLogs
This method return only logs that are still in the module.
21. High-level API Reference
YModule
Returns :
a s t r i n g w i t h l a s t l o g s o f t h e m o d u l e . O n f a i l u r e , t h r o w s a n e x c e p t i o n o r r e t u r n s
YAPI_INVALID_STRING .
www.yoctopuce.com
187
21. High-level API Reference
module
→
get_logicalName() module
→
logicalName()
Returns the logical name of the module.
js cpp m pas vb cs java uwp py php es cmd function get_logicalName( ) string get_logicalName( )
-(NSString*) logicalName function get_logicalName( ): string function get_logicalName( ) As String string get_logicalName( )
String get_logicalName( ) async Task<string> get_logicalName( ) def get_logicalName( ) function get_logicalName( ) function 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
.
YModule
188 www.yoctopuce.com
21. High-level API Reference
module
→
get_luminosity() module
→
luminosity()
Returns the luminosity of the module informative leds (from 0 to 100).
js cpp m pas vb cs java uwp py php es cmd function get_luminosity( ) int get_luminosity( )
-(int) luminosity function get_luminosity( ): LongInt function get_luminosity( ) As Integer int get_luminosity( ) int get_luminosity( ) async Task<int> get_luminosity( ) def get_luminosity( ) function get_luminosity( ) function 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
.
YModule
www.yoctopuce.com
189
21. High-level API Reference
module
→
get_parentHub() module
→
parentHub()
YModule
Returns the serial number of the YoctoHub on which this module is connected.
js cpp m pas vb cs java py php cmd function get_parentHub( ) string get_parentHub( )
-(NSString*) parentHub function get_parentHub( ): string function get_parentHub( ) As String string get_parentHub( )
String get_parentHub( ) def get_parentHub( ) function get_parentHub( )
YModule
target
get_parentHub
If the module is connected by USB, or if the module is the root YoctoHub, an empty string is returned.
Returns :
a string with the serial number of the YoctoHub or an empty string
190 www.yoctopuce.com
module
→
get_persistentSettings() module
→
persistentSettings()
Returns the current state of persistent module settings.
js cpp m pas vb cs java uwp py php es cmd function get_persistentSettings( )
Y_PERSISTENTSETTINGS_enum get_persistentSettings( )
-(Y_PERSISTENTSETTINGS_enum) persistentSettings function get_persistentSettings( ): Integer function get_persistentSettings( ) As Integer int get_persistentSettings( ) int get_persistentSettings( ) async Task<int> get_persistentSettings( ) def get_persistentSettings( ) function get_persistentSettings( ) function get_persistentSettings( )
YModule
target
get_persistentSettings
21. High-level API Reference
YModule
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
.
www.yoctopuce.com
191
21. High-level API Reference
module
→
get_productId() module
→
productId()
Returns the USB device identifier of the module.
js cpp m pas vb cs java uwp py php es cmd function get_productId( ) int get_productId( )
-(int) productId function get_productId( ): LongInt function get_productId( ) As Integer int get_productId( ) int get_productId( ) async Task<int> get_productId( ) def get_productId( ) function get_productId( ) function get_productId( )
YModule
target
get_productId
Returns :
an integer corresponding to the USB device identifier of the module
On failure, throws an exception or returns
Y_PRODUCTID_INVALID
.
YModule
192 www.yoctopuce.com
module
→
get_productName() module
→
productName()
Returns the commercial name of the module, as set by the factory.
js cpp m pas vb cs java uwp py php es cmd function get_productName( ) string get_productName( )
-(NSString*) productName function get_productName( ): string function get_productName( ) As String string get_productName( )
String get_productName( ) async Task<string> get_productName( ) def get_productName( ) function get_productName( ) function 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
.
21. High-level API Reference
YModule
www.yoctopuce.com
193
21. High-level API Reference
module
→
get_productRelease() module
→
productRelease()
Returns the hardware release version of the module.
js cpp m pas vb cs java uwp py php es cmd function get_productRelease( ) int get_productRelease( )
-(int) productRelease function get_productRelease( ): LongInt function get_productRelease( ) As Integer int get_productRelease( ) int get_productRelease( ) async Task<int> get_productRelease( ) def get_productRelease( ) function get_productRelease( ) function 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
194 www.yoctopuce.com
21. High-level API Reference
module
→
get_rebootCountdown() module
→
rebootCountdown()
YModule
Returns the remaining number of seconds before the module restarts, or zero when no reboot has been scheduled.
js cpp m pas vb cs java uwp py php es cmd function get_rebootCountdown( ) int get_rebootCountdown( )
-(int) rebootCountdown function get_rebootCountdown( ): LongInt function get_rebootCountdown( ) As Integer int get_rebootCountdown( ) int get_rebootCountdown( ) async Task<int> get_rebootCountdown( ) def get_rebootCountdown( ) function get_rebootCountdown( ) function 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
.
www.yoctopuce.com
195
21. High-level API Reference
module
→
get_serialNumber() module
→
serialNumber()
Returns the serial number of the module, as set by the factory.
js cpp m pas vb cs java uwp py php es cmd function get_serialNumber( ) string get_serialNumber( )
-(NSString*) serialNumber function get_serialNumber( ): string function get_serialNumber( ) As String string get_serialNumber( )
String get_serialNumber( ) async Task<string> get_serialNumber( ) def get_serialNumber( ) function get_serialNumber( ) function 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_SERIALNUMBER_INVALID
.
YModule
196 www.yoctopuce.com
21. High-level API Reference
module
→
get_subDevices() module
→
subDevices()
YModule
Returns a list of all the modules that are plugged into the current module.
js cpp m pas vb cs java py php cmd function get_subDevices( ) vector<string> get_subDevices( )
-(NSMutableArray*) subDevices function get_subDevices( ): TStringArray function get_subDevices( ) As List
List<string> get_subDevices( )
ArrayList<String> get_subDevices( ) def get_subDevices( ) function get_subDevices( )
YModule
target
get_subDevices
This method only makes sense when called for a YoctoHub/VirtualHub. Otherwise, an empty array will be returned.
Returns :
an array of strings containing the sub modules.
www.yoctopuce.com
197
21. High-level API Reference
module
→
get_upTime() module
→
upTime()
Returns the number of milliseconds spent since the module was powered on.
js cpp m pas vb cs java uwp py php es cmd function get_upTime( ) s64 get_upTime( )
-(s64) upTime function get_upTime( ): int64 function get_upTime( ) As Long long get_upTime( ) long get_upTime( ) async Task<long> get_upTime( ) def get_upTime( ) function get_upTime( ) function 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
.
YModule
198 www.yoctopuce.com
module
→
get_url() module
→
url()
Returns the URL used to access the module.
js cpp m pas vb cs java py php cmd function get_url( ) string get_url( )
-(NSString*) url function get_url( ): string function get_url( ) As String string get_url( )
String get_url( ) def get_url( ) function get_url( )
YModule
target
get_url
If the module is connected by USB, the string 'usb' is returned.
Returns :
a string with the URL of the module.
21. High-level API Reference
YModule
www.yoctopuce.com
199
21. High-level API Reference
module
→
get_usbCurrent() module
→
usbCurrent()
Returns the current consumed by the module on the USB bus, in milli-amps.
js cpp m pas vb cs java uwp py php es cmd function get_usbCurrent( ) int get_usbCurrent( )
-(int) usbCurrent function get_usbCurrent( ): LongInt function get_usbCurrent( ) As Integer int get_usbCurrent( ) int get_usbCurrent( ) async Task<int> get_usbCurrent( ) def get_usbCurrent( ) function get_usbCurrent( ) function 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
.
YModule
200 www.yoctopuce.com
21. High-level API Reference
module
→
get_userData() module
→
userData()
YModule
Returns the value of the userData attribute, as previously stored using method set_userData
.
js cpp m pas vb cs java py php es function get_userData( ) void * get_userData( )
-(id) userData function get_userData( ): Tobject function get_userData( ) As Object object get_userData( )
Object get_userData( ) def get_userData( ) function get_userData( ) function 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
201
21. High-level API Reference
module
→
get_userVar() module
→
userVar()
Returns the value previously stored in this attribute.
js cpp m pas vb cs java uwp py php es cmd function get_userVar( ) int get_userVar( )
-(int) userVar function get_userVar( ): LongInt function get_userVar( ) As Integer int get_userVar( ) int get_userVar( ) async Task<int> get_userVar( ) def get_userVar( ) function get_userVar( ) function get_userVar( )
YModule
target
get_userVar
On startup and after a device reboot, the value is always reset to zero.
Returns :
an integer corresponding to the value previously stored in this attribute
On failure, throws an exception or returns
Y_USERVAR_INVALID
.
YModule
202 www.yoctopuce.com
module
→
hasFunction()
Tests if the device includes a specific function.
js cpp m pas vb cs java uwp py php es cmd function hasFunction(
funcId
) bool hasFunction( string
funcId
)
-(bool) hasFunction : (NSString*)
funcId
function hasFunction(
funcId
: string): boolean function hasFunction( ) As Boolean bool hasFunction( string
funcId
) boolean hasFunction( String
funcId
) async Task<bool> hasFunction( string
funcId
) def hasFunction(
funcId
) function hasFunction(
$funcId
) function hasFunction(
funcId
)
YModule
target
hasFunction
funcId
This method takes a function identifier and returns a boolean.
Parameters : funcId
the requested function identifier
Returns :
true if the device has the function identifier
21. High-level API Reference
YModule
www.yoctopuce.com
203
21. High-level API Reference
module
→
isOnline() YModule
Checks if the module is currently reachable, without raising any error.
js cpp m pas vb cs java py php es function isOnline( ) bool isOnline( )
-(BOOL) isOnline function isOnline( ): boolean function isOnline( ) As Boolean bool isOnline( ) boolean isOnline( ) def isOnline( ) function isOnline( ) function isOnline( )
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.
Returns :
true
if the module can be reached, and false
otherwise
204 www.yoctopuce.com
21. High-level API Reference
module
→
isOnline_async() YModule
Checks if the module is currently reachable, without raising any error.
js 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
205
21. High-level API Reference
module
→
load() YModule
Preloads the module cache with a specified validity duration.
js cpp m pas vb cs java py php es 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( ulong
msValidity
) int load( long
msValidity
) def load(
msValidity
) function load(
$msValidity
) function 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 traffic 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.
206 www.yoctopuce.com
21. High-level API Reference
module
→
load_async() YModule
Preloads the module cache with a specified validity duration (asynchronous version).
js 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 traffic for instance.
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 : 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
YAPI_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
207
21. High-level API Reference
module
→
log() YModule
Adds a text message to the device logs.
js cpp m pas vb cs java uwp py php es cmd function log(
text
) int log( string
text
)
-(int) log : (NSString*)
text
function log(
text
: string): LongInt function log( ) As Integer int log( string
text
) int log( String
text
) async Task<int> log( string
text
) def log(
text
) function log(
$text
) function log(
text
)
YModule
target
log
text
This function is useful in particular to trace the execution of HTTP callbacks. If a newline is desired after the message, it must be included in the string.
Parameters : text
the string to append to the logs.
Returns :
YAPI_SUCCESS if the call succeeds.
On failure, throws an exception or returns a negative error code.
208 www.yoctopuce.com
module
→
nextModule()
Continues the module enumeration started using yFirstModule()
.
js cpp m pas vb cs java uwp py php es function nextModule( )
YModule * nextModule( )
-(YModule*) nextModule function nextModule( ): TYModule function nextModule( ) As YModule
YModule nextModule( )
YModule nextModule( )
YModule nextModule( ) def nextModule( ) function nextModule( ) function nextModule( )
21. High-level API Reference
YModule
Returns :
a pointer to a YModule object, corresponding to the next module found, or a null pointer if there are no more modules to enumerate.
www.yoctopuce.com
209
21. High-level API Reference
module
→
reboot()
Schedules a simple module reboot after the given number of seconds.
js cpp m pas vb cs java uwp py php es cmd 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
) async Task<int> reboot( int
secBeforeReboot
) def reboot(
secBeforeReboot
) function reboot(
$secBeforeReboot
) function reboot(
secBeforeReboot
)
YModule
target
reboot
secBeforeReboot
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.
YModule
210 www.yoctopuce.com
21. High-level API Reference
module
→
registerLogCallback() YModule
Registers a device log callback function.
cpp m vb cs java py void registerLogCallback( YModuleLogCallback
callback
)
-(void) registerLogCallback : (YModuleLogCallback)
callback
function registerLogCallback( ByVal
callback
As YModuleLogCallback) As Integer int registerLogCallback( LogCallback
callback
) void registerLogCallback( LogCallback
callback
) def registerLogCallback(
callback
)
This callback will be called each time that a module sends a new log message. Mostly useful to debug a Yoctopuce module.
Parameters : callback
the callback function to call, or a null pointer. The callback function should take two arguments: the module object that emitted the log message, and the character string containing the log.
www.yoctopuce.com
211
21. High-level API Reference
module
→
revertFromFlash() YModule
Reloads the settings stored in the nonvolatile memory, as when the module is powered on.
js cpp m pas vb cs java uwp py php es cmd function revertFromFlash( ) int revertFromFlash( )
-(int) revertFromFlash function revertFromFlash( ): LongInt function revertFromFlash( ) As Integer int revertFromFlash( ) int revertFromFlash( ) async Task<int> revertFromFlash( ) def revertFromFlash( ) function revertFromFlash( ) function revertFromFlash( )
YModule
target
revertFromFlash
Returns :
YAPI_SUCCESS when the call succeeds.
On failure, throws an exception or returns a negative error code.
212 www.yoctopuce.com
21. High-level API Reference
module
→
saveToFlash() YModule
Saves current settings in the nonvolatile memory of the module.
js cpp m pas vb cs java uwp py php es cmd function saveToFlash( ) int saveToFlash( )
-(int) saveToFlash function saveToFlash( ): LongInt function saveToFlash( ) As Integer int saveToFlash( ) int saveToFlash( ) async Task<int> saveToFlash( ) def saveToFlash( ) function saveToFlash( ) function saveToFlash( )
YModule
target
saveToFlash
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
213
21. High-level API Reference
module
→
set_allSettings() module
→
setAllSettings()
YModule
Restores all the settings of the device.
js cpp m pas vb cs java uwp py php es cmd function set_allSettings(
settings
) int set_allSettings( string
settings
)
-(int) setAllSettings : (NSData*)
settings
function set_allSettings(
settings
: TByteArray): LongInt procedure set_allSettings( ) int set_allSettings( ) int set_allSettings( byte[]
settings
) async Task<int> set_allSettings( ) def set_allSettings(
settings
) function set_allSettings(
$settings
) function set_allSettings(
settings
)
YModule
target
set_allSettings
settings
Useful to restore all the logical names and calibrations parameters of a module from a backup.Remember to call the saveToFlash()
method of the module if the modifications must be kept.
Parameters : settings
a binary buffer with all the settings.
Returns :
YAPI_SUCCESS when the call succeeds.
On failure, throws an exception or returns a negative error code.
214 www.yoctopuce.com
21. High-level API Reference
module
→
set_allSettingsAndFiles() module
→
setAllSettingsAndFiles()
YModule
Restores all the settings and uploaded files to the module.
js cpp m pas vb cs java uwp py php es cmd function set_allSettingsAndFiles(
settings
) int set_allSettingsAndFiles( string
settings
)
-(int) setAllSettingsAndFiles : (NSData*)
settings
function set_allSettingsAndFiles(
settings
: TByteArray): LongInt procedure set_allSettingsAndFiles( ) int set_allSettingsAndFiles( ) int set_allSettingsAndFiles( byte[]
settings
) async Task<int> set_allSettingsAndFiles( ) def set_allSettingsAndFiles(
settings
) function set_allSettingsAndFiles(
$settings
) function set_allSettingsAndFiles(
settings
)
YModule
target
set_allSettingsAndFiles
settings
This method is useful to restore all the logical names and calibrations parameters, uploaded files etc. of a device from a backup. Remember to call the saveToFlash()
method of the module if the modifications must be kept.
Parameters : settings
a binary buffer with all the settings.
Returns :
YAPI_SUCCESS when the call succeeds.
On failure, throws an exception or returns a negative error code.
www.yoctopuce.com
215
21. High-level API Reference
module
→
set_beacon() module
→
setBeacon()
Turns on or off the module localization beacon.
js cpp m pas vb cs java uwp py php es cmd function set_beacon(
newval
) int set_beacon( Y_BEACON_enum
newval
)
-(int) setBeacon : (Y_BEACON_enum)
newval
function set_beacon(
newval
: Integer): integer function set_beacon( ByVal
newval
As Integer) As Integer int set_beacon( int
newval
) int set_beacon( int
newval
) async Task<int> set_beacon( int
newval
) def set_beacon(
newval
) function set_beacon(
$newval
) function 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.
YModule
216 www.yoctopuce.com
21. High-level API Reference
module
→
set_logicalName() module
→
setLogicalName()
Changes the logical name of the module.
js cpp m pas vb cs java uwp py php es cmd function set_logicalName(
newval
) int set_logicalName( const string&
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
) async Task<int> set_logicalName( string
newval
) def set_logicalName(
newval
) function set_logicalName(
$newval
) function set_logicalName(
newval
)
YModule
target
set_logicalName
newval
YModule
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 module
Returns :
YAPI_SUCCESS
if the call succeeds.
On failure, throws an exception or returns a negative error code.
www.yoctopuce.com
217
21. High-level API Reference
module
→
set_luminosity() module
→
setLuminosity()
Changes the luminosity of the module informative leds.
js cpp m pas vb cs java uwp py php es cmd function set_luminosity(
newval
) int set_luminosity( int
newval
)
-(int) setLuminosity : (int)
newval
function set_luminosity(
newval
: LongInt): integer function set_luminosity( ByVal
newval
As Integer) As Integer int set_luminosity( int
newval
) int set_luminosity( int
newval
) async Task<int> set_luminosity( int
newval
) def set_luminosity(
newval
) function set_luminosity(
$newval
) function set_luminosity(
newval
)
YModule
target
set_luminosity
newval
YModule
The parameter is a 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.
218 www.yoctopuce.com
21. High-level API Reference
module
→
set_userData() module
→
setUserData()
Stores a user context provided as argument in the userData attribute of the function.
js cpp m pas vb cs java py php es function set_userData(
data
) void set_userData( void*
data
)
-(void) setUserData : (id)
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
) function set_userData(
$data
) function set_userData(
data
)
This attribute is never touched by the API, and is at disposal of the caller to store a context.
YModule
Parameters : data
any kind of object to be stored
www.yoctopuce.com
219
21. High-level API Reference
module
→
set_userVar() module
→
setUserVar()
YModule
Stores a 32 bit value in the device RAM.
js cpp m pas vb cs java uwp py php es cmd function set_userVar(
newval
) int set_userVar( int
newval
)
-(int) setUserVar : (int)
newval
function set_userVar(
newval
: LongInt): integer function set_userVar( ByVal
newval
As Integer) As Integer int set_userVar( int
newval
) int set_userVar( int
newval
) async Task<int> set_userVar( int
newval
) def set_userVar(
newval
) function set_userVar(
$newval
) function set_userVar(
newval
)
YModule
target
set_userVar
newval
This attribute is at programmer disposal, should he need to store a state variable. On startup and after a device reboot, the value is always reset to zero.
Parameters : newval
an integer
Returns :
YAPI_SUCCESS
if the call succeeds.
On failure, throws an exception or returns a negative error code.
220 www.yoctopuce.com
module
→
triggerFirmwareUpdate()
Schedules a module reboot into special firmware update mode.
js cpp m pas vb cs java uwp py php es cmd 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
) async Task<int> triggerFirmwareUpdate( int
secBeforeReboot
) def triggerFirmwareUpdate(
secBeforeReboot
) function triggerFirmwareUpdate(
$secBeforeReboot
) function triggerFirmwareUpdate(
secBeforeReboot
)
YModule
target
triggerFirmwareUpdate
secBeforeReboot
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.
21. High-level API Reference
YModule
www.yoctopuce.com
221
21. High-level API Reference
module
→
updateFirmware()
Prepares a firmware update of the module.
js cpp m pas vb cs java uwp py php es cmd function updateFirmware(
path
)
YFirmwareUpdate updateFirmware( string
path
)
-(YFirmwareUpdate*) updateFirmware : (NSString*)
path
function updateFirmware(
path
: string): TYFirmwareUpdate function updateFirmware( ) As YFirmwareUpdate
YFirmwareUpdate updateFirmware( string
path
)
YFirmwareUpdate updateFirmware( String
path
) async Task<YFirmwareUpdate> updateFirmware( string
path
) def updateFirmware(
path
) function updateFirmware(
$path
) function updateFirmware(
path
)
YModule
target
updateFirmware
path
YModule
This method returns a
YFirmwareUpdate
object which handles the firmware update process.
Parameters : path
the path of the .byn
file to use.
Returns :
a
YFirmwareUpdate
object or NULL on error.
222 www.yoctopuce.com
21. High-level API Reference
module
→
updateFirmwareEx()
Prepares a firmware update of the module.
js cpp m pas vb cs java uwp py php es cmd function updateFirmwareEx(
path
,
force
)
YFirmwareUpdate updateFirmwareEx( string
path
, bool
force
)
-(YFirmwareUpdate*) updateFirmwareEx : (NSString*)
path
: (bool)
force
function updateFirmwareEx(
path
: string,
force
: boolean): TYFirmwareUpdate function updateFirmwareEx( ) As YFirmwareUpdate
YFirmwareUpdate updateFirmwareEx( string
path
, bool
force
)
YFirmwareUpdate updateFirmwareEx( String
path
, boolean
force
) async Task<YFirmwareUpdate> updateFirmwareEx( string
path
, bool
force
) def updateFirmwareEx(
path
,
force
) function updateFirmwareEx(
$path
,
$force
) function updateFirmwareEx(
path
,
force
)
YModule
target
updateFirmwareEx
path force
YModule
This method returns a
YFirmwareUpdate
object which handles the firmware update process.
Parameters : path
the path of the .byn
file to use.
force
true to force the firmware update even if some prerequisites appear not to be met
Returns :
a YFirmwareUpdate object or NULL on error.
www.yoctopuce.com
223
21. High-level API Reference
module
→
wait_async() YModule
Waits for all pending asynchronous commands on the module to complete, and invoke the userprovided callback function.
js es 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.
224 www.yoctopuce.com
21. High-level API Reference
21.3. Current function interface
The Yoctopuce class YCurrent allows you to read and configure Yoctopuce current sensors. It inherits from YSensor class the core functions to read measurements, to register callback functions, to access the autonomous datalogger.
In order to use the functions described here, you should include: js cpp m pas vb cs java uwp py php es
<script type='text/javascript' src='yocto_current.js'></script>
#include "yocto_current.h"
#import "yocto_current.h" uses yocto_current; yocto_current.vb
yocto_current.cs
import com.yoctopuce.YoctoAPI.YCurrent; import com.yoctopuce.YoctoAPI.YCurrent; from yocto_current import * require_once('yocto_current.php'); in HTML: <script src="../../lib/yocto_current.js"></script> in node.js: require('yoctolib-es2017/yocto_current.js');
Global functions
func
)
Retrieves a current sensor for a given identifier.
yctx
,
func
)
Retrieves a current sensor for a given identifier in a YAPI context.
Starts the enumeration of current sensors currently accessible.
yctx
)
Starts the enumeration of current sensors currently accessible.
YCurrent
methods
rawValues
,
refValues
)
Configures error correction data points, in particular to compensate for a possible perturbation of the measure caused by an enclosure.
Invalidates the cache.
Returns a short text that describes unambiguously the instance of the current sensor in the form
TYPE(NAME)=SERIAL.FUNCTIONID
.
Returns the current value of the current sensor (no more than 6 characters).
Returns the uncalibrated, unrounded raw value returned by the sensor, in mA, as a floating point number.
Returns the current value of the current, in mA, as a floating point number.
Returns the YDatalogger object of the device hosting the sensor.
Returns the error message of the latest error with the current sensor.
www.yoctopuce.com
225
21. High-level API Reference
Returns the numerical error code of the latest error with the current sensor.
Returns a global identifier of the current sensor in the format MODULE_NAME.FUNCTION_NAME
.
Returns a unique identifier of type YFUN_DESCR corresponding to the function.
Returns the hardware identifier of the current sensor, without reference to the module.
Returns the unique hardware identifier of the current sensor in the form
SERIAL.FUNCTIONID
.
Returns the maximal value observed for the current since the device was started.
Returns the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.
Returns the logical name of the current sensor.
Returns the minimal value observed for the current since the device was started.
Gets the YModule object for the device on which the function is located.
callback
,
context
)
Gets the
YModule
object for the device on which the function is located (asynchronous version).
startTime
,
endTime
)
Retrieves a DataSet object holding historical data for this sensor, for a specified time interval.
Returns the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.
Returns the resolution of the measured values.
Returns the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now.
Returns the measuring unit for the current.
Returns the value of the userData attribute, as previously stored using method set_userData .
Checks if the current sensor is currently reachable, without raising any error.
callback
,
context
)
Checks if the current sensor is currently reachable, without raising any error (asynchronous version).
Checks if the sensor is currently able to provide an up-to-date measure.
msValidity
)
Preloads the current sensor cache with a specified validity duration.
attrName
)
226 www.yoctopuce.com
21. High-level API Reference
Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.
rawValues
,
refValues
)
Retrieves error correction data points previously entered using the method calibrateFromPoints .
msValidity
,
callback
,
context
)
Preloads the current sensor cache with a specified validity duration (asynchronous version).
Disables the propagation of every new advertised value to the parent hub.
Continues the enumeration of current sensors started using yFirstCurrent() .
callback
)
Registers the callback function that is invoked on every periodic timed notification.
callback
)
Registers the callback function that is invoked on every change of advertised value.
newval
)
Changes the recorded maximal value observed.
newval
)
Changes the datalogger recording frequency for this function.
newval
)
Changes the logical name of the current sensor.
newval
)
Changes the recorded minimal value observed.
newval
)
Changes the timed value notification frequency for this function.
newval
)
Changes the resolution of the measured physical values.
data
)
Stores a user context provided as argument in the userData attribute of the function.
Starts the data logger on the device.
Stops the datalogger on the device.
Re-enables the propagation of every new advertised value to the parent hub.
callback
,
context
)
Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.
www.yoctopuce.com
227
21. High-level API Reference
YCurrent.FindCurrent() yFindCurrent()
Retrieves a current sensor for a given identifier.
js cpp m pas vb cs java uwp py php es function yFindCurrent(
func
)
YCurrent* yFindCurrent( string
func
)
+(YCurrent*) FindCurrent : (NSString*)
func
function yFindCurrent(
func
: string): TYCurrent function yFindCurrent( ByVal
func
As String) As YCurrent
YCurrent FindCurrent( string
func
)
YCurrent FindCurrent( String
func
)
YCurrent FindCurrent( string
func
) def FindCurrent(
func
) function yFindCurrent(
$func
) function FindCurrent(
func
)
The identifier can be specified using several formats:
YCurrent
●
FunctionLogicalName
●
ModuleSerialNumber.FunctionIdentifier
●
ModuleSerialNumber.FunctionLogicalName
●
ModuleLogicalName.FunctionIdentifier
●
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, then by logical name. If a call to this object's is_online() method returns FALSE although you are certain that the matching device is plugged, make sure that you did call registerHub() at application initialization time.
Parameters : func
a string that uniquely characterizes the current sensor
Returns :
a
YCurrent
object allowing you to drive the current sensor.
228 www.yoctopuce.com
YCurrent.FindCurrentInContext() yFindCurrentInContext()
Retrieves a current sensor for a given identifier in a YAPI context.
java uwp es
YCurrent FindCurrentInContext( YAPIContext
yctx
, String
func
)
YCurrent FindCurrentInContext( YAPIContext
yctx
, string
func
) function FindCurrentInContext(
yctx
,
func
)
The identifier can be specified using several formats:
21. High-level API Reference
YCurrent
●
●
●
●
●
FunctionLogicalName
ModuleSerialNumber.FunctionIdentifier
ModuleSerialNumber.FunctionLogicalName
ModuleLogicalName.FunctionIdentifier
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, then by logical name.
Parameters : yctx
a YAPI context
func
a string that uniquely characterizes the current sensor
Returns :
a YCurrent object allowing you to drive the current sensor.
www.yoctopuce.com
229
21. High-level API Reference
YCurrent.FirstCurrent() yFirstCurrent()
Starts the enumeration of current sensors currently accessible.
js cpp m pas vb cs java uwp py php es function yFirstCurrent( )
YCurrent* yFirstCurrent( )
+(YCurrent*) FirstCurrent function yFirstCurrent( ): TYCurrent function yFirstCurrent( ) As YCurrent
YCurrent FirstCurrent( )
YCurrent FirstCurrent( )
YCurrent FirstCurrent( ) def FirstCurrent( ) function yFirstCurrent( ) function 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.
230 www.yoctopuce.com
YCurrent.FirstCurrentInContext() yFirstCurrentInContext()
21. High-level API Reference
YCurrent
Starts the enumeration of current sensors currently accessible.
java uwp es
YCurrent FirstCurrentInContext( YAPIContext
yctx
)
YCurrent FirstCurrentInContext( YAPIContext
yctx
) function FirstCurrentInContext(
yctx
)
Use the method
YCurrent.nextCurrent()
to iterate on next current sensors.
Parameters : yctx
a YAPI context.
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
231
21. High-level API Reference
current
→
calibrateFromPoints() YCurrent
Configures error correction data points, in particular to compensate for a possible perturbation of the measure caused by an enclosure.
js cpp m pas vb cs java uwp py php es cmd function calibrateFromPoints(
rawValues
,
refValues
) int calibrateFromPoints( vector<double>
rawValues
, vector<double>
refValues
)
-(int) calibrateFromPoints : (NSMutableArray*)
rawValues
: (NSMutableArray*)
refValues
function calibrateFromPoints(
rawValues
: TDoubleArray,
refValues
: TDoubleArray): LongInt procedure calibrateFromPoints( ) int calibrateFromPoints( List<double>
rawValues
,
List<double>
refValues
) int calibrateFromPoints( ArrayList<Double>
rawValues
,
ArrayList<Double>
refValues
) async Task<int> calibrateFromPoints( List<double>
rawValues
,
List<double>
refValues
) def calibrateFromPoints(
rawValues
,
refValues
) function calibrateFromPoints(
$rawValues
,
$refValues
) function calibrateFromPoints(
rawValues
,
refValues
)
YCurrent
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 [email protected].
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 values for the correction points.
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
→
clearCache() YCurrent
Invalidates the cache.
js cpp m pas vb cs java py php es function clearCache( ) void clearCache( )
-(void) clearCache procedure clearCache( ) procedure clearCache( ) void clearCache( ) void clearCache( ) def clearCache( ) function clearCache( ) function clearCache( )
Invalidates the cache of the current sensor attributes. Forces the next call to get_xxx() or loadxxx() to use values that come from the device.
www.yoctopuce.com
233
21. High-level API Reference
current
→
describe() YCurrent
Returns a short text that describes unambiguously the instance of the current sensor in the form
TYPE(NAME)=SERIAL.FUNCTIONID
.
js cpp m pas vb cs java py php es function describe( ) string describe( )
-(NSString*) describe function describe( ): string function describe( ) As String string describe( )
String describe( ) def describe( ) function describe( ) function 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.relay1)=RELAYLO1-123456.relay1
if the module is already connected or
Relay(BadCustomeName.relay1)=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.relay1)=RELAYLO1-
123456.relay1
)
234 www.yoctopuce.com
current
→
get_advertisedValue() current
→
advertisedValue()
Returns the current value of the current sensor (no more than 6 characters).
js cpp m pas vb cs java uwp py php es cmd function get_advertisedValue( ) string get_advertisedValue( )
-(NSString*) advertisedValue function get_advertisedValue( ): string function get_advertisedValue( ) As String string get_advertisedValue( )
String get_advertisedValue( ) async Task<string> get_advertisedValue( ) def get_advertisedValue( ) function get_advertisedValue( ) function get_advertisedValue( )
YCurrent
target
get_advertisedValue
21. High-level API Reference
YCurrent
Returns :
a string corresponding to the current value of the current sensor (no more than 6 characters).
On failure, throws an exception or returns
Y_ADVERTISEDVALUE_INVALID
.
www.yoctopuce.com
235
21. High-level API Reference
current
→
get_currentRawValue() current
→
currentRawValue()
YCurrent
Returns the uncalibrated, unrounded raw value returned by the sensor, in mA, as a floating point number.
js cpp m pas vb cs java uwp py php es cmd function get_currentRawValue( ) double get_currentRawValue( )
-(double) currentRawValue function get_currentRawValue( ): double function get_currentRawValue( ) As Double double get_currentRawValue( ) double get_currentRawValue( ) async Task<double> get_currentRawValue( ) def get_currentRawValue( ) function get_currentRawValue( ) function get_currentRawValue( )
YCurrent
target
get_currentRawValue
Returns :
a floating point number corresponding to the uncalibrated, unrounded raw value returned by the sensor, in mA, as a floating point number
On failure, throws an exception or returns
Y_CURRENTRAWVALUE_INVALID
.
236 www.yoctopuce.com
current
→
get_currentValue() current
→
currentValue()
Returns the current value of the current, in mA, as a floating point number.
js cpp m pas vb cs java uwp py php es cmd function get_currentValue( ) double get_currentValue( )
-(double) currentValue function get_currentValue( ): double function get_currentValue( ) As Double double get_currentValue( ) double get_currentValue( ) async Task<double> get_currentValue( ) def get_currentValue( ) function get_currentValue( ) function get_currentValue( )
YCurrent
target
get_currentValue
21. High-level API Reference
YCurrent
Returns :
a floating point number corresponding to the current value of the current, in mA, as a floating point number
On failure, throws an exception or returns
Y_CURRENTVALUE_INVALID
.
www.yoctopuce.com
237
21. High-level API Reference
current
→
get_dataLogger() current
→
dataLogger()
YCurrent
Returns the YDatalogger object of the device hosting the sensor.
js cpp m pas vb cs java uwp py php es function get_dataLogger( )
YDataLogger* get_dataLogger( )
-(YDataLogger*) dataLogger function get_dataLogger( ): TYDataLogger function get_dataLogger( ) As YDataLogger
YDataLogger get_dataLogger( )
YDataLogger get_dataLogger( ) async Task<YDataLogger> get_dataLogger( ) def get_dataLogger( ) function get_dataLogger( ) function get_dataLogger( )
This method returns an object of class YDatalogger that can control global parameters of the data logger. The returned object should not be freed.
Returns :
an YDataLogger object or null on error.
238 www.yoctopuce.com
21. High-level API Reference
current
→
get_errorMessage() current
→
errorMessage()
Returns the error message of the latest error with the current sensor.
js cpp m pas vb cs java py php es 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( ) function get_errorMessage( ) function get_errorMessage( )
This method is mostly useful when using the Yoctopuce library with exceptions disabled.
YCurrent
Returns :
a string corresponding to the latest error message that occured while using the current sensor object
www.yoctopuce.com
239
21. High-level API Reference
current
→
get_errorType() current
→
errorType()
Returns the numerical error code of the latest error with the current sensor.
js cpp pas vb cs java py php es function get_errorType( )
YRETCODE get_errorType( ) function get_errorType( ): YRETCODE function get_errorType( ) As YRETCODE
YRETCODE get_errorType( ) int get_errorType( ) def get_errorType( ) function get_errorType( ) function get_errorType( )
This method is mostly useful when using the Yoctopuce library with exceptions disabled.
YCurrent
Returns :
a number corresponding to the code of the latest error that occurred while using the current sensor object
240 www.yoctopuce.com
21. High-level API Reference
current
→
get_friendlyName() current
→
friendlyName()
YCurrent
Returns a global identifier of the current sensor in the format
MODULE_NAME.FUNCTION_NAME
.
js cpp m cs java py php es function get_friendlyName( ) string get_friendlyName( )
-(NSString*) friendlyName string get_friendlyName( )
String get_friendlyName( ) def get_friendlyName( ) function get_friendlyName( ) function 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 example:
MyCustomName.relay1
)
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
241
21. High-level API Reference
current
→
get_functionDescriptor() current
→
functionDescriptor()
YCurrent
Returns a unique identifier of type
YFUN_DESCR
corresponding to the function.
js cpp m pas vb cs java py php es 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( ) function get_functionDescriptor( ) function 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 .
I f t h e f u n c t i o n h a s n e v e r b e e n c o n t a c t e d , t h e r e t u r n e d v a l u e i s
Y _ F U N C T I O N D E S C R I P T O R _ I N V A L I D .
242 www.yoctopuce.com
21. High-level API Reference
current
→
get_functionId() current
→
functionId()
Returns the hardware identifier of the current sensor, without reference to the module.
js cpp m vb cs java py php es function get_functionId( ) string get_functionId( )
-(NSString*) functionId function get_functionId( ) As String string get_functionId( )
String get_functionId( ) def get_functionId( ) function get_functionId( ) function get_functionId( )
YCurrent
For example relay1
Returns :
a string that identifies the current sensor (ex: relay1 )
On failure, throws an exception or returns Y_FUNCTIONID_INVALID .
www.yoctopuce.com
243
21. High-level API Reference
current
→
get_hardwareId() current
→
hardwareId()
YCurrent
Returns the unique hardware identifier of the current sensor in the form
SERIAL.FUNCTIONID
.
js cpp m vb cs java py php es function get_hardwareId( ) string get_hardwareId( )
-(NSString*) hardwareId function get_hardwareId( ) As String string get_hardwareId( )
String get_hardwareId( ) def get_hardwareId( ) function get_hardwareId( ) function get_hardwareId( )
The unique hardware identifier is composed of the device serial number and of the hardware identifier of the current sensor (for example
RELAYLO1-123456.relay1
).
Returns :
a string that uniquely identifies the current sensor (ex:
RELAYLO1-123456.relay1
)
On failure, throws an exception or returns
Y_HARDWAREID_INVALID
.
244 www.yoctopuce.com
21. High-level API Reference
current
→
get_highestValue() current
→
highestValue()
Returns the maximal value observed for the current since the device was started.
js cpp m pas vb cs java uwp py php es cmd function get_highestValue( ) double get_highestValue( )
-(double) highestValue function get_highestValue( ): double function get_highestValue( ) As Double double get_highestValue( ) double get_highestValue( ) async Task<double> get_highestValue( ) def get_highestValue( ) function get_highestValue( ) function get_highestValue( )
YCurrent
target
get_highestValue
YCurrent
Returns :
a floating point number corresponding to the maximal value observed for the current since the device was started
On failure, throws an exception or returns
Y_HIGHESTVALUE_INVALID
.
www.yoctopuce.com
245
21. High-level API Reference
current
→
get_logFrequency() current
→
logFrequency()
YCurrent
Returns the datalogger recording frequency for this function, or "OFF" when measures are not stored in the data logger flash memory.
js cpp m pas vb cs java uwp py php es cmd function get_logFrequency( ) string get_logFrequency( )
-(NSString*) logFrequency function get_logFrequency( ): string function get_logFrequency( ) As String string get_logFrequency( )
String get_logFrequency( ) async Task<string> get_logFrequency( ) def get_logFrequency( ) function get_logFrequency( ) function 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
.
246 www.yoctopuce.com
current
→
get_logicalName() current
→
logicalName()
Returns the logical name of the current sensor.
js cpp m pas vb cs java uwp py php es cmd function get_logicalName( ) string get_logicalName( )
-(NSString*) logicalName function get_logicalName( ): string function get_logicalName( ) As String string get_logicalName( )
String get_logicalName( ) async Task<string> get_logicalName( ) def get_logicalName( ) function get_logicalName( ) function 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
.
21. High-level API Reference
YCurrent
www.yoctopuce.com
247
21. High-level API Reference
current
→
get_lowestValue() current
→
lowestValue()
Returns the minimal value observed for the current since the device was started.
js cpp m pas vb cs java uwp py php es cmd function get_lowestValue( ) double get_lowestValue( )
-(double) lowestValue function get_lowestValue( ): double function get_lowestValue( ) As Double double get_lowestValue( ) double get_lowestValue( ) async Task<double> get_lowestValue( ) def get_lowestValue( ) function get_lowestValue( ) function get_lowestValue( )
YCurrent
target
get_lowestValue
YCurrent
Returns :
a floating point number corresponding to the minimal value observed for the current since the device was started
On failure, throws an exception or returns
Y_LOWESTVALUE_INVALID
.
248 www.yoctopuce.com
21. High-level API Reference
current
→
get_module() current
→
module()
YCurrent
Gets the
YModule
object for the device on which the function is located.
js cpp m pas vb cs java py php es 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( ) function get_module( ) function get_module( )
If the function cannot be located on any module, the returned instance of
YModule
is not shown as online.
Returns :
an instance of YModule
www.yoctopuce.com
249
21. High-level API Reference
current
→
get_module_async() current
→
module_async()
YCurrent
Gets the
YModule
object for the device on which the function is located (asynchronous version).
js function get_module_async(
callback
,
context
)
If the function cannot be located on any module, the returned
YModule
object does not show as online.
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 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.
250 www.yoctopuce.com
21. High-level API Reference
current
→
get_recordedData() current
→
recordedData()
YCurrent
Retrieves a DataSet object holding historical data for this sensor, for a specified time interval.
js cpp m pas vb cs java uwp py php es cmd 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
) async Task<YDataSet> get_recordedData( long
startTime
, long
endTime
) def get_recordedData(
startTime
,
endTime
) function get_recordedData(
$startTime
,
$endTime
) function 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 data logger.
This function only works if the device uses a recent firmware, as DataSet objects are not supported by firmwares older than version 13000.
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
251
21. High-level API Reference
current
→
get_reportFrequency() current
→
reportFrequency()
YCurrent
Returns the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function.
js cpp m pas vb cs java uwp py php es cmd function get_reportFrequency( ) string get_reportFrequency( )
-(NSString*) reportFrequency function get_reportFrequency( ): string function get_reportFrequency( ) As String string get_reportFrequency( )
String get_reportFrequency( ) async Task<string> get_reportFrequency( ) def get_reportFrequency( ) function get_reportFrequency( ) function get_reportFrequency( )
YCurrent
target
get_reportFrequency
Returns :
a string corresponding to the timed value notification frequency, or "OFF" if timed value notifications are disabled for this function
On failure, throws an exception or returns
Y_REPORTFREQUENCY_INVALID
.
252 www.yoctopuce.com
21. High-level API Reference
current
→
get_resolution() current
→
resolution()
YCurrent
Returns the resolution of the measured values.
js cpp m pas vb cs java uwp py php es cmd function get_resolution( ) double get_resolution( )
-(double) resolution function get_resolution( ): double function get_resolution( ) As Double double get_resolution( ) double get_resolution( ) async Task<double> get_resolution( ) def get_resolution( ) function get_resolution( ) function 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
253
21. High-level API Reference
current
→
get_sensorState() current
→
sensorState()
YCurrent
Returns the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now.
js cpp m pas vb cs java uwp py php es cmd function get_sensorState( ) int get_sensorState( )
-(int) sensorState function get_sensorState( ): LongInt function get_sensorState( ) As Integer int get_sensorState( ) int get_sensorState( ) async Task<int> get_sensorState( ) def get_sensorState( ) function get_sensorState( ) function get_sensorState( )
YCurrent
target
get_sensorState
Returns :
an integer corresponding to the sensor health state code, which is zero when there is an up-to-date measure available or a positive code if the sensor is not able to provide a measure right now
On failure, throws an exception or returns
Y_SENSORSTATE_INVALID
.
254 www.yoctopuce.com
current
→
get_unit() current
→
unit()
Returns the measuring unit for the current.
js cpp m pas vb cs java uwp py php es cmd function get_unit( ) string get_unit( )
-(NSString*) unit function get_unit( ): string function get_unit( ) As String string get_unit( )
String get_unit( ) async Task<string> get_unit( ) def get_unit( ) function get_unit( ) function get_unit( )
YCurrent
target
get_unit
Returns :
a string corresponding to the measuring unit for the current
On failure, throws an exception or returns
Y_UNIT_INVALID
.
21. High-level API Reference
YCurrent
www.yoctopuce.com
255
21. High-level API Reference
current
→
get_userData() current
→
userData()
YCurrent
Returns the value of the userData attribute, as previously stored using method set_userData
.
js cpp m pas vb cs java py php es function get_userData( ) void * get_userData( )
-(id) userData function get_userData( ): Tobject function get_userData( ) As Object object get_userData( )
Object get_userData( ) def get_userData( ) function get_userData( ) function 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.
256 www.yoctopuce.com
21. High-level API Reference
current
→
isOnline() YCurrent
Checks if the current sensor is currently reachable, without raising any error.
js cpp m pas vb cs java py php es function isOnline( ) bool isOnline( )
-(BOOL) isOnline function isOnline( ): boolean function isOnline( ) As Boolean bool isOnline( ) boolean isOnline( ) def isOnline( ) function isOnline( ) function 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 :
true
if the current sensor can be reached, and false
otherwise
www.yoctopuce.com
257
21. High-level API Reference
current
→
isOnline_async() YCurrent
Checks if the current sensor is currently reachable, without raising any error (asynchronous version).
js 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.
258 www.yoctopuce.com
21. High-level API Reference
current
→
isSensorReady() YCurrent
Checks if the sensor is currently able to provide an up-to-date measure.
cmd
YCurrent
target
isSensorReady
Returns false if the device is unreachable, or if the sensor does not have a current measure to transmit.
No exception is raised if there is an error while trying to contact the device hosting $THEFUNCTION$.
Returns :
true if the sensor can provide an up-to-date measure, and false otherwise
www.yoctopuce.com
259
21. High-level API Reference
current
→
load() YCurrent
Preloads the current sensor cache with a specified validity duration.
js cpp m pas vb cs java py php es 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( ulong
msValidity
) int load( long
msValidity
) def load(
msValidity
) function load(
$msValidity
) function 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 traffic 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.
260 www.yoctopuce.com
21. High-level API Reference
current
→
loadAttribute() YCurrent
Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.
js cpp m pas vb cs java uwp py php es function loadAttribute(
attrName
) string loadAttribute( string
attrName
)
-(NSString*) loadAttribute : (NSString*)
attrName
function loadAttribute(
attrName
: string): string function loadAttribute( ) As String string loadAttribute( string
attrName
)
String loadAttribute( String
attrName
) async Task<string> loadAttribute( string
attrName
) def loadAttribute(
attrName
) function loadAttribute(
$attrName
) function loadAttribute(
attrName
)
Parameters : attrName
the name of the requested attribute
Returns :
a string with the value of the the attribute
On failure, throws an exception or returns an empty string.
www.yoctopuce.com
261
21. High-level API Reference
current
→
loadCalibrationPoints() YCurrent
R e t r i e v e s e r r o r c o r r e c t i o n d a t a p o i n t s p r e v i o u s l y e n t e r e d u s i n g t h e m e t h o d c a l i b r a t e F r o m P o i n t s
.
js cpp m pas vb cs java uwp py php es cmd function loadCalibrationPoints(
rawValues
,
refValues
) int loadCalibrationPoints( vector<double>&
rawValues
, vector<double>&
refValues
)
-(int) loadCalibrationPoints : (NSMutableArray*)
rawValues
: (NSMutableArray*)
refValues
function loadCalibrationPoints( var
rawValues
: TDoubleArray, var
refValues
: TDoubleArray): LongInt procedure loadCalibrationPoints( ) int loadCalibrationPoints( List<double>
rawValues
,
List<double>
refValues
) int loadCalibrationPoints( ArrayList<Double>
rawValues
,
ArrayList<Double>
refValues
) async Task<int> loadCalibrationPoints( List<double>
rawValues
,
List<double>
refValues
) def loadCalibrationPoints(
rawValues
,
refValues
) function loadCalibrationPoints(
&$rawValues
,
&$refValues
) function 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.
262 www.yoctopuce.com
21. High-level API Reference
current
→
load_async() YCurrent
Preloads the current sensor cache with a specified validity duration (asynchronous version).
js 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 function receives three arguments: the caller-specific context object, the receiving function object and the error code
(or YAPI_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
263
21. High-level API Reference
current
→
muteValueCallbacks() YCurrent
Disables the propagation of every new advertised value to the parent hub.
js cpp m pas vb cs java uwp py php es cmd function muteValueCallbacks( ) int muteValueCallbacks( )
-(int) muteValueCallbacks function muteValueCallbacks( ): LongInt function muteValueCallbacks( ) As Integer int muteValueCallbacks( ) int muteValueCallbacks( ) async Task<int> muteValueCallbacks( ) def muteValueCallbacks( ) function muteValueCallbacks( ) function muteValueCallbacks( )
YCurrent
target
muteValueCallbacks
You can use this function to save bandwidth and CPU on computers with limited resources, or to prevent unwanted invocations of the HTTP callback. Remember to call the saveToFlash()
method of the module if the modification must be kept.
Returns :
YAPI_SUCCESS when the call succeeds.
On failure, throws an exception or returns a negative error code.
264 www.yoctopuce.com
21. High-level API Reference
current
→
nextCurrent()
Continues the enumeration of current sensors started using yFirstCurrent()
.
js cpp m pas vb cs java uwp py php es function nextCurrent( )
YCurrent * nextCurrent( )
-(YCurrent*) nextCurrent function nextCurrent( ): TYCurrent function nextCurrent( ) As YCurrent
YCurrent nextCurrent( )
YCurrent nextCurrent( )
YCurrent nextCurrent( ) def nextCurrent( ) function nextCurrent( ) function nextCurrent( )
YCurrent
Returns :
a pointer to a YCurrent object, corresponding to a current sensor currently online, or a null pointer if there are no more current sensors to enumerate.
www.yoctopuce.com
265
21. High-level API Reference
current
→
registerTimedReportCallback()
Registers the callback function that is invoked on every periodic timed notification.
js cpp m pas vb cs java uwp py php es function registerTimedReportCallback(
callback
) int registerTimedReportCallback( YCurrentTimedReportCallback
callback
)
-(int) registerTimedReportCallback : (YCurrentTimedReportCallback)
callback
function registerTimedReportCallback(
callback
: TYCurrentTimedReportCallback): LongInt function registerTimedReportCallback( ) As Integer int registerTimedReportCallback( TimedReportCallback
callback
) int registerTimedReportCallback( TimedReportCallback
callback
) async Task<int> registerTimedReportCallback( TimedReportCallback
callback
) def registerTimedReportCallback(
callback
) function registerTimedReportCallback(
$callback
) function registerTimedReportCallback(
callback
)
YCurrent
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.
266 www.yoctopuce.com
21. High-level API Reference
current
→
registerValueCallback()
Registers the callback function that is invoked on every change of advertised value.
js cpp m pas vb cs java uwp py php es 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( UpdateCallback
callback
) async Task<int> registerValueCallback( ValueCallback
callback
) def registerValueCallback(
callback
) function registerValueCallback(
$callback
) function registerValueCallback(
callback
)
YCurrent
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
267
21. High-level API Reference
current
→
set_highestValue() current
→
setHighestValue()
Changes the recorded maximal value observed.
js cpp m pas vb cs java uwp py php es cmd function set_highestValue(
newval
) int set_highestValue( double
newval
)
-(int) setHighestValue : (double)
newval
function set_highestValue(
newval
: double): integer function set_highestValue( ByVal
newval
As Double) As Integer int set_highestValue( double
newval
) int set_highestValue( double
newval
) async Task<int> set_highestValue( double
newval
) def set_highestValue(
newval
) function set_highestValue(
$newval
) function 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
268 www.yoctopuce.com
21. High-level API Reference
current
→
set_logFrequency() current
→
setLogFrequency()
YCurrent
Changes the datalogger recording frequency for this function.
js cpp m pas vb cs java uwp py php es cmd function set_logFrequency(
newval
) int set_logFrequency( const string&
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
) async Task<int> set_logFrequency( string
newval
) def set_logFrequency(
newval
) function set_logFrequency(
$newval
) function set_logFrequency(
newval
)
YCurrent
target
set_logFrequency
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 recording for this function, use the value "OFF".
Parameters : newval
a string corresponding to the datalogger recording frequency for this function
Returns :
YAPI_SUCCESS
if the call succeeds.
On failure, throws an exception or returns a negative error code.
www.yoctopuce.com
269
21. High-level API Reference
current
→
set_logicalName() current
→
setLogicalName()
Changes the logical name of the current sensor.
js cpp m pas vb cs java uwp py php es cmd function set_logicalName(
newval
) int set_logicalName( const string&
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
) async Task<int> set_logicalName( string
newval
) def set_logicalName(
newval
) function set_logicalName(
$newval
) function set_logicalName(
newval
)
YCurrent
target
set_logicalName
newval
YCurrent
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.
270 www.yoctopuce.com
current
→
set_lowestValue() current
→
setLowestValue()
Changes the recorded minimal value observed.
js cpp m pas vb cs java uwp py php es cmd 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
) async Task<int> set_lowestValue( double
newval
) def set_lowestValue(
newval
) function set_lowestValue(
$newval
) function 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.
21. High-level API Reference
YCurrent
www.yoctopuce.com
271
21. High-level API Reference
current
→
set_reportFrequency() current
→
setReportFrequency()
YCurrent
Changes the timed value notification frequency for this function.
js cpp m pas vb cs java uwp py php es cmd function set_reportFrequency(
newval
) int set_reportFrequency( const string&
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
) async Task<int> set_reportFrequency( string
newval
) def set_reportFrequency(
newval
) function set_reportFrequency(
$newval
) function 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.
272 www.yoctopuce.com
21. High-level API Reference
current
→
set_resolution() current
→
setResolution()
YCurrent
Changes the resolution of the measured physical values.
js cpp m pas vb cs java uwp py php es cmd function set_resolution(
newval
) int set_resolution( double
newval
)
-(int) setResolution : (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
) async Task<int> set_resolution( double
newval
) def set_resolution(
newval
) function set_resolution(
$newval
) function 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 physical values
Returns :
YAPI_SUCCESS
if the call succeeds.
On failure, throws an exception or returns a negative error code.
www.yoctopuce.com
273
21. High-level API Reference
current
→
set_userData() current
→
setUserData()
Stores a user context provided as argument in the userData attribute of the function.
js cpp m pas vb cs java py php es function set_userData(
data
) void set_userData( void*
data
)
-(void) setUserData : (id)
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
) function set_userData(
$data
) function set_userData(
data
)
This attribute is never touched by the API, and is at disposal of the caller to store a context.
YCurrent
Parameters : data
any kind of object to be stored
274 www.yoctopuce.com
21. High-level API Reference
current
→
startDataLogger() YCurrent
Starts the data logger on the device.
js cpp m pas vb cs java uwp py php es cmd function startDataLogger( ) int startDataLogger( )
-(int) startDataLogger function startDataLogger( ): LongInt function startDataLogger( ) As Integer int startDataLogger( ) int startDataLogger( ) async Task<int> startDataLogger( ) def startDataLogger( ) function startDataLogger( ) function startDataLogger( )
YCurrent
target
startDataLogger
Note that the data logger will only save the measures on this sensor if the logFrequency is not set to
"OFF".
Returns :
YAPI_SUCCESS if the call succeeds.
www.yoctopuce.com
275
21. High-level API Reference
current
→
stopDataLogger()
Stops the datalogger on the device.
js cpp m pas vb cs java uwp py php es cmd function stopDataLogger( ) int stopDataLogger( )
-(int) stopDataLogger function stopDataLogger( ): LongInt function stopDataLogger( ) As Integer int stopDataLogger( ) int stopDataLogger( ) async Task<int> stopDataLogger( ) def stopDataLogger( ) function stopDataLogger( ) function stopDataLogger( )
YCurrent
target
stopDataLogger
Returns :
YAPI_SUCCESS if the call succeeds.
YCurrent
276 www.yoctopuce.com
current
→
unmuteValueCallbacks()
Re-enables the propagation of every new advertised value to the parent hub.
js cpp m pas vb cs java uwp py php es cmd function unmuteValueCallbacks( ) int unmuteValueCallbacks( )
-(int) unmuteValueCallbacks function unmuteValueCallbacks( ): LongInt function unmuteValueCallbacks( ) As Integer int unmuteValueCallbacks( ) int unmuteValueCallbacks( ) async Task<int> unmuteValueCallbacks( ) def unmuteValueCallbacks( ) function unmuteValueCallbacks( ) function unmuteValueCallbacks( )
YCurrent
target
unmuteValueCallbacks
21. High-level API Reference
YCurrent
This function reverts the effect of a previous call to muteValueCallbacks()
. Remember to call the saveToFlash()
method of the module if the modification must be kept.
Returns :
YAPI_SUCCESS
when the call succeeds.
On failure, throws an exception or returns a negative error code.
www.yoctopuce.com
277
21. High-level API Reference
current
→
wait_async() YCurrent
Waits for all pending asynchronous commands on the module to complete, and invoke the userprovided callback function.
js es 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.
278 www.yoctopuce.com
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: js cpp m pas vb cs java uwp py php es
<script type='text/javascript' src='yocto_api.js'></script>
#include "yocto_api.h"
#import "yocto_api.h" uses yocto_api; yocto_api.vb
yocto_api.cs
import com.yoctopuce.YoctoAPI.YModule; import com.yoctopuce.YoctoAPI.YModule; from yocto_api import * require_once('yocto_api.php'); in HTML: <script src="../../lib/yocto_api.js"></script> in node.js: require('yoctolib-es2017/yocto_api.js');
func
)
Retrieves a data logger for a given identifier.
Global functions
yctx
,
func
)
Retrieves a data logger for a given identifier in a YAPI context.
Starts the enumeration of data loggers currently accessible.
yctx
)
Starts the enumeration of data loggers currently accessible.
YDataLogger
methods
Invalidates the cache.
Returns a short text that describes unambiguously the instance of the data logger in the form
TYPE(NAME)=SERIAL.FUNCTIONID
.
Clears the data logger memory and discards all recorded data streams.
Returns the current value of the data logger (no more than 6 characters).
Returns the default activation state of the data logger on power up.
Returns true if the data logger is synchronised with the localization beacon.
Returns the current run number, corresponding to the number of times the module was powered on with the dataLogger enabled at some point.
Returns a list of YDataSet objects that can be used to retrieve all measures stored by the data logger.
v
)
www.yoctopuce.com
279
21. High-level API Reference
Builds a list of all data streams hold by the data logger (legacy method).
Returns the error message of the latest error with the data logger.
Returns the numerical error code of the latest error with the data logger.
Returns a global identifier of the data logger in the format MODULE_NAME.FUNCTION_NAME
.
Returns a unique identifier of type YFUN_DESCR corresponding to the function.
Returns the hardware identifier of the data logger, without reference to the module.
Returns the unique hardware identifier of the data logger in the form
SERIAL.FUNCTIONID
.
Returns the logical name of the data logger.
Gets the YModule object for the device on which the function is located.
callback
,
context
)
Gets the YModule object for the device on which the function is located (asynchronous version).
Returns the current activation state of the data logger.
Returns the Unix timestamp for current UTC time, if known.
Returns the value of the userData attribute, as previously stored using method set_userData .
Checks if the data logger is currently reachable, without raising any error.
callback
,
context
)
Checks if the data logger is currently reachable, without raising any error (asynchronous version).
msValidity
)
Preloads the data logger cache with a specified validity duration.
attrName
)
Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.
msValidity
,
callback
,
context
)
Preloads the data logger cache with a specified validity duration (asynchronous version).
Disables the propagation of every new advertised value to the parent hub.
Continues the enumeration of data loggers started using yFirstDataLogger() .
callback
)
Registers the callback function that is invoked on every change of advertised value.
newval
)
Changes the default activation state of the data logger on power up.
newval
)
280 www.yoctopuce.com
21. High-level API Reference
Changes the type of synchronisation of the data logger.
newval
)
Changes the logical name of the data logger.
newval
)
Changes the activation state of the data logger to start/stop recording data.
newval
)
Changes the current UTC time reference used for recorded data.
data
)
Stores a user context provided as argument in the userData attribute of the function.
Re-enables the propagation of every new advertised value to the parent hub.
callback
,
context
)
Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function.
www.yoctopuce.com
281
21. High-level API Reference
YDataLogger.FindDataLogger() yFindDataLogger()
Retrieves a data logger for a given identifier.
js cpp m pas vb cs java uwp py php es function yFindDataLogger(
func
)
YDataLogger* yFindDataLogger( string
func
)
+(YDataLogger*) FindDataLogger : (NSString*)
func
function yFindDataLogger(
func
: string): TYDataLogger function yFindDataLogger( ByVal
func
As String) As YDataLogger
YDataLogger FindDataLogger( string
func
)
YDataLogger FindDataLogger( String
func
)
YDataLogger FindDataLogger( string
func
) def FindDataLogger(
func
) function yFindDataLogger(
$func
) function FindDataLogger(
func
)
The identifier can be specified using several formats:
YDataLogger
●
FunctionLogicalName
●
ModuleSerialNumber.FunctionIdentifier
●
ModuleSerialNumber.FunctionLogicalName
●
ModuleLogicalName.FunctionIdentifier
●
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
YDataLogger.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. If a call to this object's is_online() method returns FALSE although you are certain that the matching device is plugged, make sure that you did call registerHub() at application initialization time.
Parameters : func
a string that uniquely characterizes the data logger
Returns :
a
YDataLogger
object allowing you to drive the data logger.
282 www.yoctopuce.com
YDataLogger.FindDataLoggerInContext() yFindDataLoggerInContext()
Retrieves a data logger for a given identifier in a YAPI context.
java uwp es
YDataLogger FindDataLoggerInContext( YAPIContext
yctx
,
String
func
)
YDataLogger FindDataLoggerInContext( YAPIContext
yctx
, string
func
) function FindDataLoggerInContext(
yctx
,
func
)
The identifier can be specified using several formats:
21. High-level API Reference
YDataLogger
●
●
●
●
●
FunctionLogicalName
ModuleSerialNumber.FunctionIdentifier
ModuleSerialNumber.FunctionLogicalName
ModuleLogicalName.FunctionIdentifier
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
YDataLogger.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 : yctx
a YAPI context
func
a string that uniquely characterizes the data logger
Returns :
a YDataLogger object allowing you to drive the data logger.
www.yoctopuce.com
283
21. High-level API Reference
YDataLogger.FirstDataLogger() yFirstDataLogger()
YDataLogger
Starts the enumeration of data loggers currently accessible.
js cpp m pas vb cs java uwp py php es function yFirstDataLogger( )
YDataLogger* yFirstDataLogger( )
+(YDataLogger*) FirstDataLogger function yFirstDataLogger( ): TYDataLogger function yFirstDataLogger( ) As YDataLogger
YDataLogger FirstDataLogger( )
YDataLogger FirstDataLogger( )
YDataLogger FirstDataLogger( ) def FirstDataLogger( ) function yFirstDataLogger( ) function FirstDataLogger( )
Use the method
YDataLogger.nextDataLogger()
to iterate 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.
284 www.yoctopuce.com
21. High-level API Reference
YDataLogger.FirstDataLoggerInContext() yFirstDataLoggerInContext()
YDataLogger
Starts the enumeration of data loggers currently accessible.
java uwp es
YDataLogger FirstDataLoggerInContext( YAPIContext
yctx
)
YDataLogger FirstDataLoggerInContext( YAPIContext
yctx
) function FirstDataLoggerInContext(
yctx
)
Use the method
YDataLogger.nextDataLogger()
to iterate on next data loggers.
Parameters : yctx
a YAPI context.
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
285
21. High-level API Reference
datalogger
→
clearCache() YDataLogger
Invalidates the cache.
js cpp m pas vb cs java py php es function clearCache( ) void clearCache( )
-(void) clearCache procedure clearCache( ) procedure clearCache( ) void clearCache( ) void clearCache( ) def clearCache( ) function clearCache( ) function clearCache( )
Invalidates the cache of the data logger attributes. Forces the next call to get_xxx() or loadxxx() to use values that come from the device.
286 www.yoctopuce.com
21. High-level API Reference
datalogger
→
describe() YDataLogger
Returns a short text that describes unambiguously the instance of the data logger in the form
TYPE(NAME)=SERIAL.FUNCTIONID
.
js cpp m pas vb cs java py php es function describe( ) string describe( )
-(NSString*) describe function describe( ): string function describe( ) As String string describe( )
String describe( ) def describe( ) function describe( ) function 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.relay1)=RELAYLO1-123456.relay1
if the module is already connected or
Relay(BadCustomeName.relay1)=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.relay1)=RELAYLO1-
123456.relay1
)
www.yoctopuce.com
287
21. High-level API Reference
datalogger
→
forgetAllDataStreams()
Clears the data logger memory and discards all recorded data streams.
js cpp m pas vb cs java uwp py php es cmd function forgetAllDataStreams( ) int forgetAllDataStreams( )
-(int) forgetAllDataStreams function forgetAllDataStreams( ): LongInt function forgetAllDataStreams( ) As Integer int forgetAllDataStreams( ) int forgetAllDataStreams( ) async Task<int> forgetAllDataStreams( ) def forgetAllDataStreams( ) function forgetAllDataStreams( ) function 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
288 www.yoctopuce.com
datalogger
→
get_advertisedValue() datalogger
→
advertisedValue()
Returns the current value of the data logger (no more than 6 characters).
js cpp m pas vb cs java uwp py php es cmd function get_advertisedValue( ) string get_advertisedValue( )
-(NSString*) advertisedValue function get_advertisedValue( ): string function get_advertisedValue( ) As String string get_advertisedValue( )
String get_advertisedValue( ) async Task<string> get_advertisedValue( ) def get_advertisedValue( ) function get_advertisedValue( ) function get_advertisedValue( )
YDataLogger
target
get_advertisedValue
21. High-level API Reference
YDataLogger
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
.
www.yoctopuce.com
289
21. High-level API Reference
datalogger
→
get_autoStart() datalogger
→
autoStart()
Returns the default activation state of the data logger on power up.
js cpp m pas vb cs java uwp py php es cmd 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( ) async Task<int> get_autoStart( ) def get_autoStart( ) function get_autoStart( ) function get_autoStart( )
YDataLogger
target
get_autoStart
YDataLogger
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 .
290 www.yoctopuce.com
datalogger
→
get_beaconDriven() datalogger
→
beaconDriven()
Returns true if the data logger is synchronised with the localization beacon.
js cpp m pas vb cs java uwp py php es cmd function get_beaconDriven( )
Y_BEACONDRIVEN_enum get_beaconDriven( )
-(Y_BEACONDRIVEN_enum) beaconDriven function get_beaconDriven( ): Integer function get_beaconDriven( ) As Integer int get_beaconDriven( ) int get_beaconDriven( ) async Task<int> get_beaconDriven( ) def get_beaconDriven( ) function get_beaconDriven( ) function get_beaconDriven( )
YDataLogger
target
get_beaconDriven
21. High-level API Reference
YDataLogger
Returns :
either
Y_BEACONDRIVEN_OFF
or
Y_BEACONDRIVEN_ON
, according to true if the data logger is synchronised with the localization beacon
On failure, throws an exception or returns Y_BEACONDRIVEN_INVALID .
www.yoctopuce.com
291
21. High-level API Reference
datalogger
→
get_currentRunIndex() datalogger
→
currentRunIndex()
YDataLogger
Returns the current run number, corresponding to the number of times the module was powered on with the dataLogger enabled at some point.
js cpp m pas vb cs java uwp py php es cmd function get_currentRunIndex( ) int get_currentRunIndex( )
-(int) currentRunIndex function get_currentRunIndex( ): LongInt function get_currentRunIndex( ) As Integer int get_currentRunIndex( ) int get_currentRunIndex( ) async Task<int> get_currentRunIndex( ) def get_currentRunIndex( ) function get_currentRunIndex( ) function get_currentRunIndex( )
YDataLogger
target
get_currentRunIndex
Returns :
an integer corresponding to the current run number, corresponding to the number of times the module was powered on with the dataLogger enabled at some point
On failure, throws an exception or returns
Y_CURRENTRUNINDEX_INVALID
.
292 www.yoctopuce.com
21. High-level API Reference
datalogger
→
get_dataSets() datalogger
→
dataSets()
YDataLogger
Returns a list of YDataSet objects that can be used to retrieve all measures stored by the data logger.
js cpp m pas vb cs java uwp py php es cmd function get_dataSets( ) vector<YDataSet> get_dataSets( )
-(NSMutableArray*) dataSets function get_dataSets( ): TYDataSetArray function get_dataSets( ) As List
List<YDataSet> get_dataSets( )
ArrayList<YDataSet> get_dataSets( ) async Task<List<YDataSet>> get_dataSets( ) def get_dataSets( ) function get_dataSets( ) function 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
293
21. High-level API Reference
datalogger
→
get_dataStreams() datalogger
→
dataStreams()
YDataLogger
Builds a list of all data streams hold by the data logger (legacy method).
js cpp m pas vb cs java py php es function get_dataStreams(
v
) int get_dataStreams( )
-(int) dataStreams : (NSArray**)
v
function get_dataStreams(
v
: Tlist): integer procedure get_dataStreams( ByVal
v
As List) int get_dataStreams( List<YDataStream>
v
) int get_dataStreams( ArrayList<YDataStream>
v
) def get_dataStreams(
v
) function get_dataStreams(
&$v
) function 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.
294 www.yoctopuce.com
21. High-level API Reference
datalogger
→
get_errorMessage() datalogger
→
errorMessage()
YDataLogger
Returns the error message of the latest error with the data logger.
js cpp m pas vb cs java py php es 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( ) function get_errorMessage( ) function 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
295
21. High-level API Reference
datalogger
→
get_errorType() datalogger
→
errorType()
YDataLogger
Returns the numerical error code of the latest error with the data logger.
js cpp pas vb cs java py php es function get_errorType( )
YRETCODE get_errorType( ) function get_errorType( ): YRETCODE function get_errorType( ) As YRETCODE
YRETCODE get_errorType( ) int get_errorType( ) def get_errorType( ) function get_errorType( ) function 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 occurred while using the data logger object
296 www.yoctopuce.com
21. High-level API Reference
datalogger
→
get_friendlyName() datalogger
→
friendlyName()
YDataLogger
Returns a global identifier of the data logger in the format
MODULE_NAME.FUNCTION_NAME
.
js cpp m cs java py php es function get_friendlyName( ) string get_friendlyName( )
-(NSString*) friendlyName string get_friendlyName( )
String get_friendlyName( ) def get_friendlyName( ) function get_friendlyName( ) function 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 example:
MyCustomName.relay1
)
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.yoctopuce.com
297
21. High-level API Reference
datalogger
→
get_functionDescriptor() datalogger
→
functionDescriptor()
YDataLogger
Returns a unique identifier of type
YFUN_DESCR
corresponding to the function.
js cpp m pas vb cs java py php es 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( ) function get_functionDescriptor( ) function 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 .
I f t h e f u n c t i o n h a s n e v e r b e e n c o n t a c t e d , t h e r e t u r n e d v a l u e i s
Y _ F U N C T I O N D E S C R I P T O R _ I N V A L I D .
298 www.yoctopuce.com
21. High-level API Reference
datalogger
→
get_functionId() datalogger
→
functionId()
Returns the hardware identifier of the data logger, without reference to the module.
js cpp m vb cs java py php es function get_functionId( ) string get_functionId( )
-(NSString*) functionId function get_functionId( ) As String string get_functionId( )
String get_functionId( ) def get_functionId( ) function get_functionId( ) function get_functionId( )
YDataLogger
For example relay1
Returns :
a string that identifies the data logger (ex: relay1 )
On failure, throws an exception or returns Y_FUNCTIONID_INVALID .
www.yoctopuce.com
299
21. High-level API Reference
datalogger
→
get_hardwareId() datalogger
→
hardwareId()
YDataLogger
Returns the unique hardware identifier of the data logger in the form
SERIAL.FUNCTIONID
.
js cpp m vb cs java py php es function get_hardwareId( ) string get_hardwareId( )
-(NSString*) hardwareId function get_hardwareId( ) As String string get_hardwareId( )
String get_hardwareId( ) def get_hardwareId( ) function get_hardwareId( ) function get_hardwareId( )
The unique hardware identifier is composed of the device serial number and of the hardware identifier of the data logger (for example
RELAYLO1-123456.relay1
).
Returns :
a string that uniquely identifies the data logger (ex:
RELAYLO1-123456.relay1
)
On failure, throws an exception or returns
Y_HARDWAREID_INVALID
.
300 www.yoctopuce.com
datalogger
→
get_logicalName() datalogger
→
logicalName()
Returns the logical name of the data logger.
js cpp m pas vb cs java uwp py php es cmd function get_logicalName( ) string get_logicalName( )
-(NSString*) logicalName function get_logicalName( ): string function get_logicalName( ) As String string get_logicalName( )
String get_logicalName( ) async Task<string> get_logicalName( ) def get_logicalName( ) function get_logicalName( ) function get_logicalName( )
YDataLogger
target
get_logicalName
Returns :
a string corresponding to the logical name of the data logger.
On failure, throws an exception or returns
Y_LOGICALNAME_INVALID
.
21. High-level API Reference
YDataLogger
www.yoctopuce.com
301
21. High-level API Reference
datalogger
→
get_module() datalogger
→
module()
YDataLogger
Gets the
YModule
object for the device on which the function is located.
js cpp m pas vb cs java py php es 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( ) function get_module( ) function get_module( )
If the function cannot be located on any module, the returned instance of
YModule
is not shown as online.
Returns :
an instance of YModule
302 www.yoctopuce.com
21. High-level API Reference
datalogger
→
get_module_async() datalogger
→
module_async()
YDataLogger
Gets the
YModule
object for the device on which the function is located (asynchronous version).
js function get_module_async(
callback
,
context
)
If the function cannot be located on any module, the returned
YModule
object does not show as online.
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 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
303
21. High-level API Reference
datalogger
→
get_recording() datalogger
→
recording()
Returns the current activation state of the data logger.
js cpp m pas vb cs java uwp py php es cmd function get_recording( )
Y_RECORDING_enum get_recording( )
-(Y_RECORDING_enum) recording function get_recording( ): Integer function get_recording( ) As Integer int get_recording( ) int get_recording( ) async Task<int> get_recording( ) def get_recording( ) function get_recording( ) function get_recording( )
YDataLogger
target
get_recording
YDataLogger
Returns :
a value among
Y_RECORDING_OFF
,
Y_RECORDING_ON
and
Y_RECORDING_PENDING corresponding to the current activation state of the data logger
On failure, throws an exception or returns Y_RECORDING_INVALID .
304 www.yoctopuce.com
datalogger
→
get_timeUTC() datalogger
→
timeUTC()
Returns the Unix timestamp for current UTC time, if known.
js cpp m pas vb cs java uwp py php es cmd function get_timeUTC( ) s64 get_timeUTC( )
-(s64) timeUTC function get_timeUTC( ): int64 function get_timeUTC( ) As Long long get_timeUTC( ) long get_timeUTC( ) async Task<long> get_timeUTC( ) def get_timeUTC( ) function get_timeUTC( ) function get_timeUTC( )
YDataLogger
target
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
.
21. High-level API Reference
YDataLogger
www.yoctopuce.com
305
21. High-level API Reference
datalogger
→
get_userData() datalogger
→
userData()
YDataLogger
Returns the value of the userData attribute, as previously stored using method set_userData
.
js cpp m pas vb cs java py php es function get_userData( ) void * get_userData( )
-(id) userData function get_userData( ): Tobject function get_userData( ) As Object object get_userData( )
Object get_userData( ) def get_userData( ) function get_userData( ) function 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.
306 www.yoctopuce.com
21. High-level API Reference
datalogger
→
isOnline() YDataLogger
Checks if the data logger is currently reachable, without raising any error.
js cpp m pas vb cs java py php es function isOnline( ) bool isOnline( )
-(BOOL) isOnline function isOnline( ): boolean function isOnline( ) As Boolean bool isOnline( ) boolean isOnline( ) def isOnline( ) function isOnline( ) function 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 data logger.
Returns :
true
if the data logger can be reached, and false
otherwise
www.yoctopuce.com
307
21. High-level API Reference
datalogger
→
isOnline_async() YDataLogger
Checks if the data logger is currently reachable, without raising any error (asynchronous version).
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.
308 www.yoctopuce.com
21. High-level API Reference
datalogger
→
load() YDataLogger
Preloads the data logger cache with a specified validity duration.
js cpp m pas vb cs java py php es 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( ulong
msValidity
) int load( long
msValidity
) def load(
msValidity
) function load(
$msValidity
) function 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 traffic 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
309
21. High-level API Reference
datalogger
→
loadAttribute() YDataLogger
Returns the current value of a single function attribute, as a text string, as quickly as possible but without using the cached value.
js cpp m pas vb cs java uwp py php es function loadAttribute(
attrName
) string loadAttribute( string
attrName
)
-(NSString*) loadAttribute : (NSString*)
attrName
function loadAttribute(
attrName
: string): string function loadAttribute( ) As String string loadAttribute( string
attrName
)
String loadAttribute( String
attrName
) async Task<string> loadAttribute( string
attrName
) def loadAttribute(
attrName
) function loadAttribute(
$attrName
) function loadAttribute(
attrName
)
Parameters : attrName
the name of the requested attribute
Returns :
a string with the value of the the attribute
On failure, throws an exception or returns an empty string.
310 www.yoctopuce.com
21. High-level API Reference
datalogger
→
load_async() YDataLogger
Preloads the data logger cache with a specified validity duration (asynchronous version).
js 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 function receives three arguments: the caller-specific context object, the receiving function object and the error code
(or YAPI_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
311
21. High-level API Reference
datalogger
→
muteValueCallbacks() YDataLogger
Disables the propagation of every new advertised value to the parent hub.
js cpp m pas vb cs java uwp py php es cmd function muteValueCallbacks( ) int muteValueCallbacks( )
-(int) muteValueCallbacks function muteValueCallbacks( ): LongInt function muteValueCallbacks( ) As Integer int muteValueCallbacks( ) int muteValueCallbacks( ) async Task<int> muteValueCallbacks( ) def muteValueCallbacks( ) function muteValueCallbacks( ) function muteValueCallbacks( )
YDataLogger
target
muteValueCallbacks
You can use this function to save bandwidth and CPU on computers with limited resources, or to prevent unwanted invocations of the HTTP callback. Remember to call the saveToFlash()
method of the module if the modification must be kept.
Returns :
YAPI_SUCCESS when the call succeeds.
On failure, throws an exception or returns a negative error code.
312 www.yoctopuce.com
21. High-level API Reference
datalogger
→
nextDataLogger()
Continues the enumeration of data loggers started using yFirstDataLogger()
.
js cpp m pas vb cs java uwp py php es function nextDataLogger( )
YDataLogger * nextDataLogger( )
-(YDataLogger*) nextDataLogger function nextDataLogger( ): TYDataLogger function nextDataLogger( ) As YDataLogger
YDataLogger nextDataLogger( )
YDataLogger nextDataLogger( )
YDataLogger nextDataLogger( ) def nextDataLogger( ) function nextDataLogger( ) function nextDataLogger( )
YDataLogger
Returns :
a pointer to a YDataLogger object, corresponding to a data logger currently online, or a null pointer if there are no more data loggers to enumerate.
www.yoctopuce.com
313
21. High-level API Reference
datalogger
→
registerValueCallback()
Registers the callback function that is invoked on every change of advertised value.
js cpp m pas vb cs java uwp py php es function registerValueCallback(
callback
) int registerValueCallback( YDataLoggerValueCallback
callback
)
-(int) registerValueCallback : (YDataLoggerValueCallback)
callback
function registerValueCallback(
callback
: TYDataLoggerValueCallback): LongInt function registerValueCallback( ) As Integer int registerValueCallback( ValueCallback
callback
) int registerValueCallback( UpdateCallback
callback
) async Task<int> registerValueCallback( ValueCallback
callback
) def registerValueCallback(
callback
) function registerValueCallback(
$callback
) function registerValueCallback(
callback
)
YDataLogger
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.
314 www.yoctopuce.com
21. High-level API Reference
datalogger
→
set_autoStart() datalogger
→
setAutoStart()
Changes the default activation state of the data logger on power up.
js cpp m pas vb cs java uwp py php es cmd 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
newval
) int set_autoStart( int
newval
) async Task<int> set_autoStart( int
newval
) def set_autoStart(
newval
) function set_autoStart(
$newval
) function set_autoStart(
newval
)
YDataLogger
target
set_autoStart
newval
YDataLogger
Remember to call the saveToFlash()
method of the module if the modification must be kept.
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
315
21. High-level API Reference
datalogger
→
set_beaconDriven() datalogger
→
setBeaconDriven()
Changes the type of synchronisation of the data logger.
js cpp m pas vb cs java uwp py php es cmd function set_beaconDriven(
newval
) int set_beaconDriven( Y_BEACONDRIVEN_enum
newval
)
-(int) setBeaconDriven : (Y_BEACONDRIVEN_enum)
newval
function set_beaconDriven(
newval
: Integer): integer function set_beaconDriven( ByVal
newval
As Integer) As Integer int set_beaconDriven( int
newval
) int set_beaconDriven( int
newval
) async Task<int> set_beaconDriven( int
newval
) def set_beaconDriven(
newval
) function set_beaconDriven(
$newval
) function set_beaconDriven(
newval
)
YDataLogger
target
set_beaconDriven
newval
YDataLogger
Remember to call the saveToFlash()
method of the module if the modification must be kept.
Parameters : newval
either
Y_BEACONDRIVEN_OFF
or
Y_BEACONDRIVEN_ON
, according to the type of synchronisation of the data logger
Returns :
YAPI_SUCCESS if the call succeeds.
On failure, throws an exception or returns a negative error code.
316 www.yoctopuce.com
21. High-level API Reference
datalogger
→
set_logicalName() datalogger
→
setLogicalName()
Changes the logical name of the data logger.
js cpp m pas vb cs java uwp py php es cmd function set_logicalName(
newval
) int set_logicalName( const string&
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
) async Task<int> set_logicalName( string
newval
) def set_logicalName(
newval
) function set_logicalName(
$newval
) function set_logicalName(
newval
)
YDataLogger
target
set_logicalName
newval
YDataLogger
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 returns a negative error code.
www.yoctopuce.com
317
21. High-level API Reference
datalogger
→
set_recording() datalogger
→
setRecording()
Changes the activation state of the data logger to start/stop recording data.
js cpp m pas vb cs java uwp py php es cmd 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
) async Task<int> set_recording( int
newval
) def set_recording(
newval
) function set_recording(
$newval
) function set_recording(
newval
)
YDataLogger
target
set_recording
newval
YDataLogger
Parameters : newval
a v a l u e a m o n g Y _ R E C O R D I N G _ O F F , Y _ R E C O R D I N G _ O N a n d
Y_RECORDING_PENDING
corresponding to the activation state of the 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.
318 www.yoctopuce.com
21. High-level API Reference
datalogger
→
set_timeUTC() datalogger
→
setTimeUTC()
Changes the current UTC time reference used for recorded data.
js cpp m pas vb cs java uwp py php es cmd function set_timeUTC(
newval
) int set_timeUTC( s64
newval
)
-(int) setTimeUTC : (s64)
newval
function set_timeUTC(
newval
: int64): integer function set_timeUTC( ByVal
newval
As Long) As Integer int set_timeUTC( long
newval
) int set_timeUTC( long
newval
) async Task<int> set_timeUTC( long
newval
) def set_timeUTC(
newval
) function set_timeUTC(
$newval
) function set_timeUTC(
newval
)
YDataLogger
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.
YDataLogger
www.yoctopuce.com
319
21. High-level API Reference
datalogger
→
set_userData() datalogger
→
setUserData()
YDataLogger
Stores a user context provided as argument in the userData attribute of the function.
js cpp m pas vb cs java py php es function set_userData(
data
) void set_userData( void*
data
)
-(void) setUserData : (id)
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
) function set_userData(
$data
) function 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
320 www.yoctopuce.com
datalogger
→
unmuteValueCallbacks()
Re-enables the propagation of every new advertised value to the parent hub.
js cpp m pas vb cs java uwp py php es cmd function unmuteValueCallbacks( ) int unmuteValueCallbacks( )
-(int) unmuteValueCallbacks function unmuteValueCallbacks( ): LongInt function unmuteValueCallbacks( ) As Integer int unmuteValueCallbacks( ) int unmuteValueCallbacks( ) async Task<int> unmuteValueCallbacks( ) def unmuteValueCallbacks( ) function unmuteValueCallbacks( ) function unmuteValueCallbacks( )
YDataLogger
target
unmuteValueCallbacks
21. High-level API Reference
YDataLogger
This function reverts the effect of a previous call to muteValueCallbacks()
. Remember to call the saveToFlash()
method of the module if the modification must be kept.
Returns :
YAPI_SUCCESS
when the call succeeds.
On failure, throws an exception or returns a negative error code.
www.yoctopuce.com
321
21. High-level API Reference
datalogger
→
wait_async() YDataLogger
Waits for all pending asynchronous commands on the module to complete, and invoke the userprovided callback function.
js es 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.
322 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 and a specified time interval. They can be used to load data points with a progress report. When the
YDataSet object is instantiated 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: cs java uwp py php es js cpp m pas vb
<script type='text/javascript' src='yocto_api.js'></script>
#include "yocto_api.h"
#import "yocto_api.h" uses yocto_api; yocto_api.vb
yocto_api.cs
import com.yoctopuce.YoctoAPI.YModule; import com.yoctopuce.YoctoAPI.YModule; from yocto_api import * require_once('yocto_api.php'); in HTML: <script src="../../lib/yocto_api.js"></script> in node.js: require('yoctolib-es2017/yocto_api.js');
YDataSet
methods
Returns the end time of the dataset, relative to the Jan 1, 1970.
Returns the hardware identifier of the function that performed the measure, without reference to the module.
Returns the unique hardware identifier of the function who performed the measures, in the form
SERIAL.FUNCTIONID
.
Returns all measured values currently available for this DataSet, as a list of YMeasure objects.
measure
)
Returns the detailed set of measures for the time interval corresponding to a given condensed measures previously returned by get_preview()
.
Returns a condensed version of the measures that can retrieved in this YDataSet, as a list of YMeasure objects.
Returns the progress of the downloads of the measures from the data logger, on a scale from 0 to 100.
Returns the start time of the dataset, relative to the Jan 1, 1970.
www.yoctopuce.com
323
21. High-level API Reference
Returns an YMeasure object which summarizes the whole DataSet.
Returns the measuring unit for the measured value.
Loads the the next block of measures from the dataLogger, and updates the progress indicator.
callback
,
context
)
Loads the the next block of measures from the dataLogger asynchronously.
324 www.yoctopuce.com
21. High-level API Reference
dataset
→
get_endTimeUTC() dataset
→
endTimeUTC()
Returns the end time of the dataset, relative to the Jan 1, 1970.
js cpp m pas vb cs java uwp py php es function get_endTimeUTC( ) s64 get_endTimeUTC( )
-(s64) endTimeUTC function get_endTimeUTC( ): int64 function get_endTimeUTC( ) As Long long get_endTimeUTC( ) long get_endTimeUTC( ) async Task<long> get_endTimeUTC( ) def get_endTimeUTC( ) function get_endTimeUTC( ) function get_endTimeUTC( )
YDataSet
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
325
21. High-level API Reference
dataset
→
get_functionId() dataset
→
functionId()
YDataSet
Returns the hardware identifier of the function that performed the measure, without reference to the module.
js cpp m pas vb cs java uwp py php es function get_functionId( ) string get_functionId( )
-(NSString*) functionId function get_functionId( ): string function get_functionId( ) As String string get_functionId( )
String get_functionId( ) async Task<string> get_functionId( ) def get_functionId( ) function get_functionId( ) function get_functionId( )
For example temperature1
.
Returns :
a string that identifies the function (ex: temperature1 )
326 www.yoctopuce.com
21. High-level API Reference
dataset
→
get_hardwareId() dataset
→
hardwareId()
YDataSet
Returns the unique hardware identifier of the function who performed the measures, in the form
SERIAL.FUNCTIONID
.
js cpp m pas vb cs java uwp py php es function get_hardwareId( ) string get_hardwareId( )
-(NSString*) hardwareId function get_hardwareId( ): string function get_hardwareId( ) As String string get_hardwareId( )
String get_hardwareId( ) async Task<string> get_hardwareId( ) def get_hardwareId( ) function get_hardwareId( ) function get_hardwareId( )
The unique hardware identifier is composed of the device serial number and of the hardware identifier of the function (for example
THRMCPL1-123456.temperature1
)
Returns :
a string that uniquely identifies the function (ex:
THRMCPL1-123456.temperature1
)
On failure, throws an exception or returns
Y_HARDWAREID_INVALID
.
www.yoctopuce.com
327
21. High-level API Reference
dataset
→
get_measures() dataset
→
measures()
YDataSet
Returns all measured values currently available for this DataSet, as a list of YMeasure objects.
js cpp m pas vb cs java uwp py php es function get_measures( ) vector<YMeasure> get_measures( )
-(NSMutableArray*) measures function get_measures( ): TYMeasureArray function get_measures( ) As List
List<YMeasure> get_measures( )
ArrayList<YMeasure> get_measures( ) async Task<List<YMeasure>> get_measures( ) def get_measures( ) function get_measures( ) function 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.
328 www.yoctopuce.com
21. High-level API Reference
dataset
→
get_measuresAt() dataset
→
measuresAt()
YDataSet
Returns the detailed set of measures for the time interval corresponding to a given condensed measures previously returned by get_preview()
.
js cpp m pas vb cs java uwp py php es function get_measuresAt(
measure
) vector<YMeasure> get_measuresAt( YMeasure
measure
)
-(NSMutableArray*) measuresAt : (YMeasure*)
measure
function get_measuresAt(
measure
: TYMeasure): TYMeasureArray function get_measuresAt( ) As List
List<YMeasure> get_measuresAt( YMeasure
measure
)
ArrayList<YMeasure> get_measuresAt( YMeasure
measure
) async Task<List<YMeasure>> get_measuresAt( YMeasure
measure
) def get_measuresAt(
measure
) function get_measuresAt(
$measure
) function get_measuresAt(
measure
)
The result is provided as a list of YMeasure objects.
Parameters : measure
condensed measure from the list previously returned by get_preview() .
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
329
21. High-level API Reference
dataset
→
get_preview() dataset
→
preview()
YDataSet
Returns a condensed version of the measures that can retrieved in this YDataSet, as a list of
YMeasure objects.
js cpp m pas vb cs java uwp py php es function get_preview( ) vector<YMeasure> get_preview( )
-(NSMutableArray*) preview function get_preview( ): TYMeasureArray function get_preview( ) As List
List<YMeasure> get_preview( )
ArrayList<YMeasure> get_preview( ) async Task<List<YMeasure>> get_preview( ) def get_preview( ) function get_preview( ) function 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.
330 www.yoctopuce.com
21. High-level API Reference
dataset
→
get_progress() dataset
→
progress()
YDataSet
Returns the progress of the downloads of the measures from the data logger, on a scale from 0 to
100.
js cpp m pas vb cs java uwp py php es function get_progress( ) int get_progress( )
-(int) progress function get_progress( ): LongInt function get_progress( ) As Integer int get_progress( ) int get_progress( ) async Task<int> get_progress( ) def get_progress( ) function get_progress( ) function get_progress( )
When the object is instantiated 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).
www.yoctopuce.com
331
21. High-level API Reference
dataset
→
get_startTimeUTC() dataset
→
startTimeUTC()
YDataSet
Returns the start time of the dataset, relative to the Jan 1, 1970.
js cpp m pas vb cs java uwp py php es function get_startTimeUTC( ) s64 get_startTimeUTC( )
-(s64) startTimeUTC function get_startTimeUTC( ): int64 function get_startTimeUTC( ) As Long long get_startTimeUTC( ) long get_startTimeUTC( ) async Task<long> get_startTimeUTC( ) def get_startTimeUTC( ) function get_startTimeUTC( ) function 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).
332 www.yoctopuce.com
21. High-level API Reference
dataset
→
get_summary() dataset
→
summary()
YDataSet
Returns an YMeasure object which summarizes the whole DataSet.
js cpp m pas vb cs java uwp py php es function get_summary( )
YMeasure get_summary( )
-(YMeasure*) summary function get_summary( ): TYMeasure function get_summary( ) As YMeasure
YMeasure get_summary( )
YMeasure get_summary( ) async Task<YMeasure> get_summary( ) def get_summary( ) function get_summary( ) function 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 time 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
www.yoctopuce.com
333
21. High-level API Reference
dataset
→
get_unit() dataset
→
unit()
Returns the measuring unit for the measured value.
js cpp m pas vb cs java uwp py php es function get_unit( ) string get_unit( )
-(NSString*) unit function get_unit( ): string function get_unit( ) As String string get_unit( )
String get_unit( ) async Task<string> get_unit( ) def get_unit( ) function get_unit( ) function get_unit( )
Returns :
a string that represents a physical unit.
On failure, throws an exception or returns Y_UNIT_INVALID .
YDataSet
334 www.yoctopuce.com
21. High-level API Reference
dataset
→
loadMore() YDataSet
Loads the the next block of measures from the dataLogger, and updates the progress indicator.
js cpp m pas vb cs java uwp py php es function loadMore( ) int loadMore( )
-(int) loadMore function loadMore( ): LongInt function loadMore( ) As Integer int loadMore( ) int loadMore( ) async Task<int> loadMore( ) def loadMore( ) function loadMore( ) function 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.
www.yoctopuce.com
335
21. High-level API Reference
dataset
→
loadMore_async()
Loads the the next block of measures from the dataLogger asynchronously.
js function loadMore_async(
callback
,
context
)
YDataSet
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.
336 www.yoctopuce.com
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: js cpp m pas vb cs java uwp py php es
<script type='text/javascript' src='yocto_api.js'></script>
#include "yocto_api.h"
#import "yocto_api.h" uses yocto_api; yocto_api.vb
yocto_api.cs
import com.yoctopuce.YoctoAPI.YModule; import com.yoctopuce.YoctoAPI.YModule; from yocto_api import * require_once('yocto_api.php'); in HTML: <script src="../../lib/yocto_api.js"></script> in node.js: require('yoctolib-es2017/yocto_api.js');
YMeasure
methods
Returns the average value observed during the time interval covered by this measure.
Returns the end time of the measure, relative to the Jan 1, 1970 UTC (Unix timestamp).
Returns the largest value observed during the time interval covered by this measure.
Returns the smallest value observed during the time interval covered by this measure.
Returns the start time of the measure, relative to the Jan 1, 1970 UTC (Unix timestamp).
www.yoctopuce.com
337
21. High-level API Reference
measure
→
get_averageValue() measure
→
averageValue()
Returns the average value observed during the time interval covered by this measure.
js cpp m pas vb cs java uwp py php es function get_averageValue( ) double get_averageValue( )
-(double) averageValue function get_averageValue( ): double function get_averageValue( ) As Double double get_averageValue( ) double get_averageValue( ) double get_averageValue( ) def get_averageValue( ) function get_averageValue( ) function get_averageValue( )
YMeasure
Returns :
a floating-point number corresponding to the average value observed.
338 www.yoctopuce.com
21. High-level API Reference
measure
→
get_endTimeUTC() measure
→
endTimeUTC()
YMeasure
Returns the end time of the measure, relative to the Jan 1, 1970 UTC (Unix timestamp).
js cpp m pas vb cs java uwp py php es function get_endTimeUTC( ) double get_endTimeUTC( )
-(double) endTimeUTC function get_endTimeUTC( ): double function get_endTimeUTC( ) As Double double get_endTimeUTC( ) double get_endTimeUTC( ) double get_endTimeUTC( ) def get_endTimeUTC( ) function get_endTimeUTC( ) function get_endTimeUTC( )
When the recording rate is higher than 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.
www.yoctopuce.com
339
21. High-level API Reference
measure
→
get_maxValue() measure
→
maxValue()
Returns the largest value observed during the time interval covered by this measure.
js cpp m pas vb cs java uwp py php es function get_maxValue( ) double get_maxValue( )
-(double) maxValue function get_maxValue( ): double function get_maxValue( ) As Double double get_maxValue( ) double get_maxValue( ) double get_maxValue( ) def get_maxValue( ) function get_maxValue( ) function get_maxValue( )
YMeasure
Returns :
a floating-point number corresponding to the largest value observed.
340 www.yoctopuce.com
21. High-level API Reference
measure
→
get_minValue() measure
→
minValue()
Returns the smallest value observed during the time interval covered by this measure.
js cpp m pas vb cs java uwp py php es function get_minValue( ) double get_minValue( )
-(double) minValue function get_minValue( ): double function get_minValue( ) As Double double get_minValue( ) double get_minValue( ) double get_minValue( ) def get_minValue( ) function get_minValue( ) function get_minValue( )
YMeasure
Returns :
a floating-point number corresponding to the smallest value observed.
www.yoctopuce.com
341
21. High-level API Reference
measure
→
get_startTimeUTC() measure
→
startTimeUTC()
YMeasure
Returns the start time of the measure, relative to the Jan 1, 1970 UTC (Unix timestamp).
js cpp m pas vb cs java uwp py php es function get_startTimeUTC( ) double get_startTimeUTC( )
-(double) startTimeUTC function get_startTimeUTC( ): double function get_startTimeUTC( ) As Double double get_startTimeUTC( ) double get_startTimeUTC( ) double get_startTimeUTC( ) def get_startTimeUTC( ) function get_startTimeUTC( ) function 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.
342 www.yoctopuce.com
22. Troubleshooting
22.1. Where to start?
If it is the first time that you use a Yoctopuce module and you do not really know where to start, have a look at the Yoctopuce blog. There is a section dedicated to beginners
1
.
22.2. 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 directory, respecting the alphabetical order (for example, the "
51-custom.rules
" file is interpreted AFTER the "
50udev-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 VirtualHub for Linux
2
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
1 see: http://www.yoctopuce.com/EN/blog_by_categories/for-the-beginners
2 http://www.yoctopuce.com/FR/virtualhub.php
www.yoctopuce.com
343
22. Troubleshooting
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 only need to copy the "
51-yoctopuce_group.rules
" file into the "
/etc/udev/rules.d
" directory and 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.3. 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.
22.4. Powered module but invisible for the OS
If your Yocto-Amp is connected by USB, if its blue led is on, but if the operating system cannot see the module, check that you are using a true USB cable with data wires, and not a charging cable.
Charging cables have only power wires.
22.5. Another process named xxx is already using yAPI
If when initializing the Yoctopuce API, you obtain the "Another process named xxx is already using
yAPI" error message, it means that another application is already using Yoctopuce USB modules. On a single machine only one process can access Yoctopuce modules by USB at a time. You can easily work around this limitation by using a VirtualHub and the network mode
3
.
22.6. Disconnections, erratic behavior
If you Yocto-Amp behaves erratically and/or disconnects itself from the USB bus without apparent reason, check that it is correctly powered. Avoid cables with a length above 2 meters. If needed, insert a powered USB hub
4 5
.
22.7. Damaged device
Yoctopuce strives to reduce the production of electronic waste. If you believe that your Yocto-Amp is not working anymore, start by contacting Yoctopuce support by e-mail to diagnose the failure. Even if you know the device was damaged by mistake, Yoctopuce engineers might be able to repair it, and avoid creating electronic waste.
3 see: http://www.yoctopuce.com/EN/article/error-message-another-process-is-already-using-yapi
4 see: http://www.yoctopuce.com/EN/article/usb-cables-size-matters
5 see: http://www.yoctopuce.com/EN/article/how-many-usb-devices-can-you-connect
344 www.yoctopuce.com
22. Troubleshooting
Waste Electrical and Electronic Equipment (WEEE) If you really want to get rid of your Yocto-Amp, do not throw it away in a trash bin but bring it to a local WEEE recycling point. In this way, it will be disposed properly by a specialized WEEE recycling center.
www.yoctopuce.com
345
346 www.yoctopuce.com
23. Characteristics
You can find below a summary of the main technical characteristics of your Yocto-Amp module.
Hardware release
Width
Length
Weight
USB connector
Max Current (continuous)
Max Current (peak)
Refresh rate
USB bus insulation
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
Rev. B
20 mm
56 mm
8 g micro-B
10 A
17 A
10 Hz (DC)
3 kV
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
347
23. Characteristics
348 www.yoctopuce.com
Index
A
B
C
calibrateFromPoints, YCurrent 231
ClearHTTPCallbackCacheDir, YAPI 134
Current 9, 23, 30, 36, 43, 53, 61, 68, 74, 81, 87,
D
E
Error 42, 51, 58, 65, 72, 78, 86, 91, 97, 109
F
FindCurrentInContext, YCurrent 228
FindDataLogger, YDataLogger 281
FindDataLoggerInContext, YDataLogger 282
FindModuleInContext, YModule 166
FirstCurrentInContext, YCurrent 230
FirstDataLogger, YDataLogger 283
FirstDataLoggerInContext, YDataLogger 284
forgetAllDataStreams, YDataLogger 287
G
get_advertisedValue, YCurrent 234
get_advertisedValue, YDataLogger 288
get_autoStart, YDataLogger 289
get_averageValue, YMeasure 337
get_beaconDriven, YDataLogger 290
get_currentRawValue, YCurrent 235
get_currentRunIndex, YDataLogger 291
get_currentValue, YCurrent 236
get_dataStreams, YDataLogger 293
get_errorMessage, YCurrent 238
get_errorMessage, YDataLogger 294
get_errorType, YDataLogger 295
get_firmwareRelease, YModule 182
get_friendlyName, YCurrent 240
get_friendlyName, YDataLogger 296
get_functionDescriptor, YCurrent 241
get_functionDescriptor, YDataLogger 297
get_functionId, YDataLogger 298
get_hardwareId, YDataLogger 299
get_highestValue, YCurrent 244
get_logFrequency, YCurrent 245
get_logicalName, YDataLogger 300
get_module_async, YCurrent 249
get_module_async, YDataLogger 302
get_persistentSettings, YModule 190
get_productRelease, YModule 193
get_rebootCountdown, YModule 194
get_recordedData, YCurrent 250
get_recording, YDataLogger 303
get_reportFrequency, YCurrent 251
get_startTimeUTC, YDataSet 331
get_startTimeUTC, YMeasure 341
H
I
isOnline_async, YDataLogger 307
J
L
Library 34, 58, 87, 121, 122, 130
loadAttribute, YDataLogger 309
loadCalibrationPoints, YCurrent 261
M
Module 13, 21, 22, 30, 39, 45, 55, 63, 70, 76, 83,
muteValueCallbacks, YCurrent 263
muteValueCallbacks, YDataLogger 311
N
nextDataLogger, YDataLogger 312
O
P
R
RegisterDeviceArrivalCallback, YAPI 144
RegisterDeviceRemovalCallback, YAPI 145
RegisterHubDiscoveryCallback, YAPI 148
registerLogCallback, YModule 210
registerTimedReportCallback, YCurrent 265
registerValueCallback, YCurrent 266
registerValueCallback, YDataLogger 313
S
set_allSettingsAndFiles, YModule 214
set_autoStart, YDataLogger 314
set_beaconDriven, YDataLogger 315
set_highestValue, YCurrent 267
set_logFrequency, YCurrent 268
set_logicalName, YDataLogger 316
set_recording, YDataLogger 317
set_reportFrequency, YCurrent 271
SetHTTPCallbackCacheDir, YAPI 152
T
triggerFirmwareUpdate, YModule 220
U
unmuteValueCallbacks, YCurrent 276
unmuteValueCallbacks, YDataLogger 320
UpdateDeviceList_async, YAPI 160
V
W
Y
yClearHTTPCallbackCacheDir 134
Yocto-Amp 21, 29, 33, 43, 53, 61, 67, 73, 81, 87,
yRegisterDeviceArrivalCallback 144
yRegisterDeviceRemovalCallback 145
Stáhnout
Reklama