The Yocto-VOC is a 60x20mm electronic module which enables you to evaluate by USB the quality of the surrounding air, by evaluating the quantity of Volatile Organic Compounds (VOC) present in the air. The Yocto-VOC can detect the presence of the following compounds: alcohols, aldehydes, aliphatic hydrocarbons, amines, aromatic hydrocarbons, CO, CH4, LPG, ketones, and organic acids. The values returned by the Yocto-VOC are provided in ppm CO2 equivalent. This makes the Yocto-VOC the ideal tool to determine automatically when it is time to ventilate a room.
The Yocto-VOC module
The Yocto-VOC is not in itself a complete product. It is a component intended to be integrated into a solution used in laboratory equipments, or in industrial process-control equipments, or for similar applications in domestic and commercial environments. In order to use it, you must at least install it in a protective enclosure and connect it to a host computer.
Yoctopuce thanks you for buying this Yocto-VOC 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-VOC is easy to install anywhere and easy to drive from a maximum of programming languages. If you are nevertheless disappointed with this module, or if you need additional information, do not hesitate to contact Yoctopuce support:
E-mail address: | support@yoctopuce.com |
Web site: | www.yoctopuce.com |
Postal address: | Chemin des Journaliers, 1 |
ZIP code, city: | 1236 Cartigny |
Country: | Switzerland |
The Yocto-VOC is designed to meet the requirements of IEC 61010-1:2010 safety standard. It does not create any serious hazards to the operator and surrounding area, even in single fault condition, as long as it is integrated and used according to the instructions contained in this documentation, and in this section in particular.
The Yocto-VOC should not be used without a protective enclosure, because of the accessible bare electronic components. For optimal safety, it should be put into a non-metallic, non-inflammable enclosure, resistant to a mechanical stress level of 5 J. For instance, use a polycarbonate (e.g. LEXAN) enclosure rated IK08 with a IEC 60695-11-10 flammability rating of V-1 or better. Using a lower quality enclosure may require specific warnings for the operator and/or compromise conformity with the safety standard.
If a damage is observed on the electronic board or on the enclosure, it should be replaced in order to ensure continued safety of the equipment, and to prevent damaging other parts of the system due to overload that a short circuit could cause.
In order to ease the maintenance and the identification of risks during maintenance, you should affixate the water-resistant identification label provided together with the electronic board as close as possible to the device. If the device is put in a dedicated enclosure, the identification label should be affixated on the outside of the enclosure.
The safety standard applied is intended to cover laboratory equipment, industrial process-control equipment and similar applications in residential or commercial environment. If you intend to use the Yocto-VOC for another kind of application, you should check the safety regulations according to the standard applicable to your application.
In particular, the Yocto-VOC is not certified for use in medical environments or for life-support applications.
The Yocto-VOC is not certified for use in hazardous locations, explosive environments, or life-threatening applications. Environmental ratings are provided below.
Yoctopuce devices have 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 environments with significant solid pollution or conductive pollution requires a protection from such pollution using an IP67 or IP68 enclosure. The products are designed for use up to altitude 2000m.
All Yoctopuce devices are warranted to perform according to their documentation and technical specifications under normal temperature conditions according to IEC61010-1, i.e. 5°C to 40°C. In addition, most devices can also be used on an extended temperature range, where some limitations may apply from case to case.
The extended operating temperature range for the Yocto-VOC is $SPECEXTTEMP$. This temperature range has been determined based on components manufacturer recommendations, and on controlled environment tests performed during a limited duration (1h). If you plan to use the Yocto-VOC in harsh environments for a long period of time, we strongly advise you to run extensive tests before going to production.
1: | Micro-B USB socket | 3: | Yocto-led |
2: | Yocto-button | 4: | Sensor |
All Yocto-modules share a number of common functionalities.
Yoctopuce modules all come with a USB 2.0 micro-B socket. 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.
If you plan to use a power source other then a standard USB host port to power the device through the USB connector, that power source must respect the assigned values of USB 2.0 specifications:
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.
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 support2.
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.
Each Yocto-module has a unique serial number assigned to it at the factory. For Yocto-VOC modules, this number starts with YVOCMK01. The module can be software driven using this serial number. The serial number cannot be modified.
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.
This sensor is a iAQ engine produced by AppliedSensor, it can be used between 0°C and +50°C. Its use does not require any specific precaution.
The Yocto-VOC module requires a relatively long heating time to auto-calibrate itself. The data is usable only after the module has been connected for 15 minutes. While heating, the sensor reports a value of 450 ppm.
The values returned by the Yocto-VOC are not absolute but relative to the rate of VOC present during the heating time. If the measured values go significatively under the values present during the auto-calibration phase, the sensor re-calibrates itself on the new minimal values. You must therefore use the Yocto-VOC as a trend indicator of air quality, and not as a scientific measuring device.
The accessories below are not necessary to use the Yocto-VOC 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.
In order to mount the Yocto-VOC module, you can put small screws in the 2.5mm assembly holes, with a screw head no larger than 4.5mm. The best way is to use threaded spacers, which you can then mount wherever you want. You can find more details on this topic in the chapter about assembly and connections.
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 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.
You can add network connectivity to your Yocto-VOC, 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.
In case you wish to connect your Yocto-VOC 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-VOC 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-VOC.
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.
Your Yocto-VOC has been designed to be installed as is in your project. Nevertheless, Yoctopuce sells enclosures specifically designed for Yoctopuce devices. These enclosures have removable mounting brackets and magnets allowing them to stick on ferromagnetic surfaces. More details are available on the Yoctopuce web site 3. The suggested enclosure model for your Yocto-VOC is the YoctoBox-Long-Thin-Black-Vents.
You can install your Yocto-VOC in an optional enclosure
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.
In order to use your Yocto-VOC module, you should have the following items at hand.
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, macOS X, Linux, and Android. Yoctopuce modules do not require installing any specific system driver, as they leverage the standard HID driver4 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. The programming library is also available for the Universal Windows Platform (UWP), which is supported by all flavors of Windows 10, including Windows 10 IoT. Yoctopuce is frequently testing its modules on Windows 7 and Windows 10.
MacOS versions currently supported are: Mac OS X 10.9 (Maverick), 10.10 (Yosemite), 10.11 (El Capitan), macOS 10.12 (Sierra), macOS 10.13 (High Sierra) and macOS 10.14 (Mojave). Yoctopuce is frequently testing its modules on macOS 10.14.
Linux kernels currently supported are the 2.6 branch, the 3.x branch and the 4.x 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 4.15 (Ubuntu 18.04 LTS).
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 7.x on a Samsung Galaxy A6 with the Java for Android library.
USB 2.0 connectors exist in three sizes: the "standard" size that you probably use to connect your printer, the very common mini size to connect small devices, and finally the micro size often used to connect mobile phones, as long as they do not exhibit an apple logo. All USB modules manufactured by Yoctopuce use micro size connectors.
The most common USB 2.0 connectors: A, B, Mini B, Micro A, Micro B5
To connect your Yocto-VOC module to a computer, you need a USB 2.0 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 2.0 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-VOC module with a USB 2.0 cable of type A - micro B
If you insert a USB hub between the computer and the Yocto-VOC 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.
At this point, your Yocto-VOC 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 software6. 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 browser7. 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.
Module list as displayed in your web bowser
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.
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-VOC.
Properties of the Yocto-VOC module
This window allows you, among other things, to play with your module to check that it is working properly. Indeed, VOC values are displayed in real time after the required heating time lasting 15 minutes.
When, in the module list, you click on the configure button corresponding to your module, the configuration window is displayed.
Yocto-VOC module configuration.
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. However, it is always possible to reprogram the module correctly by using the Virtual Hub software 8 in command line 9.
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.
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.
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 only function provided by the Yocto-VOC module is the "voc" function. Simply click on the corresponding "rename" button to assign them a new logical name.
This chapter provides important information regarding the use of the Yocto-VOC module in real-world situations. Make sure to read it carefully before going too far into your project if you want to avoid pitfalls.
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-VOC 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.
The Yocto-VOC module is designed so that you can split it into two parts, allowing you to move away the sensor from the command sub-module. You can split the module by simply breaking the circuit. However, you will obtain better results if you use a good pincer, or cutting pliers. When you have split the sub-modules, you can sandpaper the protruding parts without risk.
The Yocto-VOC module is designed so that you can split it into two
parts.
Wiring under the modules once separated.
Once the module is split into two, you must rewire the sub-modules. Several solutions are available. You can connect the sub-modules by soldering simple electric wires, but you will obtain a better result with 1.27 pitch ribbon cable. Consider using solid copper cables, rather than threaded ones: solid copper cables are somewhat less flexible, but much easier to solder.
Moving the sensors away with a simple ribbon cable.
Warning, divisible Yoctopuce modules very often have very similar connection systems. Nevertheless, sub-modules from different models are not all compatible. If you connect your Yocto-VOC sub-module to another type of module such as a Yocto-Meteo for instance, it will not work, and you run a high risk of damaging your equipment.
Although USB means Universal Serial BUS, USB devices are not physically organized as a flat bus but as a tree, using point-to-point connections. This has consequences on power distribution: to make it simple, every USB port must supply power to all devices directly or indirectly connected to it. And USB puts some limits.
In theory, a USB port provides 100mA, and may provide up to 500mA if available and requested by the device. In the case of a hub without external power supply, 100mA are available for the hub itself, and the hub should distribute no more than 100mA to each of its ports. This is it, and this is not much. In particular, it means that in theory, it is not possible to connect USB devices through two cascaded hubs without external power supply. In order to cascade hubs, it is necessary to use self-powered USB hubs, that provide a full 500mA to each subport.
In practice, USB would not have been as successful if it was really so picky about power distribution. As it happens, most USB hub manufacturers have been doing 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 you controlling and planning overall power consumption for your project, all Yoctopuce modules include a built-in current sensor that indicates (with 5mA precision) the consumption of the module on the USB bus.
Note also that the USB cable itself may also cause power supply issues, in particular when the wires are too thin or when the cable is too long 10. Good cables are usually made using AWG 26 or AWG 28 wires for data lines and AWG 24 wires for power.
Connection methods to integrate the Yocto-VOC obviously have an impact on the system overall electromagnetic emissions, and therefore also impact the conformity with international standards.
When we perform reference measurements to validate the conformity of our products with IEC CISPR 11, we do not use any enclosure but connect the devices using a shielded USB cable, compliant with USB 2.0 specifications: the cable shield is connected to both connector shells, and the total resistance from shell to shell is under 0.6Ω. The USB cable length is 3m, in order to expose one meter horizontally, one meter vertically and keep the last meter close to the host computer within a ferrite bead.
If you use a non-shielded USB cable, or an improperly shielded cable, your system will work perfectly well but you may not remain in conformity with the emission standard. If you are building a system made of multiple devices connected using 1.27mm pitch connectors, or with a sensor moved away from the device CPU, you can generally recover the conformity by using a metallic enclosure acting as an external shield.
Still on the topic of electromagnetic compatibility, the maximum supported length of the USB cable is 3m. In addition to the voltage drop issue mentionned above, using longer wires would require to run extra tests to assert compatibility with the electromagnetic immunity standards.
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-VOC 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.
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.
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.
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.
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-VOC 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.
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.
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.
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.
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.
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.
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.
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.
The Yocto-VOC module provides a single instance of the voc and DataLogger functions, matching the Volatile Organic Compound sensor and the data logger
module : Module
attribute | type | modifiable ? |
---|---|---|
productName | String | read-only |
serialNumber | String | read-only |
logicalName | String | modifiable |
productId | Hexadecimal number | read-only |
productRelease | Hexadecimal number | read-only |
firmwareRelease | String | read-only |
persistentSettings | Enumerated | modifiable |
luminosity | 0..100% | modifiable |
beacon | On/Off | modifiable |
upTime | Time | read-only |
usbCurrent | Used current (mA) | read-only |
rebootCountdown | Integer | modifiable |
userVar | Integer | modifiable |
attribute | type | modifiable ? |
---|---|---|
logicalName | String | modifiable |
advertisedValue | String | modifiable |
unit | String | read-only |
currentValue | Fixed-point number | read-only |
lowestValue | Fixed-point number | modifiable |
highestValue | Fixed-point number | modifiable |
currentRawValue | Fixed-point number | read-only |
logFrequency | Frequency | modifiable |
reportFrequency | Frequency | modifiable |
advMode | Enumerated | modifiable |
calibrationParam | Calibration parameters | modifiable |
resolution | Fixed-point number | modifiable |
sensorState | Integer | read-only |
attribute | type | modifiable ? |
---|---|---|
logicalName | String | modifiable |
advertisedValue | String | modifiable |
currentRunIndex | Integer | read-only |
timeUTC | UTC time | modifiable |
recording | Enumerated | modifiable |
autoStart | On/Off | modifiable |
beaconDriven | On/Off | modifiable |
clearHistory | Boolean | modifiable |
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.
Character string containing the commercial name of the module, as set by the factory.
Character string containing the serial number, unique and programmed at the factory. For a Yocto-VOC module, this serial number always starts with YVOCMK01. You can use the serial number to access a given module by software.
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 -.
USB device identifier of the module, preprogrammed to 41 at the factory.
Release number of the module hardware, preprogrammed at the factory.
Release version of the embedded firmware, changes each time the embedded software is updated.
State of persistent module settings: loaded from flash memory, modified by the user or saved to flash memory.
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.
Activity of the localization beacon of the module.
Time elapsed since the last time the module was powered on.
Current consumed by the module on the USB bus, in milli-amps.
Countdown to use for triggering a reboot of the module.
32bit integer variable available for user storage.
The Yoctopuce class YVoc allows you to read and configure Yoctopuce Volatile Organic Compound sensors. It inherits from YSensor class the core functions to read measurements, to register callback functions, to access the autonomous datalogger.
Character string containing the logical name of the Volatile Organic Compound 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 Volatile Organic Compound sensor directly. If two Volatile Organic Compound 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 -.
Short character string summarizing the current state of the Volatile Organic Compound sensor, that is automatically advertised up to the parent hub. For a Volatile Organic Compound sensor, the advertised value is the current value of the estimated VOC concentration.
Short character string representing the measuring unit for the estimated VOC concentration.
Current value of the estimated VOC concentration, in ppm (vol), as a floating point number.
Minimal value of the estimated VOC concentration, in ppm (vol), as a floating point number.
Maximal value of the estimated VOC concentration, in ppm (vol), as a floating point number.
Uncalibrated, unrounded raw value returned by the sensor, as a floating point number.
Datalogger recording frequency, or "OFF" when measures should not be stored in the data logger flash memory.
Timed value notification frequency, or "OFF" when timed value notifications are disabled for this function.
Measuring mode for the advertised value pushed to the parent hub.
Extra calibration parameters (for instance to compensate for the effects of an enclosure), as an array of 16 bit words.
Measure resolution (i.e. precision of the numeric representation, not necessarily of the measure itself).
Sensor health state (zero when a current measure is available).
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.
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 -.
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).
Current run number, corresponding to the number of time the module was powered on with the dataLogger enabled at some point.
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.
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.
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.
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.
Attribute that can be set to true to clear recorded data.
There are several methods to control you Yoctopuce module by software.
In this case, the software driving your project is compiled directly with a library which provides control of the modules. Objectively, it is the simplest and most elegant solution for the end user. The end user then only needs to plug the USB cable and run your software for everything to work. Unfortunately, this method is not always available or even possible.
The application uses the native library to control the locally connected module
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
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 VirtualHub11. 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.
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.
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 | Native | Native with DLL | Virtual hub |
---|---|---|---|
C++ | ✔ | ✔ | ✔ |
Objective-C | ✔ | - | ✔ |
Delphi | - | ✔ | ✔ |
Python | - | ✔ | ✔ |
VisualBasic .Net | - | ✔ | ✔ |
C# .Net | - | ✔ | ✔ |
C# UWP | ✔ | - | ✔ |
EcmaScript / JavaScript | - | - | ✔ |
PHP | - | - | ✔ |
Java | - | ✔ | ✔ |
Java for Android | ✔ | - | ✔ |
Command line | ✔ | - | ✔ |
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.
At this point of the user's guide, you should know the main theoretical points of your Yocto-VOC. It is now time to practice. You must download the Yoctopuce library for your favorite programming language from the Yoctopuce web site12. 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-VOC.
When you want to perform a punctual operation on your Yocto-VOC, 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 provided13.
Download the command line API14. 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-VOC, open a shell, and start working by typing for example:
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.
All the command line API executables work on the same principle. They must be called the following way
[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.
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:
to know the list of available commands for a given command line API executable, or even:
to obtain a detailed description of the parameters of a command.
To control the Voc function of your Yocto-VOC, you need the YVoc executable file.
For instance, you can launch:
This example uses the "any" target to indicate that we want to work on the first Voc 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-VOC module with the YVOCMK01-123456 serial number which you have called "MyModule", and its voc 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).
To work on all the Voc functions at the same time, use the "all" target.
For more details on the possibilities of the YVoc executable, use:
Each module can be controlled in a similar way with the help of the YModule executable. For example, to obtain the list of all the connected modules, use:
You can also use the following command to obtain an even more detailed list of the connected modules:
Each xxx property of the module can be obtained thanks to a command of the get_xxxx() type, and the properties which are not read only can be modified with the set_xxx() command. For example:
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:
Note that you can do the same thing in a single command with the -s option.
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.
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 VirtualHub15 on the concerned machine, and use the executables of the command line API with the -r option. For example, if you use:
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:
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.
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.
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.
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.
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:
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:
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:
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.
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.
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:
Once done, you can start the example file using:
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:
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.
If you need to run this library on older JavaScript engines, you can use Babel18 to transpile your code and the library into older JavaScript standards. To install Babel with typical settings, simply use:
You would typically ask Babel to put the transpiled files in another directory, named compat for instance. Your files and all files of the Yoctopuce library should be transpiled, as follow:
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.
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
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
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:
you can use:
You can also rewrite this last asynchronous call as:
A few lines of code are enough to use a Yocto-VOC. Here is the skeleton of a JavaScript code snipplet to use the Voc function.
Let us look at these lines in more details.
These two import provide access to functions allowing you to manage Yoctopuce modules. yocto_api is always needed, yocto_voc is necessary to manage modules containing a Volatile Organic Compound sensor, such as Yocto-VOC. Other imports can be useful in other cases, such as YModule which can let you enumerate any type of Yoctopuce device.
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.
The FindVoc method allows you to find a Volatile Organic Compound 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-VOC module with serial number YVOCMK01-123456 which you have named "MyModule", and for which you have given the voc function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.
YVoc.FindVoc returns an object which you can then use at will to control the Volatile Organic Compound sensor.
The isOnline() method of the object returned by FindVoc allows you to know if the corresponding module is present and in working order.
The get_currentValue() method of the object returned by YVoc.FindVoc provides the volatil organic compound level currently measured by the sensor. The value returned is a floating number in parts per million CO2 equivalent.
Open a command window (a terminal, a shell...) and go into the directory example_nodejs/Doc-GettingStarted-Yocto-VOC 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-VOC 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-VOC is connected and where you run the VirtualHub.
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:
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-VOC. 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.
No installation is needed to run this example, all you have to do is open the HTML file using a web browser,
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.
Each property xxx of the module can be read thanks to a method of type get_xxxx(), and properties which are not read-only can be modified with the help of the set_xxx() method. For more details regarding the used functions, refer to the API chapters.
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.
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.
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.
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:
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.
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) server19, 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.
Go to the Yoctopuce web site and download the following items:
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.
A few lines of code are enough to use a Yocto-VOC. Here is the skeleton of a PHP code snipplet to use the Voc function.
Let's look at these lines in more details.
These two PHP includes provides access to the functions allowing you to manage Yoctopuce modules. yocto_api.php must always be included, yocto_voc.php is necessary to manage modules containing a Volatile Organic Compound sensor, such as Yocto-VOC.
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.
The yFindVoc function allows you to find a Volatile Organic Compound 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-VOC module with serial number YVOCMK01-123456 which you have named "MyModule", and for which you have given the voc function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.
yFindVoc returns an object which you can then use at will to control the Volatile Organic Compound sensor.
The isOnline() method of the object returned by yFindVoc allows you to know if the corresponding module is present and in working order.
The get_currentValue() method of the object returned by yFindVoc provides the Volatile Organic Compound level currently measured by the sensor. The value returned is a floating number in parts per million, CO2 equivalent.
Open your preferred text editor22, 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-VOC 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.
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.
Each property xxx of the module can be read thanks to a method of type get_xxxx(), and properties which are not read-only can be modified with the help of the set_xxx() method. For more details regarding the used functions, refer to the API chapters.
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.
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.
Obtaining the list of the connected modules is performed with the yFirstModule() function which returns the first module found. Then, you only need to call the nextModule() function of this object to find the following modules, and this as long as the returned value is not NULL. Below a short example listing the connected modules.
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.
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.
Responses from request from LAN machines are routed.
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.
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:
Click on the "configure" button on the first line
Click on the "edit" button of the "Outgoing callbacks" section
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.
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).
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.
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.
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.
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:
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.
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 site23. 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++ libraries24 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.
A few lines of code are enough to use a Yocto-VOC. Here is the skeleton of a C++ code snipplet to use the Voc function.
Let's look at these lines in more details.
These two include files provide access to the functions allowing you to manage Yoctopuce modules. yocto_api.h must always be used, yocto_voc.h is necessary to manage modules containing a Volatile Organic Compound sensor, such as Yocto-VOC.
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.
The yFindVoc function allows you to find a Volatile Organic Compound 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-VOC module with serial number YVOCMK01-123456 which you have named "MyModule", and for which you have given the voc function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.
yFindVoc returns an object which you can then use at will to control the Volatile Organic Compound sensor.
The isOnline() method of the object returned by yFindVoc allows you to know if the corresponding module is present and in working order.
The get_currentValue() method of the object returned by yFindVoc provides the Volatile Organic Compound level currently measured by the sensor. The value returned is a floating number in parts per million, CO2 equivalent.
Launch your C++ environment and open the corresponding sample project provided in the directory Examples/Doc-GettingStarted-Yocto-VOC 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.
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.
Each property xxx of the module can be read thanks to a method of type get_xxxx(), and properties which are not read-only can be modified with the help of the set_xxx() method. For more details regarding the used functions, refer to the API chapters.
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.
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.
Obtaining the list of the connected modules is performed with the yFirstModule() function which returns the first module found. Then, you only need to call the nextModule() function of this object to find the following modules, and this as long as the returned value is not NULL. Below a short example listing the connected modules.
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:
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.
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.
Integrating all the sources of the library into your projects has several advantages:
To integrate the source code, the easiest way is to simply include the Sources directory of your Yoctopuce library into your IncludePath, and to add all the files of this directory (including the sub-directory yapi) to your project.
For your project to build correctly, you need to link with your project the prerequisite system libraries, that is:
Integration of the Yoctopuce library as a static library is a simpler manner to build a small executable which uses Yoctopuce modules. You can quickly compile the program with a single command. You do not need to install a dynamic library specific to Yoctopuce, everything is in the executable.
To integrate the static Yoctopuce library to your project, you must include the Sources directory of the Yoctopuce library into your IncludePath, and add the sub-directory Binaries/... corresponding to your operating system into your libPath.
Then, for you project to build correctly, you need to link with your project the Yoctopuce library and the prerequisite system libraries:
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 of the Yoctopuce library as a dynamic library allows you to produce an executable smaller than with the two previous methods, and to possibly update this library, if a patch reveals itself necessary, without needing to recompile the source code of the application. On the other hand, it is an integration mode which systematically requires you to copy the dynamic library on the target machine where the application will run (yocto.dll for Windows, libyocto.so.1.0.1 for Mac OS X and Linux).
To integrate the dynamic Yoctopuce library to your project, you must include the Sources directory of the Yoctopuce library into your IncludePath, and add the sub-directory Binaries/... corresponding to your operating system into your LibPath.
Then, for you project to build correctly, you need to link with your project the dynamic Yoctopuce library and the prerequisite system libraries:
With GCC, the command line to compile is simply:
gcc (...) -lyocto -lm -lpthread -lusb-1.0 -lstdc++
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 libraries25 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 example26 with video shots showing how to integrate the library into your projects.
Launch Xcode 4.2 and open the corresponding sample project provided in the directory Examples/Doc-GettingStarted-Yocto-VOC of the Yoctopuce library.
There are only a few really important lines in this example. We will look at them in details.
These two import files provide access to the functions allowing you to manage Yoctopuce modules. yocto_api.h must always be used, yocto_voc.h is necessary to manage modules containing a Volatile Organic Compound sensor, such as Yocto-VOC.
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.
The [Voc FindVoc] function allows you to find a Volatile Organic Compound 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-VOC module with serial number YVOCMK01-123456 which you have named "MyModule", and for which you have given the voc function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.
[Voc FindVoc] returns an object which you can then use at will to control the Volatile Organic Compound sensor.
The isOnline method of the object returned by [Voc FindVoc] allows you to know if the corresponding module is present and in working order.
The get_currentValue() method of the object returned by YVoc.FindVoc provides the volatil organic compound level currently measured by the sensor. The value returned is a floating number in parts per million CO2 equivalent.
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.
Each property xxx of the module can be read thanks to a method of type get_xxxx, and properties which are not read-only can be modified with the help of the set_xxx: method. For more details regarding the used functions, refer to the API chapters.
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.
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.
Obtaining the list of the connected modules is performed with the yFirstModule() function which returns the first module found. Then, you only need to call the nextModule() function of this object to find the following modules, and this as long as the returned value is not NULL. Below a short example listing the connected modules.
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:
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.
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 site27.
Download the Visual Basic Yoctopuce library from the Yoctopuce web site28. 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.
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 modules29. The source files in Visual Basic manage the high level part of the API. Therefore, your need both this DLL and the .vb files of the sources directory to create a project managing Yoctopuce modules.
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.
Then add in the same manner the yapi.dll DLL, located in the Sources/dll directory30. 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.
A few lines of code are enough to use a Yocto-VOC. Here is the skeleton of a Visual Basic code snipplet to use the Voc function.
Let's look at these lines in more details.
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.
The yFindVoc function allows you to find a Volatile Organic Compound 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-VOC module with serial number YVOCMK01-123456 which you have named "MyModule", and for which you have given the voc function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.
yFindVoc returns an object which you can then use at will to control the Volatile Organic Compound sensor.
The isOnline() method of the object returned by yFindVoc allows you to know if the corresponding module is present and in working order.
The get_currentValue() method of the object returned by yFindVoc provides the Volatile Organic Compound level currently measured by the sensor. The value returned is a floating number in parts per million, CO2 equivalent.
Launch Microsoft VisualBasic and open the corresponding sample project provided in the directory Examples/Doc-GettingStarted-Yocto-VOC 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.
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.
Each property xxx of the module can be read thanks to a method of type get_xxxx(), and properties which are not read-only can be modified with the help of the set_xxx() method. For more details regarding the used functions, refer to the API chapters.
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.
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.
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.
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:
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.
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 site31.
Our programming library is also compatible with Mono, the open source version of C# that also works on Linux and MacOS. You will find on our web site various articles that describe how to configure Mono to use our library.
Download the Visual C# Yoctopuce library from the Yoctopuce web site32. 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.
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 modules33. The source files in Visual C# manage the high level part of the API. Therefore, your need both this DLL and the .cs files of the sources directory to create a project managing Yoctopuce modules.
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.
Then add in the same manner the yapi.dll DLL, located in the Sources/dll directory34. 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.
A few lines of code are enough to use a Yocto-VOC. Here is the skeleton of a C# code snipplet to use the Voc function.
Let's look at these lines in more details.
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.
The YVoc.FindVoc function allows you to find a Volatile Organic Compound 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-VOC module with serial number YVOCMK01-123456 which you have named "MyModule", and for which you have given the voc function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.
YVoc.FindVoc returns an object which you can then use at will to control the Volatile Organic Compound sensor.
The isOnline() method of the object returned by YVoc.FindVoc allows you to know if the corresponding module is present and in working order.
The get_currentValue() method of the object returned by YVoc.FindVoc provides the volatil organic compound level currently measured by the sensor. The value returned is a floating number in parts per million CO2 equivalent.
Launch Microsoft Visual C# and open the corresponding sample project provided in the directory Examples/Doc-GettingStarted-Yocto-VOC 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.
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.
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.
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.
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.
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.
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:
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.
Universal Windows Platform (UWP) is not a language per say, but a software platform created by Microsoft. This platform allows you to run a new type of applications: the universal Windows applications. These applications can work on all machines running under Windows 10. This includes computers, tablets, smart phones, XBox One, and also Windows IoT Core.
The Yoctopuce UWP library allows you to use Yoctopuce modules in a universal Windows application and is written in C# in its entirety. You can add it to a Visual Studio 201735 project.
The Universal Windows Platform does not use the Win32 API but only the Windows Runtime API which is available on all the versions of Windows 10 and for any architecture. Thanks to this library, you can use UWP on all the Windows 10 versions, including Windows 10 IoT Core.
However, using the new UWP API has some consequences: the Windows Runtime API to access the USB ports is asynchronous, and therefore the Yoctopuce library must be asynchronous as well. Concretely, the asynchronous methods do not return a result directly but a Task or Task<> object and the result can be obtained later. Fortunately, the C# language, version 6, supports the async and await keywords, which simplifies using these functions enormously. You can thus use asynchronous functions in the same way as traditional functions as long as you respect the following two rules:
For you not to have to wonder wether a function is asynchronous or not, there is the following convention: all the public methods of the UWP library are asynchronous, that is that you must call them with the await keyword, except:
Download the Yoctopuce library for $LANG$ from the Yoctopuce web site36. There is no installation software, simply copy the content of the zip file in a directory of your choice. You essentially need the content of the Sources directory. The other directories contain documentation and a few sample programs. Sample projects are Visual Studio 2017 projects. Visual Studio 2017 is available on the Microsoft web site37.
Start by creating your project. Then, from the Solution Explorer panel right click on your project and select Add then Existing element .
A file chooser opens: select all the files in the library Sources directory.
You then have the choice between simply adding the files to your project or adding them as a link (the Add button is actually a drop-down menu). In the first case, Visual Studio copies the selected files into your project. In the second case, Visual Studio simply creates a link to the original files. We recommend to use links, as a potential library update is thus much easier.
By default a Universal Windows application doesn't have access rights to the USB ports. If you want to access USB devices, you must imperatively declare it in the Package.appxmanifest file.
Unfortunately, the edition window of this file doesn't allow this operation and you must modify the Package.appxmanifest file by hand. In the "Solution Explorer" panel, right click on the Package.appxmanifest and select "View Code".
In this XML file, we must add a DeviceCapability node in the Capabilities node. This node must have a "Name" attribute with a "humaninterfacedevice" value.
Inside this node, you must declare all the modules that can be used. Concretely, for each module, you must add a "Device" node with an "Id" attribute, which has for value a character string "vidpid:USB_VENDORID USB_DEVICE_ID". The Yoctopuce USB_VENDORID is 24e0 and you can find the USB_DEVICE_ID of each Yoctopuce device in the documentation in the "Characteristics" section. Finally, the "Device" node must contain a "Function" node with the "Type" attribute with a value of "usage:ff00 0001".
For the Yocto-VOC, here is what you must add in the "Capabilities" node:
Unfortunately, it's not possible to write a rule authorizing all Yoctopuce modules. Therefore, you must imperatively add each module that you want to use.
A few lines of code are enough to use a Yocto-VOC. Here is the skeleton of a C# code snippet to use the Voc function.
Let us look at these lines in more details.
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.
The YVoc.FindVoc function allows you to find a Volatile Organic Compound 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-VOC module with serial number YVOCMK01-123456 which you have named "MyModule", and for which you have given the voc function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.
YVoc.FindVoc returns an object which you can then use at will to control the Volatile Organic Compound sensor.
The isOnline() method of the object returned by YVoc.FindVoc allows you to know if the corresponding module is present and in working order.
The get_currentValue() method of the object returned by YVoc.FindVoc provides the volatil organic compound level currently measured by the sensor. The value returned is a floating number in parts per million CO2 equivalent.
Launch Visual Studio and open the corresponding project provided in the directory Examples/Doc-GettingStarted-Yocto-VOC of the Yoctopuce library.
Visual Studio projects contain numerous files, and most of them are not linked to the use of the Yoctopuce library. To simplify reading the code, we regrouped all the code that uses the library in the Demo class, located in the demo.cs file. Properties of this class correspond to the different fields displayed on the screen, and the Run() method contains the code which is run when the "Start" button is pushed.
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.
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.
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.
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.
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.
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.
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 Universal Windows Platform library, error handling is implemented with exceptions. You must therefore intercept and correctly handle these exceptions if you want to have a reliable project which does not crash as soon as you disconnect a module.
Library thrown exceptions are always of the YAPI_Exception type, so you can easily separate them from other exceptions in a try{...} catch{...} block.
Example:
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 something38.
Delphi libraries are provided not as VCL components, but directly as source files. These files are compatible with most Delphi versions. 39
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.
Go to the Yoctopuce web site and download the Yoctopuce Delphi libraries40. Uncompress everything in a directory of your choice, add the subdirectory sources in the list of directories of Delphi libraries.41
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.
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:
There are only a few really important lines in this sample example. We will look at them in details.
These two units provide access to the functions allowing you to manage Yoctopuce modules. yocto_api must always be used, yocto_voc is necessary to manage modules containing a Volatile Organic Compound sensor, such as Yocto-VOC.
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.
The yFindVoc function allows you to find a Volatile Organic Compound 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-VOC module with serial number YVOCMK01-123456 which you have named "MyModule", and for which you have given the voc function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.
yFindVoc returns an object which you can then use at will to control the Volatile Organic Compound sensor.
The isOnline() method of the object returned by yFindVoc allows you to know if the corresponding module is present and in working order.
The get_currentValue() method of the object returned by yFindVoc provides the Volatile Organic Compound level currently measured by the sensor. The value returned is a floating number in parts per million, CO2 equivalent.
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.
Each property xxx of the module can be read thanks to a method of type get_xxxx(), and properties which are not read-only can be modified with the help of the set_xxx() method. For more details regarding the used functions, refer to the API chapters.
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.
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.
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.
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:
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.
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 site42.
The Yoctopuce library classes43 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.
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.
A few lines of code are enough to use a Yocto-VOC. Here is the skeleton of a Python code snipplet to use the Voc function.
Let's look at these lines in more details.
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.
The YVoc.FindVoc function allows you to find a Volatile Organic Compound 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-VOC module with serial number YVOCMK01-123456 which you have named "MyModule", and for which you have given the voc function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.
YVoc.FindVoc returns an object which you can then use at will to control the Volatile Organic Compound sensor.
The isOnline() method of the object returned by YVoc.FindVoc allows you to know if the corresponding module is present and in working order.
The get_currentValue() method of the object returned by YVoc.FindVoc provides the volatil organic compound level currently measured by the sensor. The value returned is a floating number in parts per million CO2 equivalent.
Launch Python and open the corresponding sample script provided in the directory Examples/Doc-GettingStarted-Yocto-VOC 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.
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.
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.
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.
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.
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.
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:
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.
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.
Go to the Yoctopuce web site and download the following items:
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.
A few lines of code are enough to use a Yocto-VOC. Here is the skeleton of a Java code snippet to use the Voc function.
Let us look at these lines in more details.
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.
The YVoc.FindVoc function allows you to find a Volatile Organic Compound 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-VOC module with serial number YVOCMK01-123456 which you have named "MyModule", and for which you have given the voc function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.
YVoc.FindVoc returns an object which you can then use at will to control the Volatile Organic Compound sensor.
The isOnline() method of the object returned by YVoc.FindVoc allows you to know if the corresponding module is present and in working order.
The get_currentValue() method of the object returned by YVoc.FindVoc provides the volatil organic compound level currently measured by the sensor. The value returned is a floating number in parts per million CO2 equivalent.
Launch you Java environment and open the corresponding sample project provided in the directory Examples/Doc-GettingStarted-Yocto-VOC 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.
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.
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.
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.
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.
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.
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, 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.
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.
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.
Go to the Yoctopuce web site and download the Java for Android programming library46. 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.
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.
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.
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.
The library is tested and validated on the following machines:
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 47.
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.
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 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 YAPI_Exception exception is generated.
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.
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.
A few lines of code are enough to use a Yocto-VOC. Here is the skeleton of a Java code snippet to use the Voc function.
Let us look at these lines in more details.
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.
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.
The YVoc.FindVoc function allows you to find a Volatile Organic Compound 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-VOC module with serial number YVOCMK01-123456 which you have named "MyModule", and for which you have given the voc function the name "MyFunction". The following five calls are strictly equivalent, as long as "MyFunction" is defined only once.
YVoc.FindVoc returns an object which you can then use at will to control the Volatile Organic Compound sensor.
The isOnline() method of the object returned by YVoc.FindVoc allows you to know if the corresponding module is present and in working order.
The get_currentValue() method of the object returned by YVoc.FindVoc provides the volatil organic compound level currently measured by the sensor. The value returned is a floating number in parts per million CO2 equivalent.
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.
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.
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.
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.
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.
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.
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.
The preceding chapters have introduced, in each available language, the basic programming functions which can be used with your Yocto-VOC 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.
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.
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 is the function which is called each time a new Yoctopuce module is connected. It takes as parameter the relevant module.
You must then tell the API that it must call the callback when a new module is connected.
Note that if modules are already connected when the callback is registered, the callback is called for each of the already connected modules.
A classis issue of callback programming is that these callbacks can be triggered at any time, including at times when the main program is not ready to receive them. This can have undesired side effects, such as dead-locks and other race conditions. Therefore, in the Yoctopuce API, module arrival/departure callbacks are called only when the UpdateDeviceList() function is running. You only need to call UpdateDeviceList() at regular intervals from a timer or from a specific thread to precisely control when the calls to these callbacks happen:
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.
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.
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.
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.
This type of callback is called when a Volatile Organic Compound sensor changes in a significant way. It takes as parameter the relevant function and the new value, as a character string. 48
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 YVoc object using function set_userData. You can then retrieve it in the global callback procedure using get_userData.
The callback is set up for a given Voc function with the help of the registerValueCallback method. The following example sets up a callback for the first available Voc function.
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).
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.
The callback is set up for a given Voc 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 Voc function.
As for value change callbacks, each module function can thus have its own distinct timed report callback.
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 YVoc. Thus, the same callback function will be usable with any subclass of YSensor (and in particular with YVoc). 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.
You can find a complete example implemented in your favorite programming language in the Examples/Prog-EventBased directory of the corresponding library.
Your Yocto-VOC 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.
The data logger can be started with the set_recording() method.
It is possible to make the data recording start automatically as soon as the module is powered on.
Note: Yoctopuce modules do not need an active USB connection to work: they start working as soon as they are powered on. The Yocto-VOC 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.
The memory of the data logger can be erased with the forgetAllDataStreams() function. Be aware that erasing cannot be undone.
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:
To avoid wasting flash memory, it is possible to disable logging for specified functions. In order to do so, simply use the value "OFF":
Limitation: The Yocto-VOC 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.
To load recorded measures from the Yocto-VOC 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:
Measures are instances of YMeasure 49. 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:
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.
As the Yocto-VOC does not have a battery, it cannot guess alone the current time when powered on. Nevertheless, the Yocto-VOC 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 none of these conditions applies (for instance if the module is simply connected to an USB charger), the Yocto-VOC 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-VOC 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-VOC might be be subject to a clock skew (theoretically up to 0.3%).
Your Yocto-VOC 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-VOC. 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-VOC 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.
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-VOC. On the other hand, the API supports an external arbitrary calibration, implemented with callbacks.
These transformations are performed directly inside the Yocto-VOC 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.
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 voc 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 voc 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.
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 voc 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.
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.
Note that the values before correction must be sorted in a strictly ascending order, otherwise they are simply ignored.
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
To cancel the effect of a calibration on a function, call the calibrateFromPoints() method with two empty arrays.
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.
Due to storage and processing limitations of real values within Yoctopuce sensors, raw values and corrected values must conform to a few numeric consraints:
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.
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.
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.
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.
The following example updates all the Yoctopuce modules connected by USB.
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 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.
If you need to integrate firmware updates in your application, the libraries offer you an API to update your modules. 50
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.
You can then apply these parameters to other modules with the set_allSettings() method.
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 .
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.
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.
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.
The startUpdate() method starts the update as a background task. This background task automatically takes care of
The get_progress() and get_progressMessage() methods enable you to follow the progression of the update. get_progress() returns the progression as a percentage (100 = update complete). get_progressMessage() 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.
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.
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.
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).
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.
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.
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.
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.
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.
Each Yoctopuce module has its own REST interface, available in several variants. Let us imagine a Yocto-VOC with the YVOCMK01-12345 serial number and the myModule logical name. The following URL allows you to know the state of the module.
You can naturally also use the module logical name rather than its serial number.
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:
To change the value of a property, modify the corresponding attribute. Thus, to modify the luminosity, send the following request:
The module functions can be manipulated in the same way. To know the state of the voc function, build the following URL:
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:
Rather logically, attributes can be modified in the same manner.
You can find the list of available attributes for your Yocto-VOC at the beginning of the Programming chapter.
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:
Individual measures for any given stream can be obtained by appending the desired function identifier as well as start time of the stream:
The low level Yoctopuce API is available under several formats of dynamic libraries written in C. The sources are available with the C++ API. If you use one of these low level libraries, you do not need the VirtualHub anymore.
Filename | Platform |
---|---|
libyapi.dylib | Max OS X |
libyapi-amd64.so | Linux Intel (64 bits) |
libyapi-armel.so | Linux ARM EL |
libyapi-armhf.so | Linux ARM HL |
libyapi-i386.so | Linux Intel (32 bits) |
yapi64.dll | Windows (64 bits) |
yapi.dll | Windows (32 bits) |
These dynamic libraries contain all the functions necessary to completely rebuild the whole high level API in any language able to integrate these libraries. This chapter nevertheless restrains itself to describing basic use of the modules.
The three essential functions of the low level API are the following:
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.
To perform an inventory of Yoctopuce modules, you need two functions from the dynamic library:
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 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 | Type | Size (bytes) | Description |
---|---|---|---|
vendorid | int | 4 | Yoctopuce USB ID |
deviceid | int | 4 | Module USB ID |
devrelease | int | 4 | Module version |
nbinbterfaces | int | 4 | Number of USB interfaces used by the module |
manufacturer | char[] | 20 | Yoctopuce (null terminated) |
productname | char[] | 28 | Model (null terminated) |
serial | char[] | 20 | Serial number (null terminated) |
logicalname | char[] | 20 | Logical name (null terminated) |
firmware | char[] | 22 | Firmware version (null terminated) |
beacon | byte | 1 | Beacon state (0/1) |
The errmsg parameter must point to a 255 character buffer to retrieve a potential error message.
Here is a sample program written in pascal using the yapi.dll DLL to list the connected modules.
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_.
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.
This chapter summarizes the high-level API functions to drive your Yocto-VOC. 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.
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 | <script type='text/javascript' src='yocto_api.js'></script> |
cpp | #include "yocto_api.h" |
m | #import "yocto_api.h" |
pas | uses yocto_api; |
vb | yocto_api.vb |
cs | yocto_api.cs |
java | import com.yoctopuce.YoctoAPI.YModule; |
uwp | import com.yoctopuce.YoctoAPI.YModule; |
py | from yocto_api import * |
php | require_once('yocto_api.php'); |
es | in HTML: <script src="../../lib/yocto_api.js"></script> in node.js: require('yoctolib-es2017/yocto_api.js'); |
Global functions |
---|
yCheckLogicalName(name) |
Checks if a given string is valid as logical name for a module or a function. |
yClearHTTPCallbackCacheDir(bool_removeFiles) |
Disables the HTTP callback cache. |
yDisableExceptions() |
Disables the use of exceptions to report runtime errors. |
yEnableExceptions() |
Re-enables the use of exceptions for runtime error handling. |
yEnableUSBHost(osContext) |
This function is used only on Android. |
yFreeAPI() |
Frees dynamically allocated memory blocks used by the Yoctopuce library. |
yGetAPIVersion() |
Returns the version identifier for the Yoctopuce library in use. |
yGetCacheValidity() |
Returns the validity period of the data loaded by the library. |
yGetDeviceListValidity() |
Returns the time between each forced enumeration of the YoctoHub used. |
yGetTickCount() |
Returns the current value of a monotone millisecond-based time counter. |
yHandleEvents(errmsg) |
Maintains the device-to-library communication channel. |
yInitAPI(mode, errmsg) |
Initializes the Yoctopuce programming library explicitly. |
yPreregisterHub(url, errmsg) |
Fault-tolerant alternative to RegisterHub(). |
yRegisterDeviceArrivalCallback(arrivalCallback) |
Register a callback function, to be called each time a device is plugged. |
yRegisterDeviceRemovalCallback(removalCallback) |
Register a callback function, to be called each time a device is unplugged. |
yRegisterHub(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. |
yRegisterHubWebsocketCallback(ws, errmsg, authpwd) |
Variant to RegisterHub() used to initialize Yoctopuce API on an existing Websocket session, as happens for incoming websocket callbacks. |
yRegisterLogFunction(logfun) |
Registers a log callback function. |
ySelectArchitecture(arch) |
Select the architecture or the library to be loaded to access to USB. |
ySetCacheValidity(cacheValidityMs) |
Change the validity period of the data loaded by the library. |
ySetDelegate(object) |
(Objective-C only) Register an object that must follow the protocol YDeviceHotPlug. |
ySetDeviceListValidity(deviceListValidity) |
Change the time between each forced enumeration of the YoctoHub used. |
ySetHTTPCallbackCacheDir(str_directory) |
Enables the HTTP callback cache. |
ySetTimeout(callback, ms_timeout, args) |
Invoke the specified callback function after a given timeout. |
ySetUSBPacketAckMs(pktAckDelay) |
Enables the acknowledge of every USB packet received by the Yoctopuce library. |
ySleep(ms_duration, errmsg) |
Pauses the execution flow for a specified duration. |
yTestHub(url, mstimeout, errmsg) |
Test if the hub is reachable. |
yTriggerHubDiscovery(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. |
yUnregisterHub(url) |
Setup the Yoctopuce library to no more use modules connected on a previously registered machine with RegisterHub. |
yUpdateDeviceList(errmsg) |
Triggers a (re)detection of connected Yoctopuce modules. |
yUpdateDeviceList_async(callback, context) |
Triggers a (re)detection of connected Yoctopuce modules. |
Checks if a given string is valid as logical name for a module or a function.
js | function yCheckLogicalName( | name) |
cpp | bool yCheckLogicalName( | const string& name) |
m | +(BOOL) CheckLogicalName | :(NSString *) name |
pas | function yCheckLogicalName( | name: string): boolean |
vb | function yCheckLogicalName( | ByVal name As String) As Boolean |
cs | bool CheckLogicalName( | string name) |
java | boolean CheckLogicalName( | String name) |
uwp | bool CheckLogicalName( | string name) |
py | def CheckLogicalName( | name) |
php | function yCheckLogicalName( | $name) |
es | 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.
Disables the HTTP callback cache.
php | function yClearHTTPCallbackCacheDir( | $bool_removeFiles) |
This method disables the HTTP callback cache, and can additionally cleanup the cache directory.
Parameters :
bool_removeFiles | True to clear the content of the cache. |
Returns :
nothing.
Disables the use of exceptions to report runtime errors.
js | function yDisableExceptions( | ) |
cpp | void yDisableExceptions( | ) |
m | +(void) DisableExceptions |
pas | procedure yDisableExceptions( | ) |
vb | procedure yDisableExceptions( | ) |
cs | void DisableExceptions( | ) |
uwp | void DisableExceptions( | ) |
py | def DisableExceptions( | ) |
php | function yDisableExceptions( | ) |
es | 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.
Re-enables the use of exceptions for runtime error handling.
js | function yEnableExceptions( | ) |
cpp | void yEnableExceptions( | ) |
m | +(void) EnableExceptions |
pas | procedure yEnableExceptions( | ) |
vb | procedure yEnableExceptions( | ) |
cs | void EnableExceptions( | ) |
uwp | void EnableExceptions( | ) |
py | def EnableExceptions( | ) |
php | function yEnableExceptions( | ) |
es | 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.
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). |
Frees dynamically allocated memory blocks used by the Yoctopuce library.
js | function yFreeAPI( | ) |
cpp | void yFreeAPI( | ) |
m | +(void) FreeAPI |
pas | procedure yFreeAPI( | ) |
vb | procedure yFreeAPI( | ) |
cs | void FreeAPI( | ) |
java | void FreeAPI( | ) |
uwp | void FreeAPI( | ) |
py | def FreeAPI( | ) |
php | function yFreeAPI( | ) |
es | 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.
Returns the version identifier for the Yoctopuce library in use.
js | function yGetAPIVersion( | ) |
cpp | string yGetAPIVersion( | ) |
m | +(NSString*) GetAPIVersion |
pas | function yGetAPIVersion( | ): string |
vb | function yGetAPIVersion( | ) As String |
cs | String GetAPIVersion( | ) |
java | String GetAPIVersion( | ) |
uwp | string GetAPIVersion( | ) |
py | def GetAPIVersion( | ) |
php | function yGetAPIVersion( | ) |
es | 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.
Returns the validity period of the data loaded by the library.
cpp | static u64 yGetCacheValidity( | ) |
m | +(u64) GetCacheValidity |
pas | function yGetCacheValidity( | ): u64 |
vb | function yGetCacheValidity( | ) As Long |
cs | ulong GetCacheValidity( | ) |
java | long GetCacheValidity( | ) |
uwp | Task<ulong> GetCacheValidity( | ) |
py | def GetCacheValidity( | ) |
php | function yGetCacheValidity( | ) |
es | function GetCacheValidity( | ) |
This method returns the cache validity of all attributes module functions. Note: This function must be called after yInitAPI .
Returns :
an integer corresponding to the validity attributed to the loaded function parameters, in milliseconds
Returns the time between each forced enumeration of the YoctoHub used.
cpp | static int yGetDeviceListValidity( | ) |
m | +(int) GetDeviceListValidity |
pas | function yGetDeviceListValidity( | ): LongInt |
vb | function yGetDeviceListValidity( | ) As Integer |
cs | int GetDeviceListValidity( | ) |
java | int GetDeviceListValidity( | ) |
uwp | Task<int> GetDeviceListValidity( | ) |
py | def GetDeviceListValidity( | ) |
php | function yGetDeviceListValidity( | ) |
es | function GetDeviceListValidity( | ) |
Note: This function must be called after yInitAPI.
Returns :
the number of seconds between each enumeration.
Returns the current value of a monotone millisecond-based time counter.
js | function yGetTickCount( | ) |
cpp | u64 yGetTickCount( | ) |
m | +(u64) GetTickCount |
pas | function yGetTickCount( | ): u64 |
vb | function yGetTickCount( | ) As Long |
cs | ulong GetTickCount( | ) |
java | long GetTickCount( | ) |
uwp | ulong GetTickCount( | ) |
py | def GetTickCount( | ) |
php | function yGetTickCount( | ) |
es | 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.
Maintains the device-to-library communication channel.
js | function yHandleEvents( | errmsg) |
cpp | YRETCODE yHandleEvents( | string& errmsg) |
m | +(YRETCODE) HandleEvents | :(NSError**) errmsg |
pas | function yHandleEvents( | var errmsg: string): integer |
vb | function yHandleEvents( | ByRef errmsg As String) As YRETCODE |
cs | YRETCODE HandleEvents( | ref string errmsg) |
java | int HandleEvents( | ) |
uwp | Task<int> HandleEvents( | ) |
py | def HandleEvents( | errmsg=None) |
php | function yHandleEvents( | &$errmsg) |
es | 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.
Initializes the Yoctopuce programming library explicitly.
js | function yInitAPI( | mode, errmsg) |
cpp | YRETCODE yInitAPI( | int mode, string& errmsg) |
m | +(YRETCODE) InitAPI | :(int) mode :(NSError**) errmsg |
pas | function yInitAPI( | mode: integer, var errmsg: string): integer |
vb | function yInitAPI( | ByVal mode As Integer, ByRef errmsg As String) As Integer |
cs | int InitAPI( | int mode, ref string errmsg) |
java | int InitAPI( | int mode) |
uwp | Task<int> InitAPI( | int mode) |
py | def InitAPI( | mode, errmsg=None) |
php | function yInitAPI( | $mode, &$errmsg) |
es | 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.
Fault-tolerant alternative to RegisterHub().
js | function yPreregisterHub( | url, errmsg) |
cpp | YRETCODE yPreregisterHub( | const string& url, string& errmsg) |
m | +(YRETCODE) PreregisterHub | :(NSString *) url :(NSError**) errmsg |
pas | function yPreregisterHub( | url: string, var errmsg: string): integer |
vb | function yPreregisterHub( | ByVal url As String, |
ByRef errmsg As String) As Integer |
cs | int PreregisterHub( | string url, ref string errmsg) |
java | int PreregisterHub( | String url) |
uwp | Task<int> PreregisterHub( | string url) |
py | def PreregisterHub( | url, errmsg=None) |
php | function yPreregisterHub( | $url, &$errmsg) |
es | 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.
Register a callback function, to be called each time a device is plugged.
js | function yRegisterDeviceArrivalCallback( | arrivalCallback) |
cpp | void yRegisterDeviceArrivalCallback( | yDeviceUpdateCallback arrivalCallback) |
m | +(void) RegisterDeviceArrivalCallback | :(yDeviceUpdateCallback) arrivalCallback |
pas | procedure yRegisterDeviceArrivalCallback( | arrivalCallback: yDeviceUpdateFunc) |
vb | procedure yRegisterDeviceArrivalCallback( | ByVal arrivalCallback As yDeviceUpdateFunc) |
cs | void RegisterDeviceArrivalCallback( | yDeviceUpdateFunc arrivalCallback) |
java | void RegisterDeviceArrivalCallback( | DeviceArrivalCallback arrivalCallback) |
uwp | void RegisterDeviceArrivalCallback( | DeviceUpdateHandler arrivalCallback) |
py | def RegisterDeviceArrivalCallback( | arrivalCallback) |
php | function yRegisterDeviceArrivalCallback( | $arrivalCallback) |
es | 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 |
Register a callback function, to be called each time a device is unplugged.
js | function yRegisterDeviceRemovalCallback( | removalCallback) |
cpp | void yRegisterDeviceRemovalCallback( | yDeviceUpdateCallback removalCallback) |
m | +(void) RegisterDeviceRemovalCallback | :(yDeviceUpdateCallback) removalCallback |
pas | procedure yRegisterDeviceRemovalCallback( | removalCallback: yDeviceUpdateFunc) |
vb | procedure yRegisterDeviceRemovalCallback( | ByVal removalCallback As yDeviceUpdateFunc) |
cs | void RegisterDeviceRemovalCallback( | yDeviceUpdateFunc removalCallback) |
java | void RegisterDeviceRemovalCallback( | DeviceRemovalCallback removalCallback) |
uwp | void RegisterDeviceRemovalCallback( | DeviceUpdateHandler removalCallback) |
py | def RegisterDeviceRemovalCallback( | removalCallback) |
php | function yRegisterDeviceRemovalCallback( | $removalCallback) |
es | 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 |
Setup the Yoctopuce library to use modules connected on a given machine.
js | function yRegisterHub( | url, errmsg) |
cpp | YRETCODE yRegisterHub( | const string& url, string& errmsg) |
m | +(YRETCODE) RegisterHub | :(NSString *) url :(NSError**) errmsg |
pas | function yRegisterHub( | url: string, var errmsg: string): integer |
vb | function yRegisterHub( | ByVal url As String, |
ByRef errmsg As String) As Integer |
cs | int RegisterHub( | string url, ref string errmsg) |
java | int RegisterHub( | String url) |
uwp | Task<int> RegisterHub( | string url) |
py | def RegisterHub( | url, errmsg=None) |
php | function yRegisterHub( | $url, &$errmsg) |
es | function RegisterHub( | url, errmsg) |
The parameter will determine how the API will work. Use the following values:
usb: When the usb keyword is used, the API will work with devices connected directly to the USB bus. Some programming languages such a Javascript, PHP, and Java don't provide direct access to USB 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.
On failure, throws an exception or returns a negative error code.
Register a callback function, to be called each time an Network Hub send an SSDP message.
cpp | void yRegisterHubDiscoveryCallback( | YHubDiscoveryCallback hubDiscoveryCallback) |
m | +(void) RegisterHubDiscoveryCallback | : (YHubDiscoveryCallback) hubDiscoveryCallback |
pas | procedure yRegisterHubDiscoveryCallback( | hubDiscoveryCallback: YHubDiscoveryCallback) |
vb | procedure yRegisterHubDiscoveryCallback( | ByVal hubDiscoveryCallback As YHubDiscoveryCallback) |
cs | void RegisterHubDiscoveryCallback( | YHubDiscoveryCallback hubDiscoveryCallback) |
java | void RegisterHubDiscoveryCallback( | HubDiscoveryCallback hubDiscoveryCallback) |
uwp | Task RegisterHubDiscoveryCallback( | HubDiscoveryHandler hubDiscoveryCallback) |
py | 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 |
Variant to RegisterHub() used to initialize Yoctopuce API on an existing Websocket session, as happens for incoming websocket callbacks.
Parameters :
ws | node WebSocket object for the incoming websocket callback connection |
errmsg | a string passed by reference to receive any error message. |
authpwd | the optional authentication password, required only authentication is configured on the calling hub. |
Returns :
YAPI_SUCCESS when the call succeeds.
On failure, throws an exception or returns a negative error code.
Registers a log callback function.
cpp | void yRegisterLogFunction( | yLogFunction logfun) |
m | +(void) RegisterLogFunction | :(yLogCallback) logfun |
pas | procedure yRegisterLogFunction( | logfun: yLogFunc) |
vb | procedure yRegisterLogFunction( | ByVal logfun As yLogFunc) |
cs | void RegisterLogFunction( | yLogFunc logfun) |
java | void RegisterLogFunction( | LogCallback logfun) |
uwp | void RegisterLogFunction( | LogHandler logfun) |
py | 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 |
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.
Change the validity period of the data loaded by the library.
cpp | static void ySetCacheValidity( | u64 cacheValidityMs) |
m | +(void) SetCacheValidity | : (u64) cacheValidityMs |
pas | procedure ySetCacheValidity( | cacheValidityMs: u64) |
vb | procedure ySetCacheValidity( | ) |
cs | void SetCacheValidity( | ulong cacheValidityMs) |
java | void SetCacheValidity( | long cacheValidityMs) |
uwp | Task SetCacheValidity( | ulong cacheValidityMs) |
py | def SetCacheValidity( | cacheValidityMs) |
php | function ySetCacheValidity( | $cacheValidityMs) |
es | function SetCacheValidity( | cacheValidityMs) |
By default, when accessing a module, all the attributes of the module functions are automatically kept in cache for the standard duration (5 ms). This method can be used to change this standard duration, for example in order to reduce network or USB traffic. This parameter does not affect value change callbacks Note: This function must be called after yInitAPI.
Parameters :
cacheValidityMs | an integer corresponding to the validity attributed to the loaded function parameters, in milliseconds. |
(Objective-C only) Register an object that must follow the protocol YDeviceHotPlug.
m | +(void) SetDelegate | :(id) object |
The methods yDeviceArrival and yDeviceRemoval will be invoked while yUpdateDeviceList is running. You will have to call this function on a regular basis.
Parameters :
object | an object that must follow the protocol YAPIDelegate, or nil |
Change the time between each forced enumeration of the YoctoHub used.
cpp | static void ySetDeviceListValidity( | int deviceListValidity) |
m | +(void) SetDeviceListValidity | : (int) deviceListValidity |
pas | procedure ySetDeviceListValidity( | deviceListValidity: LongInt) |
vb | procedure ySetDeviceListValidity( | ) |
cs | void SetDeviceListValidity( | int deviceListValidity) |
java | void SetDeviceListValidity( | int deviceListValidity) |
uwp | Task SetDeviceListValidity( | int deviceListValidity) |
py | def SetDeviceListValidity( | deviceListValidity) |
php | function ySetDeviceListValidity( | $deviceListValidity) |
es | function SetDeviceListValidity( | deviceListValidity) |
By default, the library performs a complete enumeration every 10 seconds. To reduce network traffic it is possible to increase this delay. This is particularly useful when a YoctoHub is connected to a GSM network where the traffic is charged. This setting does not affect modules connected by USB, nor the operation of arrival/removal callbacks. Note: This function must be called after yInitAPI.
Parameters :
deviceListValidity | number of seconds between each enumeration. |
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.
Invoke the specified callback function after a given timeout.
js | function ySetTimeout( | callback, ms_timeout, args) |
es | 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.
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 |
Pauses the execution flow for a specified duration.
js | function ySleep( | ms_duration, errmsg) |
cpp | YRETCODE ySleep( | unsigned ms_duration, string& errmsg) |
m | +(YRETCODE) Sleep | :(unsigned) ms_duration :(NSError **) errmsg |
pas | function ySleep( | ms_duration: integer, var errmsg: string): integer |
vb | function ySleep( | ByVal ms_duration As Integer, |
ByRef errmsg As String) As Integer |
cs | int Sleep( | int ms_duration, ref string errmsg) |
java | int Sleep( | long ms_duration) |
uwp | Task<int> Sleep( | ulong ms_duration) |
py | def Sleep( | ms_duration, errmsg=None) |
php | function ySleep( | $ms_duration, &$errmsg) |
es | 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.
Test if the hub is reachable.
cpp | YRETCODE yTestHub( | const string& url, int mstimeout, string& errmsg) |
m | +(YRETCODE) TestHub | : (NSString*) url |
: (int) mstimeout | ||
: (NSError**) errmsg |
pas | function yTestHub( | url: string, |
mstimeout: integer, | ||
var errmsg: string): integer |
vb | function yTestHub( | ByVal url As String, |
ByVal mstimeout As Integer, | ||
ByRef errmsg As String) As Integer |
cs | int TestHub( | string url, int mstimeout, ref string errmsg) |
java | int TestHub( | String url, int mstimeout) |
uwp | Task<int> TestHub( | string url, uint mstimeout) |
py | def TestHub( | url, mstimeout, errmsg=None) |
php | function yTestHub( | $url, $mstimeout, &$errmsg) |
es | function TestHub( | url, mstimeout, errmsg) |
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.
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.
cpp | YRETCODE yTriggerHubDiscovery( | string& errmsg) |
m | +(YRETCODE) TriggerHubDiscovery | : (NSError**) errmsg |
pas | function yTriggerHubDiscovery( | var errmsg: string): integer |
vb | function yTriggerHubDiscovery( | ByRef errmsg As String) As Integer |
cs | int TriggerHubDiscovery( | ref string errmsg) |
java | int TriggerHubDiscovery( | ) |
uwp | Task<int> TriggerHubDiscovery( | ) |
py | 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.
Setup the Yoctopuce library to no more use modules connected on a previously registered machine with RegisterHub.
js | function yUnregisterHub( | url) |
cpp | void yUnregisterHub( | const string& url) |
m | +(void) UnregisterHub | :(NSString *) url |
pas | procedure yUnregisterHub( | url: string) |
vb | procedure yUnregisterHub( | ByVal url As String) |
cs | void UnregisterHub( | string url) |
java | void UnregisterHub( | String url) |
uwp | Task UnregisterHub( | string url) |
py | def UnregisterHub( | url) |
php | function yUnregisterHub( | $url) |
es | function UnregisterHub( | url) |
Parameters :
url | a string containing either "usb" or the |
Triggers a (re)detection of connected Yoctopuce modules.
js | function yUpdateDeviceList( | errmsg) |
cpp | YRETCODE yUpdateDeviceList( | string& errmsg) |
m | +(YRETCODE) UpdateDeviceList | :(NSError**) errmsg |
pas | function yUpdateDeviceList( | var errmsg: string): integer |
vb | function yUpdateDeviceList( | ByRef errmsg As String) As YRETCODE |
cs | YRETCODE UpdateDeviceList( | ref string errmsg) |
java | int UpdateDeviceList( | ) |
uwp | Task<int> UpdateDeviceList( | ) |
py | def UpdateDeviceList( | errmsg=None) |
php | function yUpdateDeviceList( | &$errmsg) |
es | 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.
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.
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 | <script type='text/javascript' src='yocto_api.js'></script> |
cpp | #include "yocto_api.h" |
m | #import "yocto_api.h" |
pas | uses yocto_api; |
vb | yocto_api.vb |
cs | yocto_api.cs |
java | import com.yoctopuce.YoctoAPI.YModule; |
uwp | import com.yoctopuce.YoctoAPI.YModule; |
py | from yocto_api import * |
php | require_once('yocto_api.php'); |
es | in HTML: <script src="../../lib/yocto_api.js"></script> in node.js: require('yoctolib-es2017/yocto_api.js'); |
Global functions |
---|
yFindModule(func) |
Allows you to find a module from its serial number or from its logical name. |
yFindModuleInContext(yctx, func) |
Retrieves a module for a given identifier in a YAPI context. |
yFirstModule() |
Starts the enumeration of modules currently accessible. |
YModule methods |
module→checkFirmware(path, onlynew) |
Tests whether the byn file is valid for this module. |
module→clearCache() |
Invalidates the cache. |
module→describe() |
Returns a descriptive text that identifies the module. |
module→download(pathname) |
Downloads the specified built-in file and returns a binary buffer with its content. |
module→functionBaseType(functionIndex) |
Retrieves the base type of the nth function on the module. |
module→functionCount() |
Returns the number of functions (beside the "module" interface) available on the module. |
module→functionId(functionIndex) |
Retrieves the hardware identifier of the nth function on the module. |
module→functionName(functionIndex) |
Retrieves the logical name of the nth function on the module. |
module→functionType(functionIndex) |
Retrieves the type of the nth function on the module. |
module→functionValue(functionIndex) |
Retrieves the advertised value of the nth function on the module. |
module→get_allSettings() |
Returns all the settings and uploaded files of the module. |
module→get_beacon() |
Returns the state of the localization beacon. |
module→get_errorMessage() |
Returns the error message of the latest error with this module object. |
module→get_errorType() |
Returns the numerical error code of the latest error with this module object. |
module→get_firmwareRelease() |
Returns the version of the firmware embedded in the module. |
module→get_functionIds(funType) |
Retrieve all hardware identifier that match the type passed in argument. |
module→get_hardwareId() |
Returns the unique hardware identifier of the module. |
module→get_icon2d() |
Returns the icon of the module. |
module→get_lastLogs() |
Returns a string with last logs of the module. |
module→get_logicalName() |
Returns the logical name of the module. |
module→get_luminosity() |
Returns the luminosity of the module informative leds (from 0 to 100). |
module→get_parentHub() |
Returns the serial number of the YoctoHub on which this module is connected. |
module→get_persistentSettings() |
Returns the current state of persistent module settings. |
module→get_productId() |
Returns the USB device identifier of the module. |
module→get_productName() |
Returns the commercial name of the module, as set by the factory. |
module→get_productRelease() |
Returns the hardware release version of the module. |
module→get_rebootCountdown() |
Returns the remaining number of seconds before the module restarts, or zero when no reboot has been scheduled. |
module→get_serialNumber() |
Returns the serial number of the module, as set by the factory. |
module→get_subDevices() |
Returns a list of all the modules that are plugged into the current module. |
module→get_upTime() |
Returns the number of milliseconds spent since the module was powered on. |
module→get_url() |
Returns the URL used to access the module. |
module→get_usbCurrent() |
Returns the current consumed by the module on the USB bus, in milli-amps. |
module→get_userData() |
Returns the value of the userData attribute, as previously stored using method set_userData. |
module→get_userVar() |
Returns the value previously stored in this attribute. |
module→hasFunction(funcId) |
Tests if the device includes a specific function. |
module→isOnline() |
Checks if the module is currently reachable, without raising any error. |
module→isOnline_async(callback, context) |
Checks if the module is currently reachable, without raising any error. |
module→load(msValidity) |
Preloads the module cache with a specified validity duration. |
module→load_async(msValidity, callback, context) |
Preloads the module cache with a specified validity duration (asynchronous version). |
module→log(text) |
Adds a text message to the device logs. |
module→nextModule() |
Continues the module enumeration started using yFirstModule(). |
module→reboot(secBeforeReboot) |
Schedules a simple module reboot after the given number of seconds. |
module→registerBeaconCallback(callback) |
Register a callback function, to be called when the localization beacon of the module has been changed. |
module→registerConfigChangeCallback(callback) |
Register a callback function, to be called when a persistent settings in a device configuration has been changed (e.g. |
module→registerLogCallback(callback) |
Registers a device log callback function. |
module→revertFromFlash() |
Reloads the settings stored in the nonvolatile memory, as when the module is powered on. |
module→saveToFlash() |
Saves current settings in the nonvolatile memory of the module. |
module→set_allSettings(settings) |
Restores all the settings of the device. |
module→set_allSettingsAndFiles(settings) |
Restores all the settings and uploaded files to the module. |
module→set_beacon(newval) |
Turns on or off the module localization beacon. |
module→set_logicalName(newval) |
Changes the logical name of the module. |
module→set_luminosity(newval) |
Changes the luminosity of the module informative leds. |
module→set_userData(data) |
Stores a user context provided as argument in the userData attribute of the function. |
module→set_userVar(newval) |
Stores a 32 bit value in the device RAM. |
module→triggerConfigChangeCallback() |
Triggers a configuration change callback, to check if they are supported or not. |
module→triggerFirmwareUpdate(secBeforeReboot) |
Schedules a module reboot into special firmware update mode. |
module→updateFirmware(path) |
Prepares a firmware update of the module. |
module→updateFirmwareEx(path, force) |
Prepares a firmware update of the module. |
module→wait_async(callback, context) |
Waits for all pending asynchronous commands on the module to complete, and invoke the user-provided callback function. |
Allows you to find a module from its serial number or from its logical name.
js | function yFindModule( | func) |
cpp | YModule* yFindModule( | string func) |
m | +(YModule*) FindModule | : (NSString*) func |
pas | function yFindModule( | func: string): TYModule |
vb | function yFindModule( | ByVal func As String) As YModule |
cs | YModule FindModule( | string func) |
java | YModule FindModule( | String func) |
uwp | YModule FindModule( | string func) |
py | def FindModule( | func) |
php | function yFindModule( | $func) |
es | 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.
Retrieves a module for a given identifier in a YAPI context.
java | YModule FindModuleInContext( | YAPIContext yctx, String func) |
uwp | YModule FindModuleInContext( | YAPIContext yctx, string func) |
es | function FindModuleInContext( | yctx, func) |
The identifier can be specified using several formats:
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.
Starts the enumeration of modules currently accessible.
js | function yFirstModule( | ) |
cpp | YModule* yFirstModule( | ) |
m | +(YModule*) FirstModule |
pas | function yFirstModule( | ): TYModule |
vb | function yFirstModule( | ) As YModule |
cs | YModule FirstModule( | ) |
java | YModule FirstModule( | ) |
uwp | YModule FirstModule( | ) |
py | def FirstModule( | ) |
php | function yFirstModule( | ) |
es | function FirstModule( | ) |
Use the method YModule.nextModule() to iterate on the next modules.
Returns :
a pointer to a YModule object, corresponding to the first module currently online, or a null pointer if there are none.
Tests whether the byn file is valid for this module.
js | function checkFirmware( | path, onlynew) |
cpp | string checkFirmware( | string path, bool onlynew) |
m | -(NSString*) checkFirmware | : (NSString*) path |
: (bool) onlynew |
pas | function checkFirmware( | path: string, onlynew: boolean): string |
vb | function checkFirmware( | ) As String |
cs | string checkFirmware( | string path, bool onlynew) |
java | String checkFirmware( | String path, boolean onlynew) |
uwp | Task<string> checkFirmware( | string path, bool onlynew) |
py | def checkFirmware( | path, onlynew) |
php | function checkFirmware( | $path, $onlynew) |
es | function checkFirmware( | path, onlynew) |
cmd | 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:".
Invalidates the cache.
js | function clearCache( | ) |
cpp | void clearCache( | ) |
m | -(void) clearCache |
pas | procedure clearCache( | ) |
vb | procedure clearCache( | ) |
cs | void clearCache( | ) |
java | void clearCache( | ) |
py | def clearCache( | ) |
php | function clearCache( | ) |
es | 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.
Returns a descriptive text that identifies the module.
js | function describe( | ) |
cpp | string describe( | ) |
m | -(NSString*) describe |
pas | function describe( | ): string |
vb | function describe( | ) As String |
cs | string describe( | ) |
java | String describe( | ) |
py | def describe( | ) |
php | function describe( | ) |
es | function describe( | ) |
The text may include either the logical name or the serial number of the module.
Returns :
a string that describes the module
Downloads the specified built-in file and returns a binary buffer with its content.
js | function download( | pathname) |
cpp | string download( | string pathname) |
m | -(NSMutableData*) download | : (NSString*) pathname |
pas | function download( | pathname: string): TByteArray |
vb | function download( | ) As Byte |
cs | byte[] download( | string pathname) |
java | byte[] download( | String pathname) |
uwp | Task<byte[]> download( | string pathname) |
py | def download( | pathname) |
php | function download( | $pathname) |
es | function download( | pathname) |
cmd | 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.
Retrieves the base type of the nth function on the module.
js | function functionBaseType( | functionIndex) |
cpp | string functionBaseType( | int functionIndex) |
pas | function functionBaseType( | functionIndex: integer): string |
vb | function functionBaseType( | ByVal functionIndex As Integer) As String |
cs | string functionBaseType( | int functionIndex) |
java | String functionBaseType( | int functionIndex) |
py | def functionBaseType( | functionIndex) |
php | function functionBaseType( | $functionIndex) |
es | function functionBaseType( | functionIndex) |
For instance, the base type of all measuring functions is "Sensor".
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.
Returns the number of functions (beside the "module" interface) available on the module.
js | function functionCount( | ) |
cpp | int functionCount( | ) |
m | -(int) functionCount |
pas | function functionCount( | ): integer |
vb | function functionCount( | ) As Integer |
cs | int functionCount( | ) |
java | int functionCount( | ) |
py | def functionCount( | ) |
php | function functionCount( | ) |
es | function functionCount( | ) |
Returns :
the number of functions on the module
On failure, throws an exception or returns a negative error code.
Retrieves the hardware identifier of the nth function on the module.
js | function functionId( | functionIndex) |
cpp | string functionId( | int functionIndex) |
m | -(NSString*) functionId | : (int) functionIndex |
pas | function functionId( | functionIndex: integer): string |
vb | function functionId( | ByVal functionIndex As Integer) As String |
cs | string functionId( | int functionIndex) |
java | String functionId( | int functionIndex) |
py | def functionId( | functionIndex) |
php | function functionId( | $functionIndex) |
es | function functionId( | functionIndex) |
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.
Retrieves the logical name of the nth function on the module.
js | function functionName( | functionIndex) |
cpp | string functionName( | int functionIndex) |
m | -(NSString*) functionName | : (int) functionIndex |
pas | function functionName( | functionIndex: integer): string |
vb | function functionName( | ByVal functionIndex As Integer) As String |
cs | string functionName( | int functionIndex) |
java | String functionName( | int functionIndex) |
py | def functionName( | functionIndex) |
php | function functionName( | $functionIndex) |
es | function functionName( | functionIndex) |
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.
Retrieves the type of the nth function on the module.
js | function functionType( | functionIndex) |
cpp | string functionType( | int functionIndex) |
pas | function functionType( | functionIndex: integer): string |
vb | function functionType( | ByVal functionIndex As Integer) As String |
cs | string functionType( | int functionIndex) |
java | String functionType( | int functionIndex) |
py | def functionType( | functionIndex) |
php | function functionType( | $functionIndex) |
es | function functionType( | functionIndex) |
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.
Retrieves the advertised value of the nth function on the module.
js | function functionValue( | functionIndex) |
cpp | string functionValue( | int functionIndex) |
m | -(NSString*) functionValue | : (int) functionIndex |
pas | function functionValue( | functionIndex: integer): string |
vb | function functionValue( | ByVal functionIndex As Integer) As String |
cs | string functionValue( | int functionIndex) |
java | String functionValue( | int functionIndex) |
py | def functionValue( | functionIndex) |
php | function functionValue( | $functionIndex) |
es | function functionValue( | functionIndex) |
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.
Returns all the settings and uploaded files of the module.
js | function get_allSettings( | ) |
cpp | string get_allSettings( | ) |
m | -(NSMutableData*) allSettings |
pas | function get_allSettings( | ): TByteArray |
vb | function get_allSettings( | ) As Byte |
cs | byte[] get_allSettings( | ) |
java | byte[] get_allSettings( | ) |
uwp | Task<byte[]> get_allSettings( | ) |
py | def get_allSettings( | ) |
php | function get_allSettings( | ) |
es | function get_allSettings( | ) |
cmd | 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.
Returns the state of the localization beacon.
js | function get_beacon( | ) |
cpp | Y_BEACON_enum get_beacon( | ) |
m | -(Y_BEACON_enum) beacon |
pas | function get_beacon( | ): Integer |
vb | function get_beacon( | ) As Integer |
cs | int get_beacon( | ) |
java | int get_beacon( | ) |
uwp | Task<int> get_beacon( | ) |
py | def get_beacon( | ) |
php | function get_beacon( | ) |
es | function get_beacon( | ) |
cmd | 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.
Returns the error message of the latest error with this module object.
js | function get_errorMessage( | ) |
cpp | string get_errorMessage( | ) |
m | -(NSString*) errorMessage |
pas | function get_errorMessage( | ): string |
vb | function get_errorMessage( | ) As String |
cs | string get_errorMessage( | ) |
java | String get_errorMessage( | ) |
py | def get_errorMessage( | ) |
php | function get_errorMessage( | ) |
es | 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 this module object
Returns the numerical error code of the latest error with this module object.
js | function get_errorType( | ) |
cpp | YRETCODE get_errorType( | ) |
pas | function get_errorType( | ): YRETCODE |
vb | function get_errorType( | ) As YRETCODE |
cs | YRETCODE get_errorType( | ) |
java | int get_errorType( | ) |
py | def get_errorType( | ) |
php | function get_errorType( | ) |
es | 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 this module object
Returns the version of the firmware embedded in the module.
js | function get_firmwareRelease( | ) |
cpp | string get_firmwareRelease( | ) |
m | -(NSString*) firmwareRelease |
pas | function get_firmwareRelease( | ): string |
vb | function get_firmwareRelease( | ) As String |
cs | string get_firmwareRelease( | ) |
java | String get_firmwareRelease( | ) |
uwp | Task<string> get_firmwareRelease( | ) |
py | def get_firmwareRelease( | ) |
php | function get_firmwareRelease( | ) |
es | function get_firmwareRelease( | ) |
cmd | 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.
Retrieve all hardware identifier that match the type passed in argument.
js | function get_functionIds( | funType) |
cpp | vector<string> get_functionIds( | string funType) |
m | -(NSMutableArray*) functionIds | : (NSString*) funType |
pas | function get_functionIds( | funType: string): TStringArray |
vb | function get_functionIds( | ) As List |
cs | List<string> get_functionIds( | string funType) |
java | ArrayList<String> get_functionIds( | String funType) |
uwp | Task<List<string>> get_functionIds( | string funType) |
py | def get_functionIds( | funType) |
php | function get_functionIds( | $funType) |
es | function get_functionIds( | funType) |
cmd | YModule target get_functionIds | funType |
Parameters :
funType | The type of function (Relay, LightSensor, Voltage,...) |
Returns :
an array of strings.
Returns the unique hardware identifier of the module.
js | function get_hardwareId( | ) |
cpp | string get_hardwareId( | ) |
m | -(NSString*) hardwareId |
vb | function get_hardwareId( | ) As String |
cs | string get_hardwareId( | ) |
java | String get_hardwareId( | ) |
py | def get_hardwareId( | ) |
php | function get_hardwareId( | ) |
es | 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
Returns the icon of the module.
js | function get_icon2d( | ) |
cpp | string get_icon2d( | ) |
m | -(NSMutableData*) icon2d |
pas | function get_icon2d( | ): TByteArray |
vb | function get_icon2d( | ) As Byte |
cs | byte[] get_icon2d( | ) |
java | byte[] get_icon2d( | ) |
uwp | Task<byte[]> get_icon2d( | ) |
py | def get_icon2d( | ) |
php | function get_icon2d( | ) |
es | function get_icon2d( | ) |
cmd | YModule target get_icon2d |
The icon is a PNG image and does not exceeds 1536 bytes.
Returns :
a binary buffer with module icon, in png format. On failure, throws an exception or returns YAPI_INVALID_STRING.
Returns a string with last logs of the module.
js | function get_lastLogs( | ) |
cpp | string get_lastLogs( | ) |
m | -(NSString*) lastLogs |
pas | function get_lastLogs( | ): string |
vb | function get_lastLogs( | ) As String |
cs | string get_lastLogs( | ) |
java | String get_lastLogs( | ) |
uwp | Task<string> get_lastLogs( | ) |
py | def get_lastLogs( | ) |
php | function get_lastLogs( | ) |
es | function get_lastLogs( | ) |
cmd | YModule target get_lastLogs |
This method return only logs that are still in the module.
Returns :
a string with last logs of the module. On failure, throws an exception or returns YAPI_INVALID_STRING.
Returns the logical name of the module.
js | function get_logicalName( | ) |
cpp | string get_logicalName( | ) |
m | -(NSString*) logicalName |
pas | function get_logicalName( | ): string |
vb | function get_logicalName( | ) As String |
cs | string get_logicalName( | ) |
java | String get_logicalName( | ) |
uwp | Task<string> get_logicalName( | ) |
py | def get_logicalName( | ) |
php | function get_logicalName( | ) |
es | function get_logicalName( | ) |
cmd | 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.
Returns the luminosity of the module informative leds (from 0 to 100).
js | function get_luminosity( | ) |
cpp | int get_luminosity( | ) |
m | -(int) luminosity |
pas | function get_luminosity( | ): LongInt |
vb | function get_luminosity( | ) As Integer |
cs | int get_luminosity( | ) |
java | int get_luminosity( | ) |
uwp | Task<int> get_luminosity( | ) |
py | def get_luminosity( | ) |
php | function get_luminosity( | ) |
es | function get_luminosity( | ) |
cmd | 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.
Returns the serial number of the YoctoHub on which this module is connected.
js | function get_parentHub( | ) |
cpp | string get_parentHub( | ) |
m | -(NSString*) parentHub |
pas | function get_parentHub( | ): string |
vb | function get_parentHub( | ) As String |
cs | string get_parentHub( | ) |
java | String get_parentHub( | ) |
uwp | Task<string> get_parentHub( | ) |
py | def get_parentHub( | ) |
php | function get_parentHub( | ) |
es | function get_parentHub( | ) |
cmd | 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
Returns the current state of persistent module settings.
js | function get_persistentSettings( | ) |
cpp | Y_PERSISTENTSETTINGS_enum get_persistentSettings( | ) |
m | -(Y_PERSISTENTSETTINGS_enum) persistentSettings |
pas | function get_persistentSettings( | ): Integer |
vb | function get_persistentSettings( | ) As Integer |
cs | int get_persistentSettings( | ) |
java | int get_persistentSettings( | ) |
uwp | Task<int> get_persistentSettings( | ) |
py | def get_persistentSettings( | ) |
php | function get_persistentSettings( | ) |
es | function get_persistentSettings( | ) |
cmd | YModule target get_persistentSettings |
Returns :
a value among Y_PERSISTENTSETTINGS_LOADED, Y_PERSISTENTSETTINGS_SAVED and Y_PERSISTENTSETTINGS_MODIFIED corresponding to the current state of persistent module settings
On failure, throws an exception or returns Y_PERSISTENTSETTINGS_INVALID.
Returns the USB device identifier of the module.
js | function get_productId( | ) |
cpp | int get_productId( | ) |
m | -(int) productId |
pas | function get_productId( | ): LongInt |
vb | function get_productId( | ) As Integer |
cs | int get_productId( | ) |
java | int get_productId( | ) |
uwp | Task<int> get_productId( | ) |
py | def get_productId( | ) |
php | function get_productId( | ) |
es | function get_productId( | ) |
cmd | 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.
Returns the commercial name of the module, as set by the factory.
js | function get_productName( | ) |
cpp | string get_productName( | ) |
m | -(NSString*) productName |
pas | function get_productName( | ): string |
vb | function get_productName( | ) As String |
cs | string get_productName( | ) |
java | String get_productName( | ) |
uwp | Task<string> get_productName( | ) |
py | def get_productName( | ) |
php | function get_productName( | ) |
es | function get_productName( | ) |
cmd | 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.
Returns the hardware release version of the module.
js | function get_productRelease( | ) |
cpp | int get_productRelease( | ) |
m | -(int) productRelease |
pas | function get_productRelease( | ): LongInt |
vb | function get_productRelease( | ) As Integer |
cs | int get_productRelease( | ) |
java | int get_productRelease( | ) |
uwp | Task<int> get_productRelease( | ) |
py | def get_productRelease( | ) |
php | function get_productRelease( | ) |
es | function get_productRelease( | ) |
cmd | 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.
Returns the remaining number of seconds before the module restarts, or zero when no reboot has been scheduled.
js | function get_rebootCountdown( | ) |
cpp | int get_rebootCountdown( | ) |
m | -(int) rebootCountdown |
pas | function get_rebootCountdown( | ): LongInt |
vb | function get_rebootCountdown( | ) As Integer |
cs | int get_rebootCountdown( | ) |
java | int get_rebootCountdown( | ) |
uwp | Task<int> get_rebootCountdown( | ) |
py | def get_rebootCountdown( | ) |
php | function get_rebootCountdown( | ) |
es | function get_rebootCountdown( | ) |
cmd | 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.
Returns the serial number of the module, as set by the factory.
js | function get_serialNumber( | ) |
cpp | string get_serialNumber( | ) |
m | -(NSString*) serialNumber |
pas | function get_serialNumber( | ): string |
vb | function get_serialNumber( | ) As String |
cs | string get_serialNumber( | ) |
java | String get_serialNumber( | ) |
uwp | Task<string> get_serialNumber( | ) |
py | def get_serialNumber( | ) |
php | function get_serialNumber( | ) |
es | function get_serialNumber( | ) |
cmd | 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.
Returns a list of all the modules that are plugged into the current module.
js | function get_subDevices( | ) |
cpp | vector<string> get_subDevices( | ) |
m | -(NSMutableArray*) subDevices |
pas | function get_subDevices( | ): TStringArray |
vb | function get_subDevices( | ) As List |
cs | List<string> get_subDevices( | ) |
java | ArrayList<String> get_subDevices( | ) |
uwp | Task<List<string>> get_subDevices( | ) |
py | def get_subDevices( | ) |
php | function get_subDevices( | ) |
es | function get_subDevices( | ) |
cmd | 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.
Returns the number of milliseconds spent since the module was powered on.
js | function get_upTime( | ) |
cpp | s64 get_upTime( | ) |
m | -(s64) upTime |
pas | function get_upTime( | ): int64 |
vb | function get_upTime( | ) As Long |
cs | long get_upTime( | ) |
java | long get_upTime( | ) |
uwp | Task<long> get_upTime( | ) |
py | def get_upTime( | ) |
php | function get_upTime( | ) |
es | function get_upTime( | ) |
cmd | 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.
Returns the URL used to access the module.
js | function get_url( | ) |
cpp | string get_url( | ) |
m | -(NSString*) url |
pas | function get_url( | ): string |
vb | function get_url( | ) As String |
cs | string get_url( | ) |
java | String get_url( | ) |
uwp | Task<string> get_url( | ) |
py | def get_url( | ) |
php | function get_url( | ) |
es | function get_url( | ) |
cmd | 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.
Returns the current consumed by the module on the USB bus, in milli-amps.
js | function get_usbCurrent( | ) |
cpp | int get_usbCurrent( | ) |
m | -(int) usbCurrent |
pas | function get_usbCurrent( | ): LongInt |
vb | function get_usbCurrent( | ) As Integer |
cs | int get_usbCurrent( | ) |
java | int get_usbCurrent( | ) |
uwp | Task<int> get_usbCurrent( | ) |
py | def get_usbCurrent( | ) |
php | function get_usbCurrent( | ) |
es | function get_usbCurrent( | ) |
cmd | 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.
Returns the value of the userData attribute, as previously stored using method set_userData.
js | function get_userData( | ) |
cpp | void * get_userData( | ) |
m | -(id) userData |
pas | function get_userData( | ): Tobject |
vb | function get_userData( | ) As Object |
cs | object get_userData( | ) |
java | Object get_userData( | ) |
py | def get_userData( | ) |
php | function get_userData( | ) |
es | 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.
Returns the value previously stored in this attribute.
js | function get_userVar( | ) |
cpp | int get_userVar( | ) |
m | -(int) userVar |
pas | function get_userVar( | ): LongInt |
vb | function get_userVar( | ) As Integer |
cs | int get_userVar( | ) |
java | int get_userVar( | ) |
uwp | Task<int> get_userVar( | ) |
py | def get_userVar( | ) |
php | function get_userVar( | ) |
es | function get_userVar( | ) |
cmd | 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.
Tests if the device includes a specific function.
js | function hasFunction( | funcId) |
cpp | bool hasFunction( | string funcId) |
m | -(bool) hasFunction | : (NSString*) funcId |
pas | function hasFunction( | funcId: string): boolean |
vb | function hasFunction( | ) As Boolean |
cs | bool hasFunction( | string funcId) |
java | boolean hasFunction( | String funcId) |
uwp | Task<bool> hasFunction( | string funcId) |
py | def hasFunction( | funcId) |
php | function hasFunction( | $funcId) |
es | function hasFunction( | funcId) |
cmd | 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
Checks if the module is currently reachable, without raising any error.
js | function isOnline( | ) |
cpp | bool isOnline( | ) |
m | -(BOOL) isOnline |
pas | function isOnline( | ): boolean |
vb | function isOnline( | ) As Boolean |
cs | bool isOnline( | ) |
java | boolean isOnline( | ) |
py | def isOnline( | ) |
php | function isOnline( | ) |
es | 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
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.
Preloads the module cache with a specified validity duration.
js | function load( | msValidity) |
cpp | YRETCODE load( | int msValidity) |
m | -(YRETCODE) load | : (u64) msValidity |
pas | function load( | msValidity: u64): YRETCODE |
vb | function load( | ByVal msValidity As Long) As YRETCODE |
cs | YRETCODE load( | ulong msValidity) |
java | int load( | long msValidity) |
py | def load( | msValidity) |
php | function load( | $msValidity) |
es | 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.
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.
Adds a text message to the device logs.
js | function log( | text) |
cpp | int log( | string text) |
m | -(int) log | : (NSString*) text |
pas | function log( | text: string): LongInt |
vb | function log( | ) As Integer |
cs | int log( | string text) |
java | int log( | String text) |
uwp | Task<int> log( | string text) |
py | def log( | text) |
php | function log( | $text) |
es | function log( | text) |
cmd | 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.
Continues the module enumeration started using yFirstModule().
js | function nextModule( | ) |
cpp | YModule * nextModule( | ) |
m | -(YModule*) nextModule |
pas | function nextModule( | ): TYModule |
vb | function nextModule( | ) As YModule |
cs | YModule nextModule( | ) |
java | YModule nextModule( | ) |
uwp | YModule nextModule( | ) |
py | def nextModule( | ) |
php | function nextModule( | ) |
es | function nextModule( | ) |
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.
Schedules a simple module reboot after the given number of seconds.
js | function reboot( | secBeforeReboot) |
cpp | int reboot( | int secBeforeReboot) |
m | -(int) reboot | : (int) secBeforeReboot |
pas | function reboot( | secBeforeReboot: LongInt): LongInt |
vb | function reboot( | ) As Integer |
cs | int reboot( | int secBeforeReboot) |
java | int reboot( | int secBeforeReboot) |
uwp | Task<int> reboot( | int secBeforeReboot) |
py | def reboot( | secBeforeReboot) |
php | function reboot( | $secBeforeReboot) |
es | function reboot( | secBeforeReboot) |
cmd | 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.
Register a callback function, to be called when the localization beacon of the module has been changed.
js | function registerBeaconCallback( | callback) |
cpp | int registerBeaconCallback( | YModuleBeaconCallback callback) |
m | -(int) registerBeaconCallback | : (YModuleBeaconCallback) callback |
pas | function registerBeaconCallback( | callback: TYModuleBeaconCallback): LongInt |
vb | function registerBeaconCallback( | ) As Integer |
cs | int registerBeaconCallback( | BeaconCallback callback) |
java | int registerBeaconCallback( | BeaconCallback callback) |
uwp | Task<int> registerBeaconCallback( | BeaconCallback callback) |
py | def registerBeaconCallback( | callback) |
php | function registerBeaconCallback( | $callback) |
es | function registerBeaconCallback( | callback) |
The callback function should take two arguments: the YModule object of which the beacon has changed, and an integer describing the new beacon state.
Parameters :
callback | The callback function to call, or null to unregister a |
Register a callback function, to be called when a persistent settings in a device configuration has been changed (e.g.
js | function registerConfigChangeCallback( | callback) |
cpp | int registerConfigChangeCallback( | YModuleConfigChangeCallback callback) |
m | -(int) registerConfigChangeCallback | : (YModuleConfigChangeCallback) callback |
pas | function registerConfigChangeCallback( | callback: TYModuleConfigChangeCallback): LongInt |
vb | function registerConfigChangeCallback( | ) As Integer |
cs | int registerConfigChangeCallback( | ConfigChangeCallback callback) |
java | int registerConfigChangeCallback( | ConfigChangeCallback callback) |
uwp | Task<int> registerConfigChangeCallback( | ConfigChangeCallback callback) |
py | def registerConfigChangeCallback( | callback) |
php | function registerConfigChangeCallback( | $callback) |
es | function registerConfigChangeCallback( | callback) |
change of unit, etc).
Parameters :
callback | a procedure taking a YModule parameter, or null |
Registers a device log callback function.
cpp | void registerLogCallback( | YModuleLogCallback callback) |
m | -(void) registerLogCallback | : (YModuleLogCallback) callback |
vb | function registerLogCallback( | ByVal callback As YModuleLogCallback) As Integer |
cs | int registerLogCallback( | LogCallback callback) |
java | void registerLogCallback( | LogCallback callback) |
py | 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. |
Reloads the settings stored in the nonvolatile memory, as when the module is powered on.
js | function revertFromFlash( | ) |
cpp | int revertFromFlash( | ) |
m | -(int) revertFromFlash |
pas | function revertFromFlash( | ): LongInt |
vb | function revertFromFlash( | ) As Integer |
cs | int revertFromFlash( | ) |
java | int revertFromFlash( | ) |
uwp | Task<int> revertFromFlash( | ) |
py | def revertFromFlash( | ) |
php | function revertFromFlash( | ) |
es | function revertFromFlash( | ) |
cmd | YModule target revertFromFlash |
Returns :
YAPI_SUCCESS when the call succeeds.
On failure, throws an exception or returns a negative error code.
Saves current settings in the nonvolatile memory of the module.
js | function saveToFlash( | ) |
cpp | int saveToFlash( | ) |
m | -(int) saveToFlash |
pas | function saveToFlash( | ): LongInt |
vb | function saveToFlash( | ) As Integer |
cs | int saveToFlash( | ) |
java | int saveToFlash( | ) |
uwp | Task<int> saveToFlash( | ) |
py | def saveToFlash( | ) |
php | function saveToFlash( | ) |
es | function saveToFlash( | ) |
cmd | 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.
Restores all the settings of the device.
js | function set_allSettings( | settings) |
cpp | int set_allSettings( | string settings) |
m | -(int) setAllSettings | : (NSData*) settings |
pas | function set_allSettings( | settings: TByteArray): LongInt |
vb | procedure set_allSettings( | ) |
cs | int set_allSettings( | ) |
java | int set_allSettings( | byte[] settings) |
uwp | Task<int> set_allSettings( | ) |
py | def set_allSettings( | settings) |
php | function set_allSettings( | $settings) |
es | function set_allSettings( | settings) |
cmd | 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.
Restores all the settings and uploaded files to the module.
js | function set_allSettingsAndFiles( | settings) |
cpp | int set_allSettingsAndFiles( | string settings) |
m | -(int) setAllSettingsAndFiles | : (NSData*) settings |
pas | function set_allSettingsAndFiles( | settings: TByteArray): LongInt |
vb | procedure set_allSettingsAndFiles( | ) |
cs | int set_allSettingsAndFiles( | ) |
java | int set_allSettingsAndFiles( | byte[] settings) |
uwp | Task<int> set_allSettingsAndFiles( | ) |
py | def set_allSettingsAndFiles( | settings) |