Index 561 .............................................................................................................................................
1. Introduction
The Yocto-GPS module is a 60x20mm module equipped with a GNSS (GPS + GLONASS) receiver
which enables you to know the position of the receiver, its travel speed, and the current time. It
requires the use of an active external antenna with a connector at the U.FL standard.
The Yocto-GPS module
Yoctopuce thanks you for buying this Yocto-GPS 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-GPS is easy to
install anywhere and easy to drive from a maximum of programming languages. If you are
nevertheless disappointed with this module, do not hesitate to contact Yoctopuce support1.
By design, all Yoctopuce modules are driven the same way. Therefore, user's guides for all the
modules of the range are very similar. If you have already carefully read through the user's guide of
another Yoctopuce module, you can jump directly to the description of the module functions.
1.1. Prerequisites
In order to use your Yocto-GPS module, you should have the following items at hand.
A computer
Yoctopuce modules are intended to be driven by a computer (or possibly an embedded
microprocessor). You will write the control software yourself, according to your needs, using the
information provided in this manual.
Yoctopuce provides software libraries to drive its modules for the following operating systems:
Windows, Mac OS X, Linux, and Android. Yoctopuce modules do not require installing any specific
system driver, as they leverage the standard HID driver2 provided with every operating system.
1
support@yoctopuce.com
www.yoctopuce.com1
Windows versions currently supported are: Windows XP, Windows 2003, Windows Vista, Windows
7, Windows 8 and Windows 10. Both 32 bit and 64 bit versions are supported. Yoctopuce is
frequently testing its modules on Windows 7 and Windows 10.
Mac OS X versions currently supported are: 10.9 (Maverick), 10.10 (Yosemite), 10.11 (El Capitan)
and 10.12 (Sierra). Yoctopuce is frequently testing its modules on Mac OS X 10.11.
Linux kernels currently supported are the 2.6 branch, the 3.0 branch and the 4.0 branch. Other
versions of the Linux kernel, and even other UNIX variants, are very likely to work as well, as Linux
support is implemented through the standard libusb API. Yoctopuce is frequently testing its modules
on Linux kernel 3.19.
Android versions currently supported are: Android 3.1 and later. Moreover, it is necessary for the
tablet or phone to support the Host USB mode. Yoctopuce is frequently testing its modules on
Android 4.x on a Nexus 7 and a Samsung Galaxy S3 with the Java for Android library.
A USB cable, type A-micro B
USB connectors exist in three sizes: the "standard" size that you probably use to connect your
printer, the very common mini size to connect small devices, and finally the micro size often used to
connect mobile phones, as long as they do not exhibit an apple logo. All USB modules manufactured
by Yoctopuce use micro size connectors.
The most common USB 2 connectors: A, B, Mini B, Micro A, Micro B.
3
To connect your Yocto-GPS module to a computer, you need a USB cable of type A-micro B. The
price of this cable may vary a lot depending on the source, look for it under the name USB A to micro B Data cable. Make sure not to buy a simple USB charging cable without data connectivity. The
correct type of cable is available on the Yoctopuce shop.
You must plug in your Yocto-GPS module with a USB cable of type A - micro B.
If you insert a USB hub between the computer and the Yocto-GPS module, make sure to take into
account the USB current limits. If you do not, be prepared to face unstable behaviors and
unpredictable failures. You can find more details on this topic in the chapter about assembly and
connections.
3
Although they existed for some time, Mini A connectors are not available anymore http://www.usb.org/developers/
Deprecation_Announcement_052507.pdf
1. Introduction
2www.yoctopuce.com
1.2. Optional accessories
The accessories below are not necessary to use the Yocto-GPS module but might be useful
depending on your project. These are mostly common products that you can buy from your favorite
hacking store. To save you the tedious job of looking for them, most of them are also available on the
Yoctopuce shop.
Screws and spacers
In order to mount the Yocto-GPS module, you can put small screws in the 2.5mm assembly holes,
with a screw head no larger than 4.5mm. The best way is to use threaded spacers, which you can
then mount wherever you want. You can find more details on this topic in the chapter about
assembly and connections.
Micro-USB hub
If you intend to put several Yoctopuce modules 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.
YoctoHub-Ethernet, YoctoHub-Wireless and YoctoHub-GSM
You can add network connectivity to your Yocto-GPS, 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.
Enclosures
Your Yocto-GPS 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 4. The suggested enclosure model for your Yocto-GPS is the
YoctoBox-Long-Thick-Transp.
You can install your Yocto-GPS in an optional enclosure
1: Micro-B USB socket 3: Yocto-led
2: Yocto-button4: Satellite reception led
5: Antenna connector
2.1. Common elements
All Yocto-modules share a number of common functionalities.
USB connector
Yoctopuce modules all come with a micro-B USB socket. The corresponding cables are not the most
common, but the sockets are the smallest available.
Warning: the USB connector is simply soldered in surface and can be pulled out if the USB plug acts
as a lever. In this case, if the tracks stayed in position, the connector can be soldered back with a
good iron and using flux to avoid bridges. Alternatively, you can solder a USB cable directly in the
1.27mm-spaced holes near the connector.
Yocto-button
The Yocto-button has two functionalities. First, it can activate the Yocto-beacon mode (see below
under Yocto-led). Second, if you plug in a Yocto-module while keeping this button pressed, you can
then reprogram its firmware with a new version. Note that there is a simpler UI-based method to
update the firmware, but this one works even in case of severely damaged firmware.
www.yoctopuce.com5
Yocto-led
Normally, the Yocto-led is used to indicate that the module is working smoothly. The Yocto-led then
emits a low blue light which varies slowly, mimicking breathing. The Yocto-led stops breathing when
the module is not communicating any more, as for instance when powered by a USB hub which is
disconnected from any active computer.
When you press the Yocto-button, the Yocto-led switches to Yocto-beacon mode. It starts flashing
faster with a stronger light, in order to facilitate the localization of a module when you have several
identical ones. It is indeed possible to trigger off the Yocto-beacon by software, as it is possible to
detect by software that a Yocto-beacon is on.
The Yocto-led has a third functionality, which is less pleasant: when the internal software which
controls the module encounters a fatal error, the Yocto-led starts emitting an SOS in morse 1. If this
happens, unplug and re-plug the module. If it happens again, check that the module contains the
latest version of the firmware, and, if it is the case, contact Yoctopuce support2.
Current sensor
Each Yocto-module is able to measure its own current consumption on the USB bus. Current supply
on a USB bus being quite critical, this functionality can be of great help. You can only view the
current consumption of a module by software.
Serial number
Each Yocto-module has a unique serial number assigned to it at the factory. For Yocto-GPS
modules, this number starts with YGNSSMK1. The module can be software driven using this serial
number. The serial number cannot be modified.
Logical name
The logical name is similar to the serial number: it is a supposedly unique character string which
allows you to reference your module by software. However, in the opposite of the serial number, the
logical name can be modified at will. The benefit is to enable you to build several copies of the same
project without needing to modify the driving software. You only need to program the same logical
name in each copy. Warning: the behavior of a project becomes unpredictable when it contains
several modules with the same logical name and when the driving software tries to access one of
these modules through its logical name. When leaving the factory, modules do not have an assigned
logical name. It is yours to define.
2.2. Specific elements
The receiver
The Yocto-GPS is based on a GNSS SL869 receiver produced by Telit. It has 32 channels and can
compute up to 10 positions per second.
Satellite reception led
The green led (Fix Sat.) on the module indicates the state of the satellite reception. It stays on when
the reception is satisfactory. It blinks fast when the module searches for satellites. With an
appropriate reception, the Yocto-GPS can obtain a position in less than 35 seconds after a cold start.
Moreover, the Yocto-GPS has a small battery enabling the GPS to remember during several hours
the position of the last seen satellites, enabling a hot start in a few seconds only in most cases. In
case of a particularly degraded satellite reception, obtaining a first position can take up to 5 minutes.
The antenna connector
The Yocto-GPS needs an antenna to work. To maximize reception quality, the Yocto-GPS is
designed to work with an active external antenna (powered seamlessly in 3.3V), connected with a
U.FL connector. Beware, U.FL connectors are not designed to be connected/disconnected
continuously. If you plan such a scenario, use a small U.FL to SMA (female) cable and an antenna
equipped with an SMA connector.
Being active, you can deport the antenna several meters away without changing the quality of the
reception signal.
Use an SMA connector if you plan to frequently disconnect the antenna.
2. Presentation
www.yoctopuce.com7
8www.yoctopuce.com
3. First steps
When reading this chapter, your Yocto-GPS 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 software1. 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 browser2. 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.
3.1. Localization
You can then physically localize each of the displayed modules by clicking on the beacon button.
This puts the Yocto-led of the corresponding module in Yocto-beacon mode. It starts flashing, which
allows you to easily localize it. The second effect is to display a little blue circle on the screen. You
obtain the same behavior when pressing the Yocto-button of the module.
3.2. Test of the module
The first item to check is that your module is working well: click on the serial number corresponding
to your module. This displays a window summarizing the properties of your Yocto-GPS.
1
www.yoctopuce.com/EN/virtualhub.php
2
The interface is tested on Chrome, FireFox, Safari, Edge et IE 11.
www.yoctopuce.com9
Properties of the Yocto-GPS module.
This window allows you, among other things, to play with you module to check how it is working.
Position values computed by the Yocto-GPS are displayed there in real time.
3.3. Configuration
When, in the module list, you click on the configure button corresponding to your module, the
configuration window is displayed.
Yocto-GPS module configuration.
Firmware
The module firmware can easily be updated with the help of the interface. To do so, you must
beforehand have the adequate firmware on your local disk. Firmware destined for Yoctopuce
modules are available as .byn files and can be downloaded from the Yoctopuce web site.
To update a firmware, simply click on the upgrade button on the configuration window and follow the
instructions. If the update fails for one reason or another, unplug and re-plug the module and start
the update process again. This solves the issue in most cases. If the module was unplugged while it
was being reprogrammed, it does probably not work anymore and is not listed in the interface.
However, it is always possible to reprogram the module correctly by using the Virtual Hub software
3
in command line 4.
3
www.yoctopuce.com/EN/virtualhub.php
4
More information available in the virtual hub documentation
3. First steps
10www.yoctopuce.com
Logical name of the module
The logical name is a name that you choose, which allows you to access your module, in the same
way a file name allows you to access its content. A logical name has a maximum length of 19
characters. Authorized characters are A..Z, a..z, 0..9, _, and -. If you assign the same logical name
to two modules connected to the same computer and you try to access one of them through this
logical name, behavior is undetermined: you have no way of knowing which of the two modules
answers.
Luminosity
This parameter allows you to act on the maximal intensity of the leds of the module. This enables
you, if necessary, to make it a little more discreet, while limiting its power consumption. Note that this
parameter acts on all the signposting leds of the module, including the Yocto-led. If you connect a
module and no led turns on, it may mean that its luminosity was set to zero.
Logical names of functions
Each Yoctopuce module has a serial number and a logical name. In the same way, each function on
each Yoctopuce module has a hardware name and a logical name, the latter can be freely chosen by
the user. Using logical names for functions provides a greater flexibility when programming modules.
You can assign logical names to several functions of the Yocto-GPS by clicking on the corresponding
"rename" button.
The GPS function
The gps function groups all the measures computed by the module: position, ground speed, travel
direction, time, and so on... Latitude and longitude are presented as character strings with a format to
be selected between DD°MM'SS.SSS", DD°MM.MMMM, and DD.DDDDDD. You can make do with
only this function. But if you need to make calculations on the positions, or if you want to use
callbacks5, the following functions prove useful.
Latitude and Longitude functions
They enable you to obtain the current latitude and longitude in numerical format, independently of the
display format selected in the GPS function. Note, for technical reasons, the values are not given in
degrees but in millidegrees (thousandths of degree).
The Altitude function
It returns an estimate of the current altitude. Beware, altitude computations based on GPS systems
are very imprecise. Expect errors of several tens of meters.
The groundSpeed function
The Yocto-GPS can compute the ground speed, that is the horizontal speed relative to the ground.
Limitations
The Yocto-GPS has pretty standard limitations: it will lose track if any of the following limits are
exceeded:
• ITAR limits: velocity greater than 515 m/s AND altitude above 18,000 m
• altitude: 100,000 m (max) or -1500 m (min)
• velocity: 600 m/s (max)
• acceleration: 2g (max)
5
See the chapter on "Advanced programming"
3. First steps
www.yoctopuce.com11
12www.yoctopuce.com
4. Assembly and connections
This chapter provides important information regarding the use of the Yocto-GPS module in real-world
situations. Make sure to read it carefully before going too far into your project if you want to avoid
pitfalls.
4.1. Fixing
While developing your project, you can simply let the module hang at the end of its cable. Check only
that it does not come in contact with any conducting material (such as your tools). When your project
is almost at an end, you need to find a way for your modules to stop moving around.
Examples of assembly on supports
The Yocto-GPS 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 packaging tape should be enough for electric insulation.
4.2. Antenna
The antenna is a key element of your system. Make sure that it is always set up in such a way as it
can "see" the largest part of the sky possible. Except in particular cases, you cannot receive good
quality GPS signals from inside. However, if you really want to try, set the antenna near a window.
www.yoctopuce.com13
Antenna cable
The Yocto-GPS is sold with a ceramic active antenna at the end of a ten centimeter coaxial cable
ending with a U.FL connector. This type of cable is rather fragile: avoid bending it at a right angle,
you could damage it. Be particularly careful about the antenna-cable juncture.
Coaxial antenna cables are fragile: avoid bending them
U.FL connectors
Theoretically, U.FL connectors are not designed to be connected more than about 10 times. Make
sure that the U.FL plug offers a good contact: when connected, it must not be able to rotate freely
around the connector. If you plan to build a system with a removable external antenna, use a female
U.FL to SMA adaptor cable and a corresponding antenna. Almost all external antennas have an SMA
connector.
External GPS antenna usually have an SMA connector
Choosing an antenna
You do not need to use the GPS antenna delivered with the Yocto-GPS. There are many GPS
antennas on the market. You must select an active antenna: active antennas include a small
electronic amplifier limiting the loses due to the antenna cable. They are usually required when the
distance between the antenna and the GPS receiver goes above 10 centimeters or so. An active
GPS antenna is most often powered directly through the antenna cable. You can use any active GPS
antenna directly with the Yocto-GPS as long as
• it can work when powered in 3.3V
• its gain does not go above 35db.
4.3. USB power distribution
Although USB means Universal Serial BUS, USB devices are not physically organized as a flat bus
but as a tree, using point-to-point connections. This has consequences on power distribution: to
make it simple, every USB port must supply power to all devices directly or indirectly connected to it.
And USB puts some limits.
In theory, a USB port provides 100mA, and may provide up to 500mA if available and requested by
the device. In the case of a hub without external power supply, 100mA are available for the hub itself,
and the hub should distribute no more than 100mA to each of its ports. This is it, and this is not
much. In particular, it means that in theory, it is not possible to connect USB devices through two
cascaded hubs without external power supply. In order to cascade hubs, it is necessary to use selfpowered USB hubs, that provide a full 500mA to each subport.
In practice, USB would not have been as successful if it was really so picky about power distribution.
As it happens, most USB hub manufacturers have been doing savings by not implementing current
limitation on ports: they simply connect the computer power supply to every port, and declare
themselves as self-powered hub even when they are taking all their power from the USB bus (in
4. Assembly and connections
14www.yoctopuce.com
order to prevent any power consumption check in the operating system). This looks a bit dirty, but
given the fact that computer USB ports are usually well protected by a hardware current limitation
around 2000mA, it actually works in every day life, and seldom makes hardware damage.
What you should remember: if you connect Yoctopuce modules through one, or more, USB hub
without external power supply, you have no safe-guard and you depend entirely on your computer
manufacturer attention to provide as much current as possible on the USB ports, and to detect
overloads before they lead to problems or to hardware damages. When modules are not provided
enough current, they may work erratically and create unpredictable bugs. If you want to prevent any
risk, do not cascade hubs without external power supply, and do not connect peripherals requiring
more than 100mA behind a bus-powered hub.
In order to help controlling and planning overall power consumption for your project, all Yoctopuce
modules include a built-in current sensor that tells (with 5mA precision) the consumption of the
module on the USB bus.
4. Assembly and connections
www.yoctopuce.com15
16www.yoctopuce.com
5. Programming, general concepts
The Yoctopuce API was designed to be at the same time simple to use and sufficiently generic for
the concepts used to be valid for all the modules in the Yoctopuce range, and this in all the available
programming languages. Therefore, when you have understood how to drive your Yocto-GPS 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.
5.1. Programming paradigm
The Yoctopuce API is object oriented. However, for simplicity's sake, only the basics of object
programming were used. Even if you are not familiar with object programming, it is unlikely that this
will be a hinderance for using Yoctopuce products. Note that you will never need to allocate or
deallocate an object linked to the Yoctopuce API: it is automatically managed.
There is one class per Yoctopuce function type. The name of these classes always starts with a Y
followed by the name of the function, for example YTemperature, YRelay, YPressure, etc.. There is
also a YModule class, dedicated to managing the modules themselves, and finally there is the static
YAPI class, that supervises the global workings of the API and manages low level communications.
Structure of the Yoctopuce API.
The YSensor class
Each Yoctopuce sensor function has its dedicated class: YTemperature to measure the temperature,
YVoltage to measure a voltage, YRelay to drive a relay, etc. However there is a special class that
can do more: YSensor.
www.yoctopuce.com17
The YSensor class is the parent class for all Yoctopuce sensors, and can provide access to any
sensor, regardless of its type. It includes methods to access all common functions. This makes it
easier to create applications that use many different sensors. Moreover, if you create an application
based on YSensor, it will work with all Yoctopuce sensors, even those which do no yet exist.
Programmation
In the Yoctopuce API, priority was put on the ease of access to the module functions by offering the
possibility to make abstractions of the modules implementing them. Therefore, it is quite possible to
work with a set of functions without ever knowing exactly which module are hosting them at the
hardware level. This tremendously simplifies programming projects with a large number of modules.
From the programming stand point, your Yocto-GPS is viewed as a module hosting a given number
of functions. In the API, these functions are objects which can be found independently, in several
ways.
Access to the functions of a module
Access by logical name
Each function can be assigned an arbitrary and persistent logical name: this logical name is stored in
the flash memory of the module, even if this module is disconnected. An object corresponding to an
Xxx function to which a logical name has been assigned can then be directly found with this logical
name and the YXxx.FindXxx method. Note however that a logical name must be unique among all
the connected modules.
Access by enumeration
You can enumerate all the functions of the same type on all the connected modules with the help of
the classic enumeration functions FirstXxx and nextXxxx available for each YXxx class.
Access by hardware name
Each module function has a hardware name, assigned at the factory and which cannot be modified.
The functions of a module can also be found directly with this hardware name and the YXxx.FindXxx
function of the corresponding class.
Difference between Find and First
The YXxx.FindXxxx and YXxx.FirstXxxx methods do not work exactly the same way. If there is no
available module, YXxx.FirstXxxx returns a null value. On the opposite, even if there is no
corresponding module, YXxx.FindXxxx returns a valid object, which is not online but which could
become so if the corresponding module is later connected.
Function handling
When the object corresponding to a function is found, its methods are available in a classic way.
Note that most of these subfunctions require the module hosting the function to be connected in
order to be handled. This is generally not guaranteed, as a USB module can be disconnected after
the control software has started. The isOnline method, available in all the classes, is then very
helpful.
Access to the modules
Even if it is perfectly possible to build a complete project while making a total abstraction of which
function is hosted on which module, the modules themselves are also accessible from the API. In
fact, they can be handled in a way quite similar to the functions. They are assigned a serial number
at the factory which allows you to find the corresponding object with YModule.Find(). You can also
assign arbitrary logical names to the modules to make finding them easier. Finally, the YModule
class contains the YModule.FirstModule() and nextModule() enumeration methods allowing you to list
the connected modules.
5. Programming, general concepts
18www.yoctopuce.com
Functions/Module interaction
From the API standpoint, the modules and their functions are strongly uncorrelated by design.
Nevertheless, the API provides the possibility to go from one to the other. Thus, the get_module()
method, available for each function class, allows you to find the object corresponding to the module
hosting this function. Inversely, the YModule class provides several methods allowing you to
enumerate the functions available on a module.
5.2. The Yocto-GPS module
The Yocto-GPS is an GNSS interface .
module : Module
attributetypemodifiable ?
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
gps : Gps
attributetypemodifiable ?
logicalName String modifiable
advertisedValue String modifiable
isFixed Boolean read-only
satCount Integer read-only
coordSystem Enumerated modifiable
latitude String read-only
longitude String read-only
dilution Fixed-point number read-only
altitude Fixed-point number read-only
groundSpeed Fixed-point number read-only
direction Fixed-point number read-only
unixTime UTC time read-only
dateTime String read-only
utcOffset Integer modifiable
command String modifiable
latitude : Latitude
attributetypemodifiable ?
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
calibrationParam Calibration parameters modifiable
resolution Fixed-point number modifiable
5. Programming, general concepts
www.yoctopuce.com19
sensorState Integer read-only
longitude : Longitude
attributetypemodifiable ?
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
calibrationParam Calibration parameters modifiable
resolution Fixed-point number modifiable
sensorState Integer read-only
altitude : Altitude
attributetypemodifiable ?
logicalName String modifiable
advertisedValue String modifiable
unit String read-only
currentValue Fixed-point number modifiable
lowestValue Fixed-point number modifiable
highestValue Fixed-point number modifiable
currentRawValue Fixed-point number read-only
logFrequency Frequency modifiable
reportFrequency Frequency modifiable
calibrationParam Calibration parameters modifiable
resolution Fixed-point number modifiable
sensorState Integer read-only
qnh Fixed-point number modifiable
technology String read-only
groundSpeed : GroundSpeed
attributetypemodifiable ?
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
calibrationParam Calibration parameters modifiable
resolution Fixed-point number modifiable
sensorState Integer read-only
This interface is identical for all Yoctopuce USB modules. It can be used to control the module global
parameters, and to enumerate the functions provided by each module.
productName
Character string containing the commercial name of the module, as set by the factory.
serialNumber
Character string containing the serial number, unique and programmed at the factory. For a YoctoGPS module, this serial number always starts with YGNSSMK1. You can use the serial number to
access a given module by software.
logicalName
Character string containing the logical name of the module, initially empty. This attribute can be
modified at will by the user. Once initialized to an non-empty value, it can be used to access a given
module. If two modules with the same logical name are in the same project, there is no way to
determine which one answers when one tries accessing by logical name. The logical name is limited
to 19 characters among A..Z,a..z,0..9,_, and -.
productId
USB device identifier of the module, preprogrammed to 83 at the factory.
productRelease
Release number of the module hardware, preprogrammed at the factory.
firmwareRelease
Release version of the embedded firmware, changes each time the embedded software is updated.
persistentSettings
State of persistent module settings: loaded from flash memory, modified by the user or saved to flash
memory.
luminosity
Lighting strength of the informative leds (e.g. the Yocto-Led) contained in the module. It is an integer
value which varies between 0 (leds turned off) and 100 (maximum led intensity). The default value is
50. To change the strength of the module leds, or to turn them off completely, you only need to
change this value.
beacon
Activity of the localization beacon of the module.
upTime
Time elapsed since the last time the module was powered on.
usbCurrent
Current consumed by the module on the USB bus, in milli-amps.
rebootCountdown
Countdown to use for triggering a reboot of the module.
5. Programming, general concepts
www.yoctopuce.com21
userVar
32bit integer variable available for user storage.
5.4. GPS function interface
The Gps function allows you to extract positionning data from the GPS device. This class can
provides complete positionning information: However, if you whish to define callbacks on position
changes, you should use the YLatitude et YLongitude classes.
logicalName
Character string containing the logical name of the GPS, 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 GPS
directly. If two GPS with the same logical name are used in the same project, there is no way to
determine which one answers when one tries accessing by logical name. The logical name is limited
to 19 characters among A..Z,a..z,0..9,_, and -.
advertisedValue
Short character string summarizing the current GPS reception state.
isFixed
Indicates whether the receiver has found enough satellites to work
satCount
Visible satellite count.
coordSystem
Representation system to use for positioning data
latitude
Current latitude
longitude
Current longitude
dilution
Current dilution of precision
altitude
Current altitude
groundSpeed
Current ground speed
direction
Current direction
unixTime
Unix form of the current time (number of elapsed seconds since Jan 1970 1st)
dateTime
Current time in the form "YYYY/MM/DD hh:mm:ss"
5. Programming, general concepts
22www.yoctopuce.com
utcOffset
Number of seconds between current time and UTC time (time zone)
command
Magic attribute used to send commands to the device. If a command is not interpreted as expected,
check the device logs.
5.5. Latitude function interface
The Yoctopuce class YLatitude allows you to read the latitude from Yoctopuce geolocalization
sensors. It inherits from the YSensor class the core functions to read measurements, to register
callback functions, to access the autonomous datalogger.
logicalName
Character string containing the logical name of the latitude 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
latitude sensor directly. If two latitude sensors with the same logical name are used in the same
project, there is no way to determine which one answers when one tries accessing by logical name.
The logical name is limited to 19 characters among A..Z,a..z,0..9,_, and -.
advertisedValue
Short character string summarizing the current state of the latitude sensor, that is automatically
advertised up to the parent hub. For a latitude sensor, the advertised value is the current value of the
latitude.
unit
Short character string representing the measuring unit for the latitude.
currentValue
Current value of the latitude, in deg/1000, as a floating point number.
lowestValue
Minimal value of the latitude, in deg/1000, as a floating point number.
highestValue
Maximal value of the latitude, in deg/1000, as a floating point number.
currentRawValue
Uncalibrated, unrounded raw value returned by the sensor, as a floating point number.
logFrequency
Datalogger recording frequency, or "OFF" when measures should not be stored in the data logger
flash memory.
reportFrequency
Timed value notification frequency, or "OFF" when timed value notifications are disabled for this
function.
calibrationParam
Extra calibration parameters (for instance to compensate for the effects of an enclosure), as an array
of 16 bit words.
5. Programming, general concepts
www.yoctopuce.com23
resolution
Measure resolution (i.e. precision of the numeric representation, not necessarily of the measure
itself).
sensorState
Sensor health state (zero when a current measure is available).
5.6. Longitude function interface
The Yoctopuce class YLongitude allows you to read the longitude from Yoctopuce geolocalization
sensors. It inherits from the YSensor class the core functions to read measurements, register
callback functions, access the autonomous datalogger.
logicalName
Character string containing the logical name of the longitude 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
longitude sensor directly. If two longitude sensors with the same logical name are used in the same
project, there is no way to determine which one answers when one tries accessing by logical name.
The logical name is limited to 19 characters among A..Z,a..z,0..9,_, and -.
advertisedValue
Short character string summarizing the current state of the longitude sensor, that is automatically
advertised up to the parent hub. For a longitude sensor, the advertised value is the current value of
the longitude.
unit
Short character string representing the measuring unit for the longitude.
currentValue
Current value of the longitude, in deg/1000, as a floating point number.
lowestValue
Minimal value of the longitude, in deg/1000, as a floating point number.
highestValue
Maximal value of the longitude, in deg/1000, as a floating point number.
currentRawValue
Uncalibrated, unrounded raw value returned by the sensor, as a floating point number.
logFrequency
Datalogger recording frequency, or "OFF" when measures should not be stored in the data logger
flash memory.
reportFrequency
Timed value notification frequency, or "OFF" when timed value notifications are disabled for this
function.
calibrationParam
Extra calibration parameters (for instance to compensate for the effects of an enclosure), as an array
of 16 bit words.
5. Programming, general concepts
24www.yoctopuce.com
resolution
Measure resolution (i.e. precision of the numeric representation, not necessarily of the measure
itself).
sensorState
Sensor health state (zero when a current measure is available).
5.7. Altitude function interface
The Yoctopuce class YAltitude allows you to read and configure Yoctopuce altitude sensors. It
inherits from the YSensor class the core functions to read measurements, to register callback
functions, to access the autonomous datalogger. This class adds the ability to configure the
barometric pressure adjusted to sea level (QNH) for barometric sensors.
logicalName
Character string containing the logical name of the altimeter, 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
altimeter directly. If two altimeters with the same logical name are used in the same project, there is
no way to determine which one answers when one tries accessing by logical name. The logical name
is limited to 19 characters among A..Z,a..z,0..9,_, and -.
advertisedValue
Short character string summarizing the current state of the altimeter, that is automatically advertised
up to the parent hub. For an altimeter, the advertised value is the current value of the altitude.
unit
Short character string representing the measuring unit for the altitude.
currentValue
Current value of the altitude, in meters, as a floating point number.
lowestValue
Minimal value of the altitude, in meters, as a floating point number.
highestValue
Maximal value of the altitude, in meters, as a floating point number.
currentRawValue
Uncalibrated, unrounded raw value returned by the sensor, as a floating point number.
logFrequency
Datalogger recording frequency, or "OFF" when measures should not be stored in the data logger
flash memory.
reportFrequency
Timed value notification frequency, or "OFF" when timed value notifications are disabled for this
function.
calibrationParam
Extra calibration parameters (for instance to compensate for the effects of an enclosure), as an array
of 16 bit words.
5. Programming, general concepts
www.yoctopuce.com25
resolution
Measure resolution (i.e. precision of the numeric representation, not necessarily of the measure
itself).
sensorState
Sensor health state (zero when a current measure is available).
qnh
Barometric pressure adjusted to sea level.
technology
Sensor tecnology
5.8. GroundSpeed function interface
The Yoctopuce class YGroundSpeed allows you to read the ground speed from Yoctopuce
geolocalization sensors. It inherits from the YSensor class the core functions to read measurements,
register callback functions, access the autonomous datalogger.
logicalName
Character string containing the logical name of the ground speed 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 ground speed sensor directly. If two ground speed sensors with the same logical name
are used in the same project, there is no way to determine which one answers when one tries
accessing by logical name. The logical name is limited to 19 characters among A..Z,a..z,0..9,_, and
-.
advertisedValue
Short character string summarizing the current state of the ground speed sensor, that is
automatically advertised up to the parent hub. For a ground speed sensor, the advertised value is the
current value of the ground speed.
unit
Short character string representing the measuring unit for the ground speed.
currentValue
Current value of the ground speed, in km/h, as a floating point number.
lowestValue
Minimal value of the ground speed, in km/h, as a floating point number.
highestValue
Maximal value of the ground speed, in km/h, as a floating point number.
currentRawValue
Uncalibrated, unrounded raw value returned by the sensor, as a floating point number.
logFrequency
Datalogger recording frequency, or "OFF" when measures should not be stored in the data logger
flash memory.
5. Programming, general concepts
26www.yoctopuce.com
reportFrequency
Timed value notification frequency, or "OFF" when timed value notifications are disabled for this
function.
calibrationParam
Extra calibration parameters (for instance to compensate for the effects of an enclosure), as an array
of 16 bit words.
resolution
Measure resolution (i.e. precision of the numeric representation, not necessarily of the measure
itself).
sensorState
Sensor health state (zero when a current measure is available).
5.9. GPS function interface
The Gps function allows you to extract positionning data from the GPS device. This class can
provides complete positionning information: However, if you whish to define callbacks on position
changes, you should use the YLatitude et YLongitude classes.
logicalName
Character string containing the logical name of the GPS, 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 GPS
directly. If two GPS with the same logical name are used in the same project, there is no way to
determine which one answers when one tries accessing by logical name. The logical name is limited
to 19 characters among A..Z,a..z,0..9,_, and -.
advertisedValue
Short character string summarizing the current GPS reception state.
isFixed
Indicates whether the receiver has found enough satellites to work
satCount
Visible satellite count.
coordSystem
Representation system to use for positioning data
latitude
Current latitude
longitude
Current longitude
dilution
Current dilution of precision
altitude
Current altitude
5. Programming, general concepts
www.yoctopuce.com27
groundSpeed
Current ground speed
direction
Current direction
unixTime
Unix form of the current time (number of elapsed seconds since Jan 1970 1st)
dateTime
Current time in the form "YYYY/MM/DD hh:mm:ss"
utcOffset
Number of seconds between current time and UTC time (time zone)
command
Magic attribute used to send commands to the device. If a command is not interpreted as expected,
check the device logs.
5.10. DataLogger function interface
Yoctopuce sensors include a non-volatile memory capable of storing ongoing measured data
automatically, without requiring a permanent connection to a computer. The DataLogger function
controls the global parameters of the internal data logger.
logicalName
Character string containing the logical name of the data logger, initially empty. This attribute can be
modified at will by the user. Once initialized to an non-empty value, it can be used to access the data
logger directly. If two data loggers with the same logical name are used in the same project, there is
no way to determine which one answers when one tries accessing by logical name. The logical name
is limited to 19 characters among A..Z,a..z,0..9,_, and -.
advertisedValue
Short character string summarizing the current state of the data logger, that is automatically
advertised up to the parent hub. For a data logger, the advertised value is its recording state (ON or
OFF).
currentRunIndex
Current run number, corresponding to the number of time the module was powered on with the
dataLogger enabled at some point.
timeUTC
Current UTC time, in case it is desirable to bind an absolute time reference to the data stored by the
data logger. This time must be set up by software.
recording
Activation state of the data logger. The data logger can be enabled and disabled at will, using this
attribute, but its state on power on is determined by the autoStart persistent attribute. When the
datalogger is enabled but not yet ready to record data, its state is set to PENDING.
autoStart
Automatic start of the data logger on power on. Setting this attribute ensures that the data logger is
always turned on when the device is powered up, without need for a software command.
5. Programming, general concepts
28www.yoctopuce.com
beaconDriven
Synchronize the sate of the localization beacon and the state of the data logger. If this attribute is set,
it is possible to start the recording with the Yocto-button or the attribute beacon of the function
YModule. In the same way, if the attribute recording is changed, the sate of the localization
beacon is updated. Note: when this attribute is set the localization beacon pulses slower than usual.
clearHistory
Attribute that can be set to true to clear recorded data.
5.11. What interface: Native, DLL or Service ?
There are several methods to control you Yoctopuce module by software.
Native control
In this case, the software driving your project is compiled directly with a library which provides control
of the modules. Objectively, it is the simplest and most elegant solution for the end user. The end
user then only needs to plug the USB cable and run your software for everything to work.
Unfortunately, this method is not always available or even possible.
The application uses the native library to control the locally connected module
Native control by DLL
Here, the main part of the code controlling the modules is located in a 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
5. Programming, general concepts
www.yoctopuce.com29
Control by service
Some languages do simply not allow you to easily gain access to the hardware layers of the
machine. It is the case for Javascript, for instance. To deal with this case, Yoctopuce provides a
solution in the form of a small piece of software called VirtualHub1. 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.
1
www.yoctopuce.com/EN/virtualhub.php
5. Programming, general concepts
30www.yoctopuce.com
Language Native Native with DLL Virtual hub
C++
✔✔✔
Objective-C
✔
-
✔
Delphi-
✔✔
Python-
✔✔
VisualBasic .Net-
✔✔
C# .Net-
✔✔
EcmaScript / JavaScript--
✔
PHP--
✔
Java-
✔✔
Java for Android
✔
-
✔
Command line
✔
-
✔
Support methods for different languages
Limitations of the Yoctopuce libraries
Natives et DLL libraries have a technical limitation. On the same computer, you cannot concurrently
run several applications accessing Yoctopuce devices directly. If you want to run several projects on
the same computer, make sure your control applications use Yoctopuce devices through a
VirtualHub software. The modification is trivial: it is just a matter of parameter change in the
yRegisterHub() call.
5.12. Programming, where to start?
At this point of the user's guide, you should know the main theoretical points of your Yocto-GPS. It is
now time to practice. You must download the Yoctopuce library for your favorite programming
language from the Yoctopuce web site2. 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-GPS.
2
http://www.yoctopuce.com/EN/libraries.php
5. Programming, general concepts
www.yoctopuce.com31
32www.yoctopuce.com
6. Using the Yocto-GPS in command line
When you want to perform a punctual operation on your Yocto-GPS, 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 provided1.
6.1. Installing
Download the command line API2. 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-GPS, open a shell, and start working by typing for example:
C:\>YGps any get_latitude
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.
6.2. Use: general description
All the command line API executables work on the same principle. They must be called the following
way
C:\>Executable[options][target]command[parameter]
[options] manage the global workings of the commands, they allow you, for instance, to pilot a
module remotely through the network, or to force the module to save its configuration after executing
the command.
[target] is the name of the module or of the function to which the command applies. Some very
generic commands do not need a target. You can also use the aliases "any" and "all", or a list of
names separated by comas without space.
1
If you want to recompile the command line API, you also need the C++ API.
2
http://www.yoctopuce.com/EN/libraries.php
www.yoctopuce.com33
command is the command you want to run. Almost all the functions available in the classic
programming APIs are available as commands. You need to respect neither the case nor the
underlined characters in the command name.
[parameters] logically are the parameters needed by the command.
At any time, the command line API executables can provide a rather detailed help. Use for instance:
C:\>executable/help
to know the list of available commands for a given command line API executable, or even:
C:\>executablecommand/help
to obtain a detailed description of the parameters of a command.
6.3. Control of the Latitude function
To control the Latitude function of your Yocto-GPS, you need the YLatitude executable file.
For instance, you can launch:
C:\>YGps any get_latitude
This example uses the "any" target to indicate that we want to work on the first Latitude 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-GPS module with the YGNSSMK1-123456 serial number which you have called
"MyModule", and its latitude function which you have renamed "MyFunction". The five following calls
are strictly equivalent (as long as MyFunction is defined only once, to avoid any ambiguity).
C:\>YLatitude YGNSSMK1-123456.latitude describe
C:\>YLatitude YGNSSMK1-123456.MyFunction describe
C:\>YLatitude MyModule.latitude describe
C:\>YLatitude MyModule.MyFunction describe
C:\>YLatitude MyFunction describe
To work on all the Latitude functions at the same time, use the "all" target.
C:\>YLatitude all describe
For more details on the possibilities of the YLatitude executable, use:
C:\>YLatitude /help
6.4. Control of the module part
Each module can be controlled in a similar way with the help of the YModule executable. For
example, to obtain the list of all the connected modules, use:
C:\>YModule inventory
You can also use the following command to obtain an even more detailed list of the connected
modules:
6. Using the Yocto-GPS in command line
34www.yoctopuce.com
C:\>YModule all describe
Each xxx property of the module can be obtained thanks to a command of the get_xxxx() type,
and the properties which are not read only can be modified with the 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:
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.
6.5. Limitations
The command line API has the same limitation than the other APIs: there can be only one application
at a given time which can access the modules natively. By default, the command line API works in
native mode.
You can easily work around this limitation by using a Virtual Hub: run the VirtualHub3 on the
concerned machine, and use the executables of the command line API with the -r option. For
example, if you use:
C:\>YModule inventory
you obtain a list of the modules connected by USB, using a native access. If another command which
accesses the modules natively is already running, this does not work. But if you run a Virtual Hub,
and you give your command in the form:
C:\>YModule -r 127.0.0.1 inventory
it works because the command is not executed natively anymore, but through the Virtual Hub. Note
that the Virtual Hub counts as a native application.
3
http://www.yoctopuce.com/EN/virtualhub.php
6. Using the Yocto-GPS in command line
www.yoctopuce.com35
36www.yoctopuce.com
7. Using Yocto-GPS with JavaScript / EcmaScript
EcmaScript is the official name of the standardized version of the web-oriented programming
language commonly referred to as JavaScript. This Yoctopuce library take advantages of advanced
features introduced in EcmaScript 2017. It has therefore been named Library for JavaScript / EcmaScript 2017 to differentiate it from the previous Library for JavaScript, now deprecated in favor
of this new version.
This library provides access to Yoctopuce devices for modern JavaScript engines. It can be used
within a browser as well as with Node.js. The library will automatically detect upon initialization
whether the runtime environment is a browser or a Node.js virtual machine, and use the most
appropriate system libraries accordingly.
Asynchronous communication with the devices is handled across the whole library using Promise
objects, leveraging the new EcmaScript 2017 async / await non-blocking syntax for asynchronous
I/O (see below). This syntax is now available out-of-the-box in most Javascript engines. No
transpilation is needed: no Babel, no jspm, just plain Javascript. Here is your favorite engines
minimum version needed to run this code. All of them are officially released at the time we write this
document.
• Node.js v7.6 and later
• Firefox 52
• Opera 42 (incl. Android version)
• Chrome 55 (incl. Android version)
• Safari 10.1 (incl. iOS version)
• Android WebView 55
• Google V8 Javascript engine v5.5
If you need backward-compatibility with older releases, you can always run Babel to transpile your
code and the library to older standards, as described a few paragraphs below.
We don't suggest using jspm 0.17 anymore since that tool is still in Beta after 18 month, and
having to use an extra tool to implement our library is pointless now that async / await are part of
the standard.
7.1. Blocking I/O versus Asynchronous I/O in JavaScript
JavaScript is single-threaded by design. That means, if a program is actively waiting for the result of
a network-based operation such as reading from a sensor, the whole program is blocked. In browser
environments, this can even completely freeze the user interface. For this reason, the use of blocking
I/O in JavaScript is strongly discouraged nowadays, and blocking network APIs are getting
deprecated everywhere.
www.yoctopuce.com37
Instead of using parallel threads, JavaScript relies on asynchronous I/O to handle operations with a
possible long timeout: whenever a long I/O call needs to be performed, it is only triggered and but
then the code execution flow is terminated. The JavaScript engine is therefore free to handle other
pending tasks, such as UI. Whenever the pending I/O call is completed, the system invokes a
callback function with the result of the I/O call to resume execution of the original execution flow.
When used with plain callback functions, as pervasive in Node.js libraries, asynchronous I/O tend to
produce code with poor readability, as the execution flow is broken into many disconnected callback
functions. Fortunately, new methods have emerged recently to improve that situation. In particular,
the use of Promise objects to abstract and work with asynchronous tasks helps a lot. Any function
that makes a long I/O operation can return a Promise, which can be used by the caller to chain
subsequent operations in the same flow. Promises are part of EcmaScript 2015 standard.
Promise objects are good, but what makes them even better is the new async / await keywords to
handle asynchronous I/O:
• a function declared async will automatically encapsulate its result as a Promise
• within an async function, any function call prefixed with by await will chain the Promise
returned by the function with a promise to resume execution of the caller
• any exception during the execution of an async function will automatically invoke the Promise
failure continuation
Long story made short, async and await make it possible to write EcmaScript code with all benefits of
asynchronous I/O, but without breaking the code flow. It is almost like multi-threaded execution,
except that control switch between pending tasks only happens at places where the await keyword
appears.
We have therefore chosen to write our new EcmaScript library using Promises and async functions,
so that you can use the friendly await syntax. To keep it easy to remember, all public methods of
the EcmaScript library are async, i.e. return a Promise object, except:
• GetTickCount(), because returning a time stamp asynchronously does not make sense...
• FindModule(), FirstModule(), nextModule(), ... because device detection and
enumeration always work on internal device lists handled in background, and does not require
immediate asynchronous I/O.
7.2. Using Yoctopuce library for JavaScript / EcmaScript 2017
JavaScript is one of those languages which do not generally allow you to directly access the
hardware layers of your computer. Therefore the library can only be used to access network-enabled
devices (connected through a YoctoHub), or USB devices accessible through Yoctopuce TCP/IP to
USB gateway, named VirtualHub.
Go to the Yoctopuce web site and download the following items:
• The Javascript / EcmaScript 2017 programming library
1
• The VirtualHub software2 for Windows, Mac OS X or Linux, depending on your OS
Extract the library files in a folder of your choice, you will find many of examples in it. Connect your
modules and start the VirtualHub software. You do not need to install any driver.
Using the official Yoctopuce library for node.js
Start by installing the latest Node.js version (v7.6 or later) on your system. It is very easy. You can
download it from the official web site: http://nodejs.org. Make sure to install it fully, including npm, and
add it to the system path.
1
www.yoctopuce.com/EN/libraries.php
2
www.yoctopuce.com/EN/virtualhub.php
7. Using Yocto-GPS with JavaScript / EcmaScript
38www.yoctopuce.com
To give it a try, go into one of the example directory (for instance example_nodejs/Doc-Inventory).
You will see that it include an application description file (package.json) and a source file (demo.js).
To download and setup the libraries needed by this example, just run:
npm install
Once done, you can start the example file using:
node demo.js
Using a local copy of the Yoctopuce library with node.js
If for some reason you need to make changes to the Yoctopuce library, you can easily configure your
project to use the local copy in the lib/ subdirectory rather than the official npm package. In order
to do so, simply type the following command in your project directory:
npm link ../../lib
Using the Yoctopuce library within a browser (HTML)
For HTML examples, it is even simpler: there is nothing to install. Each example is a single HTML file
that you can open in a browser to try it. In this context, loading the Yoctopuce library is no different
from any standard HTML script include tag.
Using the Yoctoluce library on older JavaScript engines
If you need to run this library on older JavaScript engines, you can use Babel3 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.
Backward-compatibility with the old JavaScript library
This new library is not fully backward-compatible with the old JavaScript library, because there is no
way to transparently map the old blocking API to the new asynchronous API. The method names
however are the same, and old synchronous code can easily be made asynchronous just by adding
the proper await keywords before the method calls. For instance, simply replace:
beaconState = module.get_beacon();
by
3
http://babeljs.io
7. Using Yocto-GPS with JavaScript / EcmaScript
www.yoctopuce.com39
beaconState = await module.get_beacon();
Apart from a few exceptions, most XXX_async redundant methods have been removed as well, as
they would have introduced confusion on the proper way of handling asynchronous behaviors. It is
however very simple to get an async method to invoke a callback upon completion, using the
returned Promise object. For instance, you can replace:
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:
// Get access to your device, through the VirtualHub running locally
await YAPI.RegisterHub('127.0.0.1');
var latitude = YLatitude.FindLatitude("YGNSSMK1-123456.latitude");
// Check that the module is online to handle hot-plug
if(await latitude.isOnline())
{
// Use latitude.get_currentValue()[...]
}
Let us look at these lines in more details.
7. Using Yocto-GPS with JavaScript / EcmaScript
40www.yoctopuce.com
YAPI and YLatitude Import
These two import provide access to functions allowing you to manage Yoctopuce modules. YAPI is
always needed, YLatitude.js is necessary to manage modules containing a latitude sensor,
such as Yocto-GPS. Other imports can be useful in other cases, such as YModule which can let
you enumerate any type of Yoctopuce device.
YAPI.RegisterHub
The RegisterHub method allows you to indicate on which machine the Yoctopuce modules are
located, more precisely on which machine the VirtualHub software is running. In our case, the
127.0.0.1:4444 address indicates the local machine, port 4444 (the standard port used by
Yoctopuce). You can very well modify this address, and enter the address of another machine on
which the VirtualHub software is running, or of a YoctoHub. If the host cannot be reached, this
function will trigger an exception.
YLatitude.FindLatitude
The FindLatitude method allows you to find a latitude 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-GPS module with serial number
YGNSSMK1-123456 which you have named "MyModule", and for which you have given the latitude
function the name "MyFunction". The following five calls are strictly equivalent, as long as
"MyFunction" is defined only once.
latitude = YLatitude.FindLatitude("YGNSSMK1-123456.latitude")
latitude = YLatitude.FindLatitude("YGNSSMK1-123456.MaFonction")
latitude = YLatitude.FindLatitude("MonModule.latitude")
latitude = YLatitude.FindLatitude("MonModule.MaFonction")
latitude = YLatitude.FindLatitude("MaFonction")
YLatitude.FindLatitude returns an object which you can then use at will to control the
latitude sensor.
isOnline
The isOnline() method of the object returned by FindLatitude allows you to know if the
corresponding module is present and in working order.
get_latitude
The get_latitude() method of the object returned by YGps.FindGps provides the latitude
currently measured by the Yocto-GPS. The value returned is a string, the format will vary according
to the Yocto-GPS configuration. To get a floating point value, no matter the configuartion, use the
YLatitude Class.
A real example
Open a command window (a terminal, a shell...) and go into the directory example_node/DocGettingStarted-Yocto-GPS within Yoctopuce EcmaScript library. In there, you will find a
subdirectory src 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-GPS 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-GPS is connected and where
you run the VirtualHub.
// Setup the API to use the VirtualHub on local machinelet errmsg = new YErrorMsg();if(await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS){
console.log('Cannot contact VirtualHub on 127.0.0.1: '+errmsg.msg);return;
}
// Select specified device, or use first available onelet serial = process.argv[process.argv.length-1];
if(serial[8] != '-'){// by default use any connected module suitable for the demolet anysensor = YGps.FirstGps();if(anysensor){let module = await anysensor.module();
serial = await module.get_serialNumber();}else{
console.log('No matching sensor connected, check cable !');return;
}}
console.log('Using device '+serial);
gps = YGps.FindGps(serial+".gps");
As explained at the beginning of this chapter, you need to have Node.js and jspm installed to try this
example. When done, you can type the following two commands to automatically download and
install the dependencies for building this example:
npm install
jspm install
You can the start the sample code within Node.js using the following command, replacing the [...] by
the arguments that you want to pass to the demo code:
jspm run src/demo.js [...]
Same example, but this time running in a browser
If you want to see how to use the library within a browser, switch to the directory example_html/
Doc-GettingStarted-Yocto-GPS. You will find there a subdirectory src as well with a very similar
source code (below), but with a few changes compared to the Node.js version since it has to interact
through an HTML page rather than through the JavaScript console.
// Setup the API to use the VirtualHub on local machinelet errmsg = new YErrorMsg();if(await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS){alert('Cannot contact VirtualHub on 127.0.0.1: '+errmsg.msg);}
7. Using Yocto-GPS with JavaScript / EcmaScript
42www.yoctopuce.com
refresh();
}
asyncfunction refresh()
{
let serial = document.getElementById('serial').value;
if(serial == ''){// by default use any connected module suitable for the demolet anysensor = YGps.FirstGps();if(anysensor){let module = await anysensor.module();
serial = await module.get_serialNumber();document.getElementById('serial').value = serial;
}}let gps = YGps.FindGps(serial+".gps");
}}else{document.getElementById('msg').value = 'Module not connected';
}setTimeout(refresh, 500);
}
startDemo();
At the root of this example you will also find a file demo.html which contains the UI elements for the
demo code.
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title><scriptsrc='jspm_packages/system.js'></script><scriptsrc='jspm.browser.js'></script><scriptsrc='jspm.config.js'></script><script>
System.import('app/helloworld.js');
</script><!-- When going in production, you can generate a self-contained js file using
As above, the two following commands will download and install all dependencies for building this
example:
npm install
jspm install
You can now publish this directory on a Web server to test the example through a web browser. In
order to let the loader find its files, you will have to point the baseURL parameter in jspm.browser.js
file to the path within the web server root to reach the demo project. For instance, if you open the
7. Using Yocto-GPS with JavaScript / EcmaScript
www.yoctopuce.com43
example using URL http://127.0.0.1/EcmaScript/example_html/Doc-GettingStarted-Yocto-GPS/
demo.html then the beginning of your jspm.browser.js file should look like:
If you prefer to open the demo code as a local file rather than through a web server, or if you would
like the example to load as a single JavaScript file rather than as dynamically loaded modules, you
can build it with the command:
jspm build --minify src/demo.js demo-sfx.js
This will create a single JavaScript file named demo-sfx.js in the root directory of the project, that
can be included directly in the HTML file instead of the 6 script lines:
<scriptsrc='demo-sfx.js'></script>
Once your project is built in this way, the example can be opened by a browser directly from the local
disk.
7.4. Control of the module part
Each module can be controlled in a similar manner, you can find below a simple sample program
displaying the main parameters of the module and enabling you to activate the localization beacon.
// Setup the API to use the VirtualHub on local machinelet errmsg = new YErrorMsg();if(await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS){
console.log('Cannot contact VirtualHub on 127.0.0.1: '+errmsg.msg);return;
}
Each property xxx of the module can be read thanks to a method of type get_xxxx(), and
properties which are not read-only can be modified with the help of the set_xxx() method. For
more details regarding the used functions, refer to the API chapters.
Changing the module settings
When you want to modify the settings of a module, you only need to call the corresponding
set_xxx() function. However, this modification is performed only in the random access memory
(RAM) of the module: if the module is restarted, the modifications are lost. To memorize them
persistently, it is necessary to ask the module to save its current configuration in its permanent
memory. To do so, use the saveToFlash() method. Inversely, it is possible to force the module to
forget its current settings by using the revertFromFlash() method. The short example below
allows you to modify the logical name of a module.
// Setup the API to use the VirtualHub on local machinelet errmsg = new YErrorMsg();if(await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS){
console.log('Cannot contact VirtualHub on 127.0.0.1: '+errmsg.msg);return;
}
// Select the relay to uselet module = YModule.FindModule(args[0]);if(await module.isOnline()){if(args.length > 1){var newname = args[1];if(!await YAPI.CheckLogicalName(newname)){
console.log("Invalid name (" + newname + ")");
process.exit(1);}await module.set_logicalName(newname);await module.saveToFlash();}
console.log('Current name: '+await module.get_logicalName());
}else{
console.log("Module not connected (check identification and USB cable)\n");}await YAPI.FreeAPI();
}
if(process.argv.length < 3){
console.log("usage: jspm run src/demo.js <serial> [newLogicalName]");
Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this
limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to
the technology employed by the module micro-processor, is located at about 100000 cycles. In short,
you can use the saveToFlash() function only 100000 times in the life of the module. Make sure
you do not call this function within a loop.
Listing the modules
Obtaining the list of the connected modules is performed with the YModule.FirstModule()
function which returns the first module found. Then, you only need to call the nextModule()
function of this object to find the following modules, and this as long as the returned value is not
null. Below a short example listing the connected modules.
// Setup the API to use the VirtualHub on local machinelet errmsg = new YErrorMsg();if(await YAPI.RegisterHub('127.0.0.1', errmsg) != YAPI.SUCCESS){
console.log('Cannot contact VirtualHub on 127.0.0.1');return;
}
refresh();
}
asyncfunction refresh()
{
try{let errmsg = new YErrorMsg();await YAPI.UpdateDeviceList(errmsg);
let module = YModule.FirstModule();while(module){let line = await module.get_serialNumber();
line += '(' + (await module.get_productName()) + ')';
console.log(line);
module = module.nextModule();}setTimeout(refresh, 500);}catch(e){
console.log(e);}
}
try{
startDemo();
}catch(e){
console.log(e);
}
7.5. Error handling
When you implement a program which must interact with USB modules, you cannot disregard error
handling. Inevitably, there will be a time when a user will have unplugged the device, either before
running the software, or even while the software is running. The Yoctopuce library is designed to help
you support this kind of behavior, but your code must nevertheless be conceived to interpret in the
best possible way the errors indicated by the library.
The simplest way to work around the problem is the one used in the short examples provided in this
chapter: before accessing a module, check that it is online with the isOnline function, and then
hope that it will stay so during the fraction of a second necessary for the following code lines to run.
This method is not perfect, but it can be sufficient in some cases. You must however be aware that
you cannot completely exclude an error which would occur after the call to isOnline and which
could crash the software. The only way to prevent this is to implement one of the two error handling
techniques described below.
The method recommended by most programming languages for unpredictable error handling is the
use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while
you try to access a module, the library throws an exception. In this case, there are three possibilities:
• If your code catches the exception and handles it, everything goes well.
• If your program is running in debug mode, you can relatively easily determine where the
problem happened and view the explanatory message linked to the exception.
• Otherwise... the exception makes your program crash, bang!
As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for
error handling, allowing you to create a robust program without needing to catch exceptions at every
line of code. You simply need to call the YAPI.DisableExceptions() function to commute the
library to a mode where exceptions for all the functions are systematically replaced by specific return
7. Using Yocto-GPS with JavaScript / EcmaScript
46www.yoctopuce.com
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.
7. Using Yocto-GPS with JavaScript / EcmaScript
www.yoctopuce.com47
48www.yoctopuce.com
8. Using Yocto-GPS with PHP
PHP is, like Javascript, an atypical language when interfacing with hardware is at stakes.
Nevertheless, using PHP with Yoctopuce modules provides you with the opportunity to very easily
create web sites which are able to interact with their physical environment, and this is not available to
every web server. This technique has a direct application in home automation: a few Yoctopuce
modules, a PHP server, and you can interact with your home from anywhere on the planet, as long
as you have an internet connection.
PHP is one of those languages which do not allow you to directly access the hardware layers of your
computer. Therefore you need to run a virtual hub on the machine on which your modules are
connected.
To start your tests with PHP, you need a PHP 5.3 (or more) server1, 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.
8.1. Getting ready
Go to the Yoctopuce web site and download the following items:
• The PHP programming library
2
• The VirtualHub software3 for Windows, Mac OS X, or Linux, depending on your OS
Decompress the library files in a folder of your choice accessible to your web server, connect your
modules, run the VirtualHub software, and you are ready to start your first tests. You do not need to
install any driver.
8.2. Control of the Latitude function
A few lines of code are enough to use a Yocto-GPS. Here is the skeleton of a PHP code snipplet to
use the Latitude function.
// Check that the module is online to handle hot-plug
if(latitude->isOnline())
{
// Use latitude->get_currentValue(), ...
}
Let's look at these lines in more details.
yocto_api.php and yocto_latitude.php
These two PHP includes provides access to the functions allowing you to manage Yoctopuce
modules. yocto_api.php must always be included, yocto_latitude.php is necessary to
manage modules containing a latitude sensor, such as Yocto-GPS.
yRegisterHub
The yRegisterHub function allows you to indicate on which machine the Yoctopuce modules are
located, more precisely on which machine the VirtualHub software is running. In our case, the
127.0.0.1:4444 address indicates the local machine, port 4444 (the standard port used by
Yoctopuce). You can very well modify this address, and enter the address of another machine on
which the VirtualHub software is running.
yFindLatitude
The yFindLatitude function allows you to find a latitude 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-GPS module with serial number
YGNSSMK1-123456 which you have named "MyModule", and for which you have given the latitude
function the name "MyFunction". The following five calls are strictly equivalent, as long as
"MyFunction" is defined only once.
yFindLatitude returns an object which you can then use at will to control the latitude sensor.
isOnline
The isOnline() method of the object returned by yFindLatitude allows you to know if the
corresponding module is present and in working order.
get_latitude
The get_latitude() method of the object returned by yFindGps provides the latitude currently
measured by the Yocto-GPS. The value returned is a string, the format will vary according to the
Yocto-GPS configuration. To get a floating point value, no matter the configuartion, use the YLatitude
Class.
A real example
Open your preferred text editor4, 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-GPS of
the Yoctopuce library.
In this example, you will recognize the functions explained above, but this time used with all side
materials needed to make it work nicely as a small demo.
4
If you do not have a text editor, use Notepad rather than Microsoft Word.
// Use explicit error handling rather than exceptions//yDisableExceptions();
// Setup the API to use the VirtualHub on local machineif(yRegisterHub('http://127.0.0.1:4444/',$errmsg) != YAPI_SUCCESS){die("Cannot contact VirtualHub on 127.0.0.1");}
@$serial = $_GET['serial'];if($serial != ''){// Check if a specified module is available online
$gps = yFindGps("$serial.gps");if(!$gps->isOnline()){die("Module not connected (check serial and USB cable)");}}else{// or use any connected module suitable for the demo
$gps = yFirstGps();if(is_null($gps)){die("No module connected (check USB cable)");}else{
$serial = $gps->module()->get_serialnumber();}}Print("Module to use: <input name='serial' value='$serial'><br>");
// trigger auto-refresh after one secondPrint("<script language='javascript1.5' type='text/JavaScript'>\n");Print("setTimeout('window.location.reload()',1000);");Print("</script>\n");
?>
</BODY>
</HTML>
8.3. Control of the module part
Each module can be controlled in a similar manner, you can find below a simple sample program
displaying the main parameters of the module and enabling you to activate the localization beacon.
// Use explicit error handling rather than exceptions
yDisableExceptions();
// Setup the API to use the VirtualHub on local machineif(yRegisterHub('http://127.0.0.1:4444/',$errmsg) != YAPI_SUCCESS){die("Cannot contact VirtualHub on 127.0.0.1 : ".$errmsg);}
@$serial = $_GET['serial'];if($serial != ''){
8. Using Yocto-GPS with PHP
www.yoctopuce.com51
// Check if a specified module is available online
$module = yFindModule("$serial");if(!$module->isOnline()){die("Module not connected (check serial and USB cable)");}}else{// or use any connected module suitable for the demo
$module = yFirstModule();if($module){// skip VirtualHub
$module = $module->nextModule();}if(is_null($module)){die("No module connected (check USB cable)");}else{
$serial = $module->get_serialnumber();}}Print("Module to use: <input name='serial' value='$serial'><br>");
Each property xxx of the module can be read thanks to a method of type get_xxxx(), and
properties which are not read-only can be modified with the help of the set_xxx() method. For
more details regarding the used functions, refer to the API chapters.
Changing the module settings
When you want to modify the settings of a module, you only need to call the corresponding
set_xxx() function. However, this modification is performed only in the random access memory
(RAM) of the module: if the module is restarted, the modifications are lost. To memorize them
persistently, it is necessary to ask the module to save its current configuration in its permanent
memory. To do so, use the saveToFlash() method. Inversely, it is possible to force the module to
forget its current settings by using the revertFromFlash() method. The short example below
allows you to modify the logical name of a module.
// Use explicit error handling rather than exceptions
yDisableExceptions();
// Setup the API to use the VirtualHub on local machineif(yRegisterHub('http://127.0.0.1:4444/',$errmsg) != YAPI_SUCCESS){die("Cannot contact VirtualHub on 127.0.0.1");
8. Using Yocto-GPS with PHP
52www.yoctopuce.com
}
@$serial = $_GET['serial'];if($serial != ''){// Check if a specified module is available online
$module = yFindModule("$serial");if(!$module->isOnline()){die("Module not connected (check serial and USB cable)");}}else{// or use any connected module suitable for the demo
$module = yFirstModule();if($module){// skip VirtualHub
$module = $module->nextModule();}if(is_null($module)){die("No module connected (check USB cable)");}else{
$serial = $module->get_serialnumber();}}Print("Module to use: <input name='serial' value='$serial'><br>");
Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this
limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to
the technology employed by the module micro-processor, is located at about 100000 cycles. In short,
you can use the saveToFlash() function only 100000 times in the life of the module. Make sure
you do not call this function within a loop.
Listing the modules
Obtaining the list of the connected modules is performed with the yFirstModule() function which
returns the first module found. Then, you only need to call the nextModule() function of this
object to find the following modules, and this as long as the returned value is not NULL. Below a
short example listing the connected modules.
The PHP library is able to work in a specific mode called HTTP callback Yocto-API. With this mode,
you can control Yoctopuce devices installed behind a NAT filter, such as a DSL router for example,
and this without needing to open a port. The typical application is to control Yoctopuce devices,
located on a private network, from a public web site.
The NAT filter: advantages and disadvantages
A DSL router which translates network addresses (NAT) works somewhat like a private phone
switchboard (a PBX): internal extensions can call each other and call the outside; but seen from the
outside, there is only one official phone number, that of the switchboard itself. You cannot reach the
internal extensions from the outside.
Typical DSL configuration: LAN machines are isolated from the outside by the DSL router
Transposed to the network, we have the following: appliances connected to your home automation
network can communicate with one another using a local IP address (of the 192.168.xxx.yyy type),
and contact Internet servers through their public address. However, seen from the outside, you have
only one official IP address, assigned to the DSL router only, and you cannot reach your network
appliances directly from the outside. It is rather restrictive, but it is a relatively efficient protection
against intrusions.
Responses from request from LAN machines are routed.
8. Using Yocto-GPS with PHP
54www.yoctopuce.com
But requests from the outside are blocked.
Seeing Internet without being seen provides an enormous security advantage. However, this signifies
that you cannot, a priori, set up your own web server at home to control a home automation
installation from the outside. A solution to this problem, advised by numerous home automation
system dealers, consists in providing outside visibility to your home automation server itself, by
adding a routing rule in the NAT configuration of the DSL router. The issue of this solution is that it
exposes the home automation server to external attacks.
The HTTP callback API solves this issue without having to modify the DSL router configuration. The
module control script is located on an external site, and it is the VirtualHub which is in charge of
calling it a regular intervals.
The HTTP callback API uses the VirtualHub which initiates the requests.
Configuration
The callback API thus uses the VirtualHub as a gateway. All the communications are initiated by the
VirtualHub. They are thus outgoing communications and therefore perfectly authorized by the DSL
router.
You must configure the VirtualHub so that it calls the PHP script on a regular basis. To do so:
1. Launch a VirtualHub
2. Access its interface, usually 127.0.0.1:4444
3. Click on the configure button of the line corresponding to the VirtualHub itself
4. Click on the edit button of the Outgoing callbacks section
Click on the "configure" button on the first line
8. Using Yocto-GPS with PHP
www.yoctopuce.com55
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.
Usage
From the programmer standpoint, the only difference is at the level of the yRegisterHub function call.
Instead of using an IP address, you must use the callback string (or http://callback which is
equivalent).
include("yocto_api.php");
yRegisterHub("callback");
The remainder of the code stays strictly identical. On the VirtualHub interface, at the bottom of the
configuration window for the HTTP callback API , there is a button allowing you to test the call to the
PHP script.
Be aware that the PHP script controlling the modules remotely through the HTTP callback API can
be called only by the VirtualHub. Indeed, it requires the information posted by the VirtualHub to
function. To code a web site which controls Yoctopuce modules interactively, you must create a user
interface which stores in a file or in a database the actions to be performed on the Yoctopuce
modules. These actions are then read and run by the control script.
8. Using Yocto-GPS with PHP
56www.yoctopuce.com
Common issues
For the HTTP callback API to work, the PHP option allow_url_fopen must be set. Some web site
hosts do not set it by default. The problem then manifests itself with the following error:
error: URL file-access is disabled in the server configuration
To set this option, you must create, in the repertory where the control PHP script is located, an .htaccess
file containing the following line:
php_flag "allow_url_fopen" "On"
Depending on the security policies of the host, it is sometimes impossible to authorize this option at
the root of the web site, or even to install PHP scripts receiving data from a POST HTTP. In this
case, place the PHP script in a subdirectory.
Limitations
This method that allows you to go through NAT filters cheaply has nevertheless a price.
Communications being initiated by the VirtualHub at a more or less regular interval, reaction time to
an event is clearly longer than if the Yoctopuce modules were driven directly. You can configure the
reaction time in the specific window of the VirtualHub, but it is at least of a few seconds in the best
case.
The HTTP callback Yocto-API mode is currently available in PHP and Node.JS only.
8.5. Error handling
When you implement a program which must interact with USB modules, you cannot disregard error
handling. Inevitably, there will be a time when a user will have unplugged the device, either before
running the software, or even while the software is running. The Yoctopuce library is designed to help
you support this kind of behavior, but your code must nevertheless be conceived to interpret in the
best possible way the errors indicated by the library.
The simplest way to work around the problem is the one used in the short examples provided in this
chapter: before accessing a module, check that it is online with the isOnline function, and then
hope that it will stay so during the fraction of a second necessary for the following code lines to run.
This method is not perfect, but it can be sufficient in some cases. You must however be aware that
you cannot completely exclude an error which would occur after the call to isOnline and which
could crash the software. The only way to prevent this is to implement one of the two error handling
techniques described below.
The method recommended by most programming languages for unpredictable error handling is the
use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while
you try to access a module, the library throws an exception. In this case, there are three possibilities:
• If your code catches the exception and handles it, everything goes well.
• If your program is running in debug mode, you can relatively easily determine where the
problem happened and view the explanatory message linked to the exception.
• Otherwise... the exception makes your program crash, bang!
As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for
error handling, allowing you to create a robust program without needing to catch exceptions at every
line of code. You simply need to call the YAPI.DisableExceptions() function to commute the
library to a mode where exceptions for all the functions are systematically replaced by specific return
values, which can be tested by the caller when necessary. For each function, the name of each
return value in case of error is systematically documented in the library reference. The name always
follows the same logic: a get_state() method returns a Y_STATE_INVALID value, a
get_currentValue method returns a Y_CURRENTVALUE_INVALID value, and so on. In any
case, the returned value is of the expected type and is not a null pointer which would risk crashing
your program. At worst, if you display the value without testing it, it will be outside the expected
8. Using Yocto-GPS with PHP
www.yoctopuce.com57
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.
8. Using Yocto-GPS with PHP
58www.yoctopuce.com
9. Using Yocto-GPS with C++
C++ is not the simplest language to master. However, if you take care to limit yourself to its essential
functionalities, this language can very well be used for short programs quickly coded, and it has the
advantage of being easily ported from one operating system to another. Under Windows, all the
examples and the project models are tested with Microsoft Visual Studio 2010 Express, freely
available on the Microsoft web site1. 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++ libraries2 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.
9.1. Control of the Latitude function
A few lines of code are enough to use a Yocto-GPS. Here is the skeleton of a C++ code snipplet to
use the Latitude function.
// Hot-plug is easy: just check that the device is online
if(latitude->isOnline())
{
// Use latitude->get_currentValue(), ...
}
Let's look at these lines in more details.
yocto_api.h et yocto_latitude.h
These two include files provide access to the functions allowing you to manage Yoctopuce modules.
yocto_api.h must always be used, yocto_latitude.h is necessary to manage modules
containing a latitude sensor, such as Yocto-GPS.
yRegisterHub
The yRegisterHub function initializes the Yoctopuce API and indicates where the modules should
be looked for. When used with the parameter "usb", it will use the modules locally connected to the
computer running the library. If the initialization does not succeed, this function returns a value
different from YAPI_SUCCESS and errmsg contains the error message.
yFindLatitude
The yFindLatitude function allows you to find a latitude 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-GPS module with serial number
YGNSSMK1-123456 which you have named "MyModule", and for which you have given the latitude
function the name "MyFunction". The following five calls are strictly equivalent, as long as
"MyFunction" is defined only once.
yFindLatitude returns an object which you can then use at will to control the latitude sensor.
isOnline
The isOnline() method of the object returned by yFindLatitude allows you to know if the
corresponding module is present and in working order.
get_latitude
The get_latitude() method of the object returned by yFindGps provides the latitude currently
measured by the Yocto-GPS. The value returned is a string, the format will vary according to the
Yocto-GPS configuration. To get a floating point value, no matter the configuartion, use the YLatitude
Class.
A real example
Launch your C++ environment and open the corresponding sample project provided in the directory
Examples/Doc-GettingStarted-Yocto-GPS 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.
while(1){if(!gps->isOnline()){cout << "Module not connected (check identification and USB cable)";break;
}if(!gps->get_isFixed()){cout << "Fixing.." << endl;
}else{cout << gps->get_latitude() << " " << gps->get_longitude() << endl;
}cout << " (press Ctrl-C to exit)" << endl;
ySleep(1000, errmsg);}
yFreeAPI();return0;
}
9.2. Control of the module part
Each module can be controlled in a similar manner, you can find below a simple sample program
displaying the main parameters of the module and enabling you to activate the localization beacon.
Each property xxx of the module can be read thanks to a method of type get_xxxx(), and
properties which are not read-only can be modified with the help of the set_xxx() method. For
more details regarding the used functions, refer to the API chapters.
Changing the module settings
When you want to modify the settings of a module, you only need to call the corresponding
set_xxx() function. However, this modification is performed only in the random access memory
(RAM) of the module: if the module is restarted, the modifications are lost. To memorize them
persistently, it is necessary to ask the module to save its current configuration in its permanent
memory. To do so, use the saveToFlash() method. Inversely, it is possible to force the module to
forget its current settings by using the revertFromFlash() method. The short example below
allows you to modify the logical name of a module.
Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this
limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to
the technology employed by the module micro-processor, is located at about 100000 cycles. In short,
you can use the saveToFlash() function only 100000 times in the life of the module. Make sure
you do not call this function within a loop.
Listing the modules
Obtaining the list of the connected modules is performed with the yFirstModule() function which
returns the first module found. Then, you only need to call the nextModule() function of this
object to find the following modules, and this as long as the returned value is not NULL. Below a
short example listing the connected modules.
#include <iostream>
#include "yocto_api.h"
usingnamespace std;
int main(int argc, constchar * argv[])
{
string errmsg;
// Setup the API to use local USB devicesif(YAPI::RegisterHub("usb", errmsg) != YAPI_SUCCESS){cerr << "RegisterHub error: " << errmsg << endl;
return1;
}
When you implement a program which must interact with USB modules, you cannot disregard error
handling. Inevitably, there will be a time when a user will have unplugged the device, either before
running the software, or even while the software is running. The Yoctopuce library is designed to help
you support this kind of behavior, but your code must nevertheless be conceived to interpret in the
best possible way the errors indicated by the library.
The simplest way to work around the problem is the one used in the short examples provided in this
chapter: before accessing a module, check that it is online with the isOnline function, and then
hope that it will stay so during the fraction of a second necessary for the following code lines to run.
This method is not perfect, but it can be sufficient in some cases. You must however be aware that
you cannot completely exclude an error which would occur after the call to isOnline and which
could crash the software. The only way to prevent this is to implement one of the two error handling
techniques described below.
The method recommended by most programming languages for unpredictable error handling is the
use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while
you try to access a module, the library throws an exception. In this case, there are three possibilities:
• If your code catches the exception and handles it, everything goes well.
• If your program is running in debug mode, you can relatively easily determine where the
problem happened and view the explanatory message linked to the exception.
• Otherwise... the exception makes your program crash, bang!
As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for
error handling, allowing you to create a robust program without needing to catch exceptions at every
line of code. You simply need to call the YAPI.DisableExceptions() function to commute the
library to a mode where exceptions for all the functions are systematically replaced by specific return
values, which can be tested by the caller when necessary. For each function, the name of each
return value in case of error is systematically documented in the library reference. The name always
follows the same logic: a get_state() method returns a Y_STATE_INVALID value, a
get_currentValue method returns a Y_CURRENTVALUE_INVALID value, and so on. In any
case, the returned value is of the expected type and is not a null pointer which would risk crashing
your program. At worst, if you display the value without testing it, it will be outside the expected
bounds for the returned value. In the case of functions which do not normally return information, the
return value is YAPI_SUCCESS if everything went well, and a different error code in case of failure.
When you work without exceptions, you can obtain an error code and an error message explaining
the source of the error. You can request them from the object which returned the error, calling the
errType() and errMessage() methods. Their returned values contain the same information as
in the exceptions when they are active.
9.4. Integration variants for the C++ Yoctopuce library
Depending on your needs and on your preferences, you can integrate the library into your projects in
several distinct manners. This section explains how to implement the different options.
Integration in source format
Integrating all the sources of the library into your projects has several advantages:
• It guaranties the respect of the compilation conventions of your project (32/64 bits, inclusion of
debugging symbols, unicode or ASCII characters, etc.);
• It facilitates debugging if you are looking for the cause of a problem linked to the Yoctopuce
library;
• It reduces the dependencies on third party components, for example in the case where you
would need to recompile this project for another architecture in many years;
• It does not require the installation of a dynamic library specific to Yoctopuce on the final
system, everything is in the executable.
9. Using Yocto-GPS with C++
64www.yoctopuce.com
To integrate the source code, the easiest way is to simply include the Sources directory of your
Yoctopuce library into your IncludePath, and to add all the files of this directory (including the subdirectory yapi) to your project.
For your project to build correctly, you need to link with your project the prerequisite system libraries,
that is:
• For Windows: the libraries are added automatically
• For Mac OS X: IOKit.framework and CoreFoundation.framework
• For Linux: libm, libpthread, libusb1.0, and libstdc++
Integration as a static library
Integration of the Yoctopuce library as a static library is a simpler manner to build a small executable
which uses Yoctopuce modules. You can quickly compile the program with a single command. You
do not need to install a dynamic library specific to Yoctopuce, everything is in the executable.
To integrate the static Yoctopuce library to your project, you must include the Sources directory of
the Yoctopuce library into your IncludePath, and add the sub-directory Binaries/...
corresponding to your operating system into your libPath.
Then, for you project to build correctly, you need to link with your project the Yoctopuce library and
the prerequisite system libraries:
• For Windows: yocto-static.lib
• For Mac OS X: libyocto-static.a, IOKit.framework, and CoreFoundation.framework
• For Linux: libyocto-static.a, libm, libpthread, libusb1.0, and libstdc++.
Note, under Linux, if you wish to compile in command line with GCC, it is generally advisable to link
system libraries as dynamic libraries, rather than as static ones. To mix static and dynamic libraries
on the same command line, you must pass the following arguments:
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:
• For Windows: yocto.lib
• For Mac OS X: libyocto, IOKit.framework, and CoreFoundation.framework
• For Linux: libyocto, libm, libpthread, libusb1.0, and libstdc++.
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 libraries1 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 example2 with video
shots showing how to integrate the library into your projects.
10.1. Control of the Latitude function
Launch Xcode 4.2 and open the corresponding sample project provided in the directory Examples/
Doc-GettingStarted-Yocto-GPS of the Yoctopuce library.
@autoreleasepool{// Setup the API to use local USB devicesif([YAPI RegisterHub:@"usb": &error] != YAPI_SUCCESS){NSLog(@"RegisterHub error: %@", [error localizedDescription]);return1;
}NSString *target = [NSString stringWithUTF8String:argv[1]];
YGps *gps;
if([target isEqualToString:@"any"]){
gps = [YGps FirstGps];if(gps == NULL){NSLog(@"No module connected (check USB cable)");return1;
}}else{
gps = [YGps FindGps:[target stringByAppendingString:@".gps"]];}
while(1){if(![gps isOnline]){NSLog(@"Module not connected (check identification and USB cable)\n");break;
}if([gps get_isFixed] != Y_ISFIXED_TRUE){NSLog(@"fixing");}else{NSLog(@"%@ %@ \n", [gps get_latitude], [gps get_longitude]);}
NSLog(@" (press Ctrl-C to exit)\n");[YAPI Sleep:1000:NULL];
}[YAPI FreeAPI];}return0;
}
There are only a few really important lines in this example. We will look at them in details.
yocto_api.h et yocto_latitude.h
These two import files provide access to the functions allowing you to manage Yoctopuce modules.
yocto_api.h must always be used, yocto_latitude.h is necessary to manage modules
containing a latitude sensor, such as Yocto-GPS.
[YAPI RegisterHub]
The [YAPI RegisterHub] function initializes the Yoctopuce API and indicates where the
modules should be looked for. When used with the parameter @"usb", it will use the modules
locally connected to the computer running the library. If the initialization does not succeed, this
function returns a value different from YAPI_SUCCESS and errmsg contains the error message.
[Latitude FindLatitude]
The [Latitude FindLatitude] function allows you to find a latitude 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-GPS module with serial number
YGNSSMK1-123456 which you have named "MyModule", and for which you have given the latitude
function the name "MyFunction". The following five calls are strictly equivalent, as long as
"MyFunction" is defined only once.
[Latitude FindLatitude] returns an object which you can then use at will to control the
latitude sensor.
isOnline
The isOnline method of the object returned by [Latitude FindLatitude] allows you to
know if the corresponding module is present and in working order.
get_latitude
The get_latitude() method of the object returned by YGps.FindGps provides the latitude
currently measured by the Yocto-GPS. The value returned is a string, the format will vary according
to the Yocto-GPS configuration. To get a floating point value, no matter the configuartion, use the
YLatitude Class.
10.2. Control of the module part
Each module can be controlled in a similar manner, you can find below a simple sample program
displaying the main parameters of the module and enabling you to activate the localization beacon.
NSLog(@"usage: %s <serial or logical name> [ON/OFF]\n", exe);exit(1);
}
int main (int argc, constchar * argv[])
{
NSError *error;
@autoreleasepool{// Setup the API to use local USB devicesif([YAPI RegisterHub:@"usb": &error] != YAPI_SUCCESS){NSLog(@"RegisterHub error: %@", [error localizedDescription]);return1;
}if(argc < 2)
usage(argv[0]);NSString *serial_or_name = [NSString stringWithUTF8String:argv[1]];// use serial or logical name
YModule *module = [YModule FindModule:serial_or_name];if([module isOnline]){if(argc > 2){if(strcmp(argv[2], "ON") == 0)[module setBeacon:Y_BEACON_ON];else[module setBeacon:Y_BEACON_OFF];}NSLog(@"serial: %@\n", [module serialNumber]);NSLog(@"logical name: %@\n", [module logicalName]);NSLog(@"luminosity: %d\n", [module luminosity]);NSLog(@"beacon: ");if([module beacon] == Y_BEACON_ON)NSLog(@"ON\n");elseNSLog(@"OFF\n");NSLog(@"upTime: %ld sec\n", [module upTime] / 1000);NSLog(@"USB current: %d mA\n", [module usbCurrent]);NSLog(@"logs: %@\n", [module get_lastLogs]);}else{NSLog(@"%@ not connected (check identification and USB cable)\n",
serial_or_name);}[YAPI FreeAPI];}return0;
10. Using Yocto-GPS with Objective-C
www.yoctopuce.com69
}
Each property xxx of the module can be read thanks to a method of type get_xxxx, and
properties which are not read-only can be modified with the help of the set_xxx: method. For
more details regarding the used functions, refer to the API chapters.
Changing the module settings
When you want to modify the settings of a module, you only need to call the corresponding
set_xxx: function. However, this modification is performed only in the random access memory
(RAM) of the module: if the module is restarted, the modifications are lost. To memorize them
persistently, it is necessary to ask the module to save its current configuration in its permanent
memory. To do so, use the saveToFlash method. Inversely, it is possible to force the module to
forget its current settings by using the revertFromFlash method. The short example below
allows you to modify the logical name of a module.
@autoreleasepool{// Setup the API to use local USB devicesif([YAPI RegisterHub:@"usb" :&error] != YAPI_SUCCESS){NSLog(@"RegisterHub error: %@", [error localizedDescription]);return1;
}
if(argc < 2)
usage(argv[0]);
NSString *serial_or_name = [NSString stringWithUTF8String:argv[1]];// use serial or logical name
YModule *module = [YModule FindModule:serial_or_name];
if(module.isOnline){if(argc >= 3){NSString *newname = [NSString stringWithUTF8String:argv[2]];if(![YAPI CheckLogicalName:newname]){NSLog(@"Invalid name (%@)\n", newname);
usage(argv[0]);}
module.logicalName = newname;
[module saveToFlash];}NSLog(@"Current name: %@\n", module.logicalName);}else{NSLog(@"%@ not connected (check identification and USB cable)\n",
serial_or_name);}[YAPI FreeAPI];}return0;
}
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.
10. Using Yocto-GPS with Objective-C
70www.yoctopuce.com
Listing the modules
Obtaining the list of the connected modules is performed with the yFirstModule() function which
returns the first module found. Then, you only need to call the nextModule() function of this
object to find the following modules, and this as long as the returned value is not NULL. Below a
short example listing the connected modules.
@autoreleasepool{// Setup the API to use local USB devicesif([YAPI RegisterHub:@"usb" :&error] != YAPI_SUCCESS){NSLog(@"RegisterHub error: %@\n", [error localizedDescription]);return1;
}
When you implement a program which must interact with USB modules, you cannot disregard error
handling. Inevitably, there will be a time when a user will have unplugged the device, either before
running the software, or even while the software is running. The Yoctopuce library is designed to help
you support this kind of behavior, but your code must nevertheless be conceived to interpret in the
best possible way the errors indicated by the library.
The simplest way to work around the problem is the one used in the short examples provided in this
chapter: before accessing a module, check that it is online with the isOnline function, and then
hope that it will stay so during the fraction of a second necessary for the following code lines to run.
This method is not perfect, but it can be sufficient in some cases. You must however be aware that
you cannot completely exclude an error which would occur after the call to isOnline and which
could crash the software. The only way to prevent this is to implement one of the two error handling
techniques described below.
The method recommended by most programming languages for unpredictable error handling is the
use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while
you try to access a module, the library throws an exception. In this case, there are three possibilities:
• If your code catches the exception and handles it, everything goes well.
• If your program is running in debug mode, you can relatively easily determine where the
problem happened and view the explanatory message linked to the exception.
• Otherwise... the exception makes your program crash, bang!
As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for
error handling, allowing you to create a robust program without needing to catch exceptions at every
line of code. You simply need to call the YAPI.DisableExceptions() function to commute the
library to a mode where exceptions for all the functions are systematically replaced by specific return
values, which can be tested by the caller when necessary. For each function, the name of each
return value in case of error is systematically documented in the library reference. The name always
follows the same logic: a get_state() method returns a Y_STATE_INVALID value, a
10. Using Yocto-GPS with Objective-C
www.yoctopuce.com71
get_currentValue method returns a Y_CURRENTVALUE_INVALID value, and so on. In any
case, the returned value is of the expected type and is not a null pointer which would risk crashing
your program. At worst, if you display the value without testing it, it will be outside the expected
bounds for the returned value. In the case of functions which do not normally return information, the
return value is YAPI_SUCCESS if everything went well, and a different error code in case of failure.
When you work without exceptions, you can obtain an error code and an error message explaining
the source of the error. You can request them from the object which returned the error, calling the
errType() and errMessage() methods. Their returned values contain the same information as
in the exceptions when they are active.
10. Using Yocto-GPS with Objective-C
72www.yoctopuce.com
11. Using Yocto-GPS with Visual Basic .NET
VisualBasic has long been the most favored entrance path to the Microsoft world. Therefore, we had
to provide our library for this language, even if the new trend is shifting to C#. All the examples and
the project models are tested with Microsoft VisualBasic 2010 Express, freely available on the
Microsoft web site1.
11.1. Installation
Download the Visual Basic Yoctopuce library from the Yoctopuce web site2. 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.
11.2. Using the Yoctopuce API in a Visual Basic project
The Visual Basic.NET Yoctopuce library is composed of a DLL and of source files in Visual Basic.
The DLL is not a .NET DLL, but a classic DLL, written in C, which manages the low level
communications with the modules3. The source files in Visual Basic manage the high level part of the
API. Therefore, your need both this DLL and the .vb files of the sources directory to create a
project managing Yoctopuce modules.
Configuring a Visual Basic project
The following indications are provided for Visual Studio Express 2010, but the process is similar for
other versions. Start by creating your project. Then, on the 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.
The sources of this DLL are available in the C++ API
www.yoctopuce.com73
Then add in the same manner the yapi.dll DLL, located in the Sources/dll directory4. 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.
11.3. Control of the Latitude function
A few lines of code are enough to use a Yocto-GPS. Here is the skeleton of a Visual Basic code
snipplet to use the Latitude function.
[...]
Dim errmsg AsString errmsg
Dim latitude As YLatitude
REM Get access to your device, connected locally on USB for instance
yRegisterHub("usb", errmsg)
latitude = yFindLatitude("YGNSSMK1-123456.latitude")
REM Hot-plug is easy: just check that the device is online
If(latitude.isOnline())Then
REM Use latitude.get_currentValue(), ...
EndIf
Let's look at these lines in more details.
yRegisterHub
The yRegisterHub function initializes the Yoctopuce API and indicates where the modules should
be looked for. When used with the parameter "usb", it will use the modules locally connected to the
computer running the library. If the initialization does not succeed, this function returns a value
different from YAPI_SUCCESS and errmsg contains the error message.
yFindLatitude
The yFindLatitude function allows you to find a latitude 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-GPS module with serial number
YGNSSMK1-123456 which you have named "MyModule", and for which you have given the latitude
function the name "MyFunction". The following five calls are strictly equivalent, as long as
"MyFunction" is defined only once.
latitude = yFindLatitude("YGNSSMK1-123456.latitude")
latitude = yFindLatitude("YGNSSMK1-123456.MyFunction")
latitude = yFindLatitude("MyModule.latitude")
latitude = yFindLatitude("MyModule.MyFunction")
latitude = yFindLatitude("MyFunction")
yFindLatitude returns an object which you can then use at will to control the latitude sensor.
isOnline
The isOnline() method of the object returned by yFindLatitude allows you to know if the
corresponding module is present and in working order.
get_latitude
The get_latitude() method of the object returned by yFindGps provides the latitude currently
measured by the Yocto-GPS. The value returned is a string, the format will vary according to the
4
Remember to change the filter of the selection window, otherwise the DLL will not show.
11. Using Yocto-GPS with Visual Basic .NET
74www.yoctopuce.com
Yocto-GPS configuration. To get a floating point value, no matter the configuartion, use the YLatitude
Class.
A real example
Launch Microsoft VisualBasic and open the corresponding sample project provided in the directory
Examples/Doc-GettingStarted-Yocto-GPS 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.
Sub Main()Dim argv()AsString = System.Environment.GetCommandLineArgs()Dim errmsg AsString = ""Dim target AsStringDim gps As YGps
If argv.Length < 2Then Usage()
target = argv(1)REM Setup the API to use local USB devicesIf(yRegisterHub("usb", errmsg) <> YAPI_SUCCESS)ThenConsole.WriteLine("RegisterHub error: " + errmsg)EndEndIf
If target = "any"Then
gps = yFirstGps()
If gps IsNothingThenConsole.WriteLine("No module connected (check USB cable) ")EndEndIfElse
gps = yFindGps(target + ".gps")EndIf
While(True)IfNot(gps.isOnline())ThenConsole.WriteLine("Module not connected (check identification and USB cable)")EndEndIfIf(gps.get_isFixed() <> YGps.ISFIXED_TRUE)ThenConsole.WriteLine("Fixing...")ElseConsole.WriteLine(gps.get_latitude() + " " + gps.get_longitude())EndIfConsole.WriteLine(" (press Ctrl-C to exit)")
ySleep(1000, errmsg)EndWhile
yFreeAPI()EndSub
EndModule
11.4. Control of the module part
Each module can be controlled in a similar manner, you can find below a simple sample program
displaying the main parameters of the module and enabling you to activate the localization beacon.
11. Using Yocto-GPS with Visual Basic .NET
www.yoctopuce.com75
ImportsSystem.IO
ImportsSystem.Environment
Module Module1
Sub usage()Console.WriteLine("usage: demo <serial or logical name> [ON/OFF]")EndEndSub
Sub Main()Dim argv()AsString = System.Environment.GetCommandLineArgs()Dim errmsg AsString = ""Dim m As ymodule
m = yFindModule(argv(1))REM use serial or logical nameIf(m.isOnline())ThenIf argv.Length > 2ThenIf argv(2) = "ON"Then m.set_beacon(Y_BEACON_ON)If argv(2) = "OFF"Then m.set_beacon(Y_BEACON_OFF)EndIfConsole.WriteLine("serial: " + m.get_serialNumber())Console.WriteLine("logical name: " + m.get_logicalName())Console.WriteLine("luminosity: " + Str(m.get_luminosity()))Console.Write("beacon: ")If(m.get_beacon() = Y_BEACON_ON)ThenConsole.WriteLine("ON")ElseConsole.WriteLine("OFF")EndIfConsole.WriteLine("upTime: " + Str(m.get_upTime() / 1000) + " sec")Console.WriteLine("USB current: " + Str(m.get_usbCurrent()) + " mA")Console.WriteLine("Logs:")Console.WriteLine(m.get_lastLogs())ElseConsole.WriteLine(argv(1) + " not connected (check identification and USB cable)")EndIf
yFreeAPI()EndSub
EndModule
Each property xxx of the module can be read thanks to a method of type get_xxxx(), and
properties which are not read-only can be modified with the help of the set_xxx() method. For
more details regarding the used functions, refer to the API chapters.
Changing the module settings
When you want to modify the settings of a module, you only need to call the corresponding
set_xxx() function. However, this modification is performed only in the random access memory
(RAM) of the module: if the module is restarted, the modifications are lost. To memorize them
persistently, it is necessary to ask the module to save its current configuration in its permanent
memory. To do so, use the saveToFlash() method. Inversely, it is possible to force the module to
forget its current settings by using the revertFromFlash() method. The short example below
allows you to modify the logical name of a module.
Module Module1
Sub usage()
Console.WriteLine("usage: demo <serial or logical name> <new logical name>")EndEndSub
Sub Main()
11. Using Yocto-GPS with Visual Basic .NET
76www.yoctopuce.com
Dim argv()AsString = System.Environment.GetCommandLineArgs()Dim errmsg AsString = ""Dim newname AsStringDim m As YModule
If(argv.Length <> 3)Then usage()
REM Setup the API to use local USB devicesIf yRegisterHub("usb", errmsg) <> YAPI_SUCCESS ThenConsole.WriteLine("RegisterHub error: " + errmsg)EndEndIf
m = yFindModule(argv(1))REM use serial or logical nameIf m.isOnline()Then
newname = argv(2)If(Not yCheckLogicalName(newname))ThenConsole.WriteLine("Invalid name (" + newname + ")")EndEndIf
m.set_logicalName(newname)
m.saveToFlash()REM do not forget thisConsole.Write("Module: serial= " + m.get_serialNumber)Console.Write(" / name= " + m.get_logicalName())ElseConsole.Write("not connected (check identification and USB cable")EndIf
yFreeAPI()
EndSub
EndModule
Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this
limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to
the technology employed by the module micro-processor, is located at about 100000 cycles. In short,
you can use the saveToFlash() function only 100000 times in the life of the module. Make sure
you do not call this function within a loop.
Listing the modules
Obtaining the list of the connected modules is performed with the yFirstModule() function which
returns the first module found. Then, you only need to call the nextModule() function of this
object to find the following modules, and this as long as the returned value is not Nothing. Below a
short example listing the connected modules.
Module Module1
Sub Main()Dim M As ymodule
Dim errmsg AsString = ""
REM Setup the API to use local USB devicesIf yRegisterHub("usb", errmsg) <> YAPI_SUCCESS ThenConsole.WriteLine("RegisterHub error: " + errmsg)EndEndIf
Console.WriteLine("Device list")
M = yFirstModule()While M IsNotNothingConsole.WriteLine(M.get_serialNumber() + " (" + M.get_productName() + ")")
M = M.nextModule()EndWhile
yFreeAPI()EndSub
EndModule
11. Using Yocto-GPS with Visual Basic .NET
www.yoctopuce.com77
11.5. Error handling
When you implement a program which must interact with USB modules, you cannot disregard error
handling. Inevitably, there will be a time when a user will have unplugged the device, either before
running the software, or even while the software is running. The Yoctopuce library is designed to help
you support this kind of behavior, but your code must nevertheless be conceived to interpret in the
best possible way the errors indicated by the library.
The simplest way to work around the problem is the one used in the short examples provided in this
chapter: before accessing a module, check that it is online with the isOnline function, and then
hope that it will stay so during the fraction of a second necessary for the following code lines to run.
This method is not perfect, but it can be sufficient in some cases. You must however be aware that
you cannot completely exclude an error which would occur after the call to isOnline and which
could crash the software. The only way to prevent this is to implement one of the two error handling
techniques described below.
The method recommended by most programming languages for unpredictable error handling is the
use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while
you try to access a module, the library throws an exception. In this case, there are three possibilities:
• If your code catches the exception and handles it, everything goes well.
• If your program is running in debug mode, you can relatively easily determine where the
problem happened and view the explanatory message linked to the exception.
• Otherwise... the exception makes your program crash, bang!
As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for
error handling, allowing you to create a robust program without needing to catch exceptions at every
line of code. You simply need to call the YAPI.DisableExceptions() function to commute the
library to a mode where exceptions for all the functions are systematically replaced by specific return
values, which can be tested by the caller when necessary. For each function, the name of each
return value in case of error is systematically documented in the library reference. The name always
follows the same logic: a get_state() method returns a Y_STATE_INVALID value, a
get_currentValue method returns a Y_CURRENTVALUE_INVALID value, and so on. In any
case, the returned value is of the expected type and is not a null pointer which would risk crashing
your program. At worst, if you display the value without testing it, it will be outside the expected
bounds for the returned value. In the case of functions which do not normally return information, the
return value is YAPI_SUCCESS if everything went well, and a different error code in case of failure.
When you work without exceptions, you can obtain an error code and an error message explaining
the source of the error. You can request them from the object which returned the error, calling the
errType() and errMessage() methods. Their returned values contain the same information as
in the exceptions when they are active.
11. Using Yocto-GPS with Visual Basic .NET
78www.yoctopuce.com
12. Using Yocto-GPS with C#
C# (pronounced C-Sharp) is an object-oriented programming language promoted by Microsoft, it is
somewhat similar to Java. Like Visual-Basic and Delphi, it allows you to create Windows applications
quite easily. All the examples and the project models are tested with Microsoft C# 2010 Express,
freely available on the Microsoft web site1.
12.1. Installation
Download the Visual C# Yoctopuce library from the Yoctopuce web site2. 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.
12.2. Using the Yoctopuce API in a Visual C# project
The Visual C#.NET Yoctopuce library is composed of a DLL and of source files in Visual C#. The
DLL is not a .NET DLL, but a classic DLL, written in C, which manages the low level communications
with the modules3. The source files in Visual C# manage the high level part of the API. Therefore,
your need both this DLL and the .cs files of the sources directory to create a project managing
Yoctopuce modules.
Configuring a Visual C# project
The following indications are provided for Visual Studio Express 2010, but the process is similar for
other versions. Start by creating your project. Then, on the Solution Explorer panel, right 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.
The sources of this DLL are available in the C++ API
www.yoctopuce.com79
Then add in the same manner the yapi.dll DLL, located in the Sources/dll directory4. Then,
from the Solution Explorer window, right click on the DLL, select Properties and in the Properties
panel, set the Copy to output folder to always. You are now ready to use your Yoctopuce modules
from Visual Studio.
In order to keep them simple, all the examples provided in this documentation are console
applications. Naturally, the libraries function in a strictly identical manner if you integrate them in an
application with a graphical interface.
12.3. Control of the Latitude function
A few lines of code are enough to use a Yocto-GPS. Here is the skeleton of a C# code snipplet to
use the Latitude function.
[...]
string errmsg ="";
YLatitude latitude;
// Get access to your device, connected locally on USB for instance
YAPI.RegisterHub("usb", errmsg);
latitude = YLatitude.FindLatitude("YGNSSMK1-123456.latitude");
// Hot-plug is easy: just check that the device is online
if(latitude.isOnline())
{// Use latitude.get_currentValue(); ...}
Let's look at these lines in more details.
YAPI.RegisterHub
The YAPI.RegisterHub function initializes the Yoctopuce API and indicates where the modules
should be looked for. When used with the parameter "usb", it will use the modules locally
connected to the computer running the library. If the initialization does not succeed, this function
returns a value different from YAPI.SUCCESS and errmsg contains the error message.
YLatitude.FindLatitude
The YLatitude.FindLatitude function allows you to find a latitude 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-GPS module with serial number
YGNSSMK1-123456 which you have named "MyModule", and for which you have given the latitude
function the name "MyFunction". The following five calls are strictly equivalent, as long as
"MyFunction" is defined only once.
latitude = YLatitude.FindLatitude("YGNSSMK1-123456.latitude");
latitude = YLatitude.FindLatitude("YGNSSMK1-123456.MyFunction");
latitude = YLatitude.FindLatitude("MyModule.latitude");
latitude = YLatitude.FindLatitude("MyModule.MyFunction");
latitude = YLatitude.FindLatitude("MyFunction");
YLatitude.FindLatitude returns an object which you can then use at will to control the
latitude sensor.
isOnline
The isOnline() method of the object returned by YLatitude.FindLatitude allows you to
know if the corresponding module is present and in working order.
4
Remember to change the filter of the selection window, otherwise the DLL will not show.
12. Using Yocto-GPS with C#
80www.yoctopuce.com
get_latitude
The get_latitude() method of the object returned by YGps.FindGps provides the latitude
currently measured by the Yocto-GPS. The value returned is a string, the format will vary according
to the Yocto-GPS configuration. To get a floating point value, no matter the configuartion, use the
YLatitude Class.
A real example
Launch Microsoft Visual C# and open the corresponding sample project provided in the directory
Examples/Doc-GettingStarted-Yocto-GPS 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.
// Setup the API to use local USB devicesif(YAPI.RegisterHub("usb", ref errmsg) != YAPI.SUCCESS){Console.WriteLine("RegisterHub error: " + errmsg);
Environment.Exit(0);
}
if(!gps.isOnline()){Console.WriteLine("Module not connected (check identification and USB cable)");
Environment.Exit(0);
}while(gps.isOnline()){if(gps.get_isFixed() != YGps.ISFIXED_TRUE)Console.WriteLine("fixing... ");
elseConsole.WriteLine(gps.get_latitude() + " " + gps.get_longitude());
Console.WriteLine(" (press Ctrl-C to exit)");
YAPI.Sleep(1000, ref errmsg);}
12. Using Yocto-GPS with C#
www.yoctopuce.com81
YAPI.FreeAPI();}}
}
12.4. Control of the module part
Each module can be controlled in a similar manner, you can find below a simple sample program
displaying the main parameters of the module and enabling you to activate the localization beacon.
}else{Console.WriteLine(args[0] + " not connected (check identification and USB cable)");
}
YAPI.FreeAPI();}}
}
12. Using Yocto-GPS with C#
82www.yoctopuce.com
Each property xxx of the module can be read thanks to a method of type YModule.get_xxxx(),
and properties which are not read-only can be modified with the help of the YModule.set_xxx()
method. For more details regarding the used functions, refer to the API chapters.
Changing the module settings
When you want to modify the settings of a module, you only need to call the corresponding
YModule.set_xxx() function. However, this modification is performed only in the random access
memory (RAM) of the module: if the module is restarted, the modifications are lost. To memorize
them persistently, it is necessary to ask the module to save its current configuration in its permanent
memory. To do so, use the YModule.saveToFlash() method. Inversely, it is possible to force
the module to forget its current settings by using the YModule.revertFromFlash() method.
The short example below allows you to modify the logical name of a module.
m.set_logicalName(newname);
m.saveToFlash(); // do not forget this
Console.Write("Module: serial= " + m.get_serialNumber());
Console.WriteLine(" / name= " + m.get_logicalName());
}else{Console.Write("not connected (check identification and USB cable");
}
YAPI.FreeAPI();}}
}
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.
12. Using Yocto-GPS with C#
www.yoctopuce.com83
Listing the modules
Obtaining the list of the connected modules is performed with the YModule.yFirstModule()
function which returns the first module found. Then, you only need to call the nextModule()
function of this object to find the following modules, and this as long as the returned value is not
null. Below a short example listing the connected modules.
Console.WriteLine("Device list");
m = YModule.FirstModule();while(m != null){Console.WriteLine(m.get_serialNumber() + " (" + m.get_productName() + ")");
m = m.nextModule();}
YAPI.FreeAPI();}}
}
12.5. Error handling
When you implement a program which must interact with USB modules, you cannot disregard error
handling. Inevitably, there will be a time when a user will have unplugged the device, either before
running the software, or even while the software is running. The Yoctopuce library is designed to help
you support this kind of behavior, but your code must nevertheless be conceived to interpret in the
best possible way the errors indicated by the library.
The simplest way to work around the problem is the one used in the short examples provided in this
chapter: before accessing a module, check that it is online with the isOnline function, and then
hope that it will stay so during the fraction of a second necessary for the following code lines to run.
This method is not perfect, but it can be sufficient in some cases. You must however be aware that
you cannot completely exclude an error which would occur after the call to isOnline and which
could crash the software. The only way to prevent this is to implement one of the two error handling
techniques described below.
The method recommended by most programming languages for unpredictable error handling is the
use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while
you try to access a module, the library throws an exception. In this case, there are three possibilities:
• If your code catches the exception and handles it, everything goes well.
• If your program is running in debug mode, you can relatively easily determine where the
problem happened and view the explanatory message linked to the exception.
• Otherwise... the exception makes your program crash, bang!
As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for
error handling, allowing you to create a robust program without needing to catch exceptions at every
line of code. You simply need to call the YAPI.DisableExceptions() function to commute the
library to a mode where exceptions for all the functions are systematically replaced by specific return
12. Using Yocto-GPS with C#
84www.yoctopuce.com
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.
12. Using Yocto-GPS with C#
www.yoctopuce.com85
86www.yoctopuce.com
13. Using Yocto-GPS with Delphi
Delphi is a descendent of Turbo-Pascal. Originally, Delphi was produced by Borland, Embarcadero
now edits it. The strength of this language resides in its ease of use, as anyone with some notions of
the Pascal language can develop a Windows application in next to no time. Its only disadvantage is
to cost something1.
Delphi libraries are provided not as VCL components, but directly as source files. These files are
compatible with most Delphi versions.
2
To keep them simple, all the examples provided in this documentation are console applications.
Obviously, the libraries work in a strictly identical way with VCL applications.
You will soon notice that the Delphi API defines many functions which return objects. You do not
need to deallocate these objects yourself, the API does it automatically at the end of the application.
13.1. Preparation
Go to the Yoctopuce web site and download the Yoctopuce Delphi libraries3. Uncompress everything
in a directory of your choice, add the subdirectory sources in the list of directories of Delphi libraries.
4
By default, the Yoctopuce Delphi library uses the yapi.dll DLL, all the applications you will create with
Delphi must have access to this DLL. The simplest way to ensure this is to make sure yapi.dll is
located in the same directory as the executable file of your application.
13.2. Control of the Latitude function
Launch your Delphi environment, copy the yapi.dll DLL in a directory, create a new console
application in the same directory, and copy-paste the piece of code below:
program helloworld;
{$APPTYPE CONSOLE}
uses
SysUtils,
Windows,
yocto_api,
yocto_gps;
1
Actually, Borland provided free versions (for personal use) of Delphi 2006 and 2007. Look for them on the Internet, you
may still be able to download them.
2
Delphi libraries are regularly tested with Delphi 5 and Delphi XE2.
3
www.yoctopuce.com/EN/libraries.php
4
Use the Tools / Environment options menu.
www.yoctopuce.com87
Procedure Usage();
var
exe : string;
begin
exe:= ExtractFileName(paramstr(0));WriteLn(exe+' <serial_number>');WriteLn(exe+' <logical_name>');WriteLn(exe+' any');halt;
End;
var
gps : TYGps;
errmsg : string;
done : boolean;
begin
if(paramcount<1)then usage();
// Setup the API to use local USB devicesif yRegisterHub('usb', errmsg)<>YAPI_SUCCESS thenbeginWrite('RegisterHub error: '+errmsg);exit;
end;
ifparamstr(1)='any'thenbegin// try to find the first temperature gps available
gps := yFirstGps();if gps=nilthenbeginwriteln('No module connected (check USB cable)');halt;
endendelse// or use the one specified on the commande line
gps:= YFindGps(paramstr(1)+'.temperature');
Writeln(' (press Ctrl-C to exit)');Sleep(1000);endelsebeginWriteln('Module not connected (check identification and USB cable)');
done := true;
end;
until done;
yFreeAPI();
end.
There are only a few really important lines in this sample example. We will look at them in details.
yocto_api and yocto_latitude
These two units provide access to the functions allowing you to manage Yoctopuce modules.
yocto_api must always be used, yocto_latitude is necessary to manage modules containing
a latitude sensor, such as Yocto-GPS.
13. Using Yocto-GPS with Delphi
88www.yoctopuce.com
yRegisterHub
The yRegisterHub function initializes the Yoctopuce API and specifies where the modules should
be looked for. When used with the parameter 'usb', it will use the modules locally connected to the
computer running the library. If the initialization does not succeed, this function returns a value
different from YAPI_SUCCESS and errmsg contains the error message.
yFindLatitude
The yFindLatitude function allows you to find a latitude 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-GPS module with serial number
YGNSSMK1-123456 which you have named "MyModule", and for which you have given the latitude
function the name "MyFunction". The following five calls are strictly equivalent, as long as
"MyFunction" is defined only once.
latitude := yFindLatitude("YGNSSMK1-123456.latitude");
latitude := yFindLatitude("YGNSSMK1-123456.MyFunction");
latitude := yFindLatitude("MyModule.latitude");
latitude := yFindLatitude("MyModule.MyFunction");
latitude := yFindLatitude("MyFunction");
yFindLatitude returns an object which you can then use at will to control the latitude sensor.
isOnline
The isOnline() method of the object returned by yFindLatitude allows you to know if the
corresponding module is present and in working order.
get_latitude
The get_latitude() method of the object returned by yFindGps provides the latitude currently
measured by the Yocto-GPS. The value returned is a string, the format will vary according to the
Yocto-GPS configuration. To get a floating point value, no matter the configuartion, use the YLatitude
Class.
13.3. Control of the module part
Each module can be controlled in a similar manner, you can find below a simple sample program
displaying the main parameters of the module and enabling you to activate the localization beacon.
program modulecontrol;
{$APPTYPE CONSOLE}
uses
SysUtils,
yocto_api;
const
serial = 'YGNSSMK1-123456'; // use serial number or logical name
procedure refresh(module:Tymodule) ;
beginif(module.isOnline())thenbeginWriteln('');Writeln('Serial : ' + module.get_serialNumber());Writeln('Logical name : ' + module.get_logicalName());Writeln('Luminosity : ' + intToStr(module.get_luminosity()));Write('Beacon :');if(module.get_beacon()=Y_BEACON_ON)thenWriteln('on')elseWriteln('off');
Writeln('uptime : ' + intToStr(module.get_upTime()div1000)+'s');Writeln('USB current : ' + intToStr(module.get_usbCurrent())+'mA');Writeln('Logs : ');Writeln(module.get_lastlogs());Writeln('');Writeln('r : refresh / b:beacon ON / space : beacon off');end
13. Using Yocto-GPS with Delphi
www.yoctopuce.com89
elseWriteln('Module not connected (check identification and USB cable)');
end;
procedure beacon(module:Tymodule;state:integer);
begin
module.set_beacon(state);
refresh(module);end;
var
module : TYModule;
c : char;
errmsg : string;
begin
// Setup the API to use local USB devicesif yRegisterHub('usb', errmsg)<>YAPI_SUCCESS thenbeginWrite('RegisterHub error: '+errmsg);exit;
end;
module := yFindModule(serial);
refresh(module);
repeatread(c);case c of'r': refresh(module);'b': beacon(module,Y_BEACON_ON);' ': beacon(module,Y_BEACON_OFF);end;
until c = 'x';
yFreeAPI();
end.
Each property xxx of the module can be read thanks to a method of type get_xxxx(), and
properties which are not read-only can be modified with the help of the set_xxx() method. For
more details regarding the used functions, refer to the API chapters.
Changing the module settings
When you want to modify the settings of a module, you only need to call the corresponding
set_xxx() function. However, this modification is performed only in the random access memory
(RAM) of the module: if the module is restarted, the modifications are lost. To memorize them
persistently, it is necessary to ask the module to save its current configuration in its permanent
memory. To do so, use the saveToFlash() method. Inversely, it is possible to force the module to
forget its current settings by using the revertFromFlash() method. The short example below
allows you to modify the logical name of a module.
program savesettings;
{$APPTYPE CONSOLE}
uses
SysUtils,
yocto_api;
const
serial = 'YGNSSMK1-123456'; // use serial number or logical name
beginwriteln('Module not connected (check identification and USB cable)');exit;
end;
Writeln('Current logical name : '+module.get_logicalName());Write('Enter new name : ');Readln(newname);if(not(yCheckLogicalName(newname)))thenbeginWriteln('invalid logical name');exit;
end;
module.set_logicalName(newname);
module.saveToFlash();
yFreeAPI();Writeln('logical name is now : '+module.get_logicalName());
end.
Warning: the number of write cycles of the nonvolatile memory of the module is limited. When this
limit is reached, nothing guaranties that the saving process is performed correctly. This limit, linked to
the technology employed by the module micro-processor, is located at about 100000 cycles. In short,
you can use the saveToFlash() function only 100000 times in the life of the module. Make sure
you do not call this function within a loop.
Listing the modules
Obtaining the list of the connected modules is performed with the yFirstModule() function which
returns the first module found. Then, you only need to call the nextModule() function of this
object to find the following modules, and this as long as the returned value is not nil. Below a short
example listing the connected modules.
program inventory;
{$APPTYPE CONSOLE}
uses
SysUtils,
yocto_api;
var
module : TYModule;
errmsg : string;
begin
// Setup the API to use local USB devicesif yRegisterHub('usb', errmsg)<>YAPI_SUCCESS thenbeginWrite('RegisterHub error: '+errmsg);exit;
end;
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.
13. Using Yocto-GPS with Delphi
www.yoctopuce.com91
The simplest way to work around the problem is the one used in the short examples provided in this
chapter: before accessing a module, check that it is online with the isOnline function, and then
hope that it will stay so during the fraction of a second necessary for the following code lines to run.
This method is not perfect, but it can be sufficient in some cases. You must however be aware that
you cannot completely exclude an error which would occur after the call to isOnline and which
could crash the software. The only way to prevent this is to implement one of the two error handling
techniques described below.
The method recommended by most programming languages for unpredictable error handling is the
use of exceptions. By default, it is the behavior of the Yoctopuce library. If an error happens while
you try to access a module, the library throws an exception. In this case, there are three possibilities:
• If your code catches the exception and handles it, everything goes well.
• If your program is running in debug mode, you can relatively easily determine where the
problem happened and view the explanatory message linked to the exception.
• Otherwise... the exception makes your program crash, bang!
As this latest situation is not the most desirable, the Yoctopuce library offers another possibility for
error handling, allowing you to create a robust program without needing to catch exceptions at every
line of code. You simply need to call the YAPI.DisableExceptions() function to commute the
library to a mode where exceptions for all the functions are systematically replaced by specific return
values, which can be tested by the caller when necessary. For each function, the name of each
return value in case of error is systematically documented in the library reference. The name always
follows the same logic: a get_state() method returns a Y_STATE_INVALID value, a
get_currentValue method returns a Y_CURRENTVALUE_INVALID value, and so on. In any
case, the returned value is of the expected type and is not a null pointer which would risk crashing
your program. At worst, if you display the value without testing it, it will be outside the expected
bounds for the returned value. In the case of functions which do not normally return information, the
return value is YAPI_SUCCESS if everything went well, and a different error code in case of failure.
When you work without exceptions, you can obtain an error code and an error message explaining
the source of the error. You can request them from the object which returned the error, calling the
errType() and errMessage() methods. Their returned values contain the same information as
in the exceptions when they are active.
13. Using Yocto-GPS with Delphi
92www.yoctopuce.com
14. Using the Yocto-GPS with Python
Python is an interpreted object oriented language developed by Guido van Rossum. Among its
advantages is the fact that it is free, and the fact that it is available for most platforms, Windows as
well as UNIX. It is an ideal language to write small scripts on a napkin. The Yoctopuce library is
compatible with Python 2.6+ and 3+. It works under Windows, Mac OS X, and Linux, Intel as well as
ARM. The library was tested with Python 2.6 and Python 3.2. Python interpreters are available on the
Python web site1.
14.1. Source files
The Yoctopuce library classes2 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.
14.2. Dynamic library
A section of the low-level library is written in C, but you should not need to interact directly with it: it is
provided as a DLL under Windows, as a .so files under UNIX, and as a .dylib file under Mac OS X.
Everything was done to ensure the simplest possible interaction from Python: the distinct versions of
the dynamic library corresponding to the distinct operating systems and architectures are stored in
the cdll directory. The API automatically loads the correct file during its initialization. You should not
have to worry about it.
If you ever need to recompile the dynamic library, its complete source code is located in the
Yoctopuce C++ library.
In order to keep them simple, all the examples provided in this documentation are console
applications. Naturally, the libraries function in a strictly identical manner if you integrate them in an
application with a graphical interface.
14.3. Control of the Latitude function
A few lines of code are enough to use a Yocto-GPS. Here is the skeleton of a Python code snipplet
to use the Latitude function.
1
http://www.python.org/download/
2
www.yoctopuce.com/EN/libraries.php
www.yoctopuce.com93
[...]
errmsg=YRefParam()
#Get access to your device, connected locally on USB for instance
YAPI.RegisterHub("usb",errmsg)
latitude = YLatitude.FindLatitude("YGNSSMK1-123456.latitude")
# Hot-plug is easy: just check that the device is online
if latitude.isOnline():
#Use latitude.get_currentValue()
...
[...]
Let's look at these lines in more details.
YAPI.RegisterHub
The yAPI.RegisterHub function initializes the Yoctopuce API and indicates where the modules
should be looked for. When used with the parameter "usb", it will use the modules locally
connected to the computer running the library. If the initialization does not succeed, this function
returns a value different from YAPI.SUCCESS and errmsg contains the error message.
YLatitude.FindLatitude
The YLatitude.FindLatitude function allows you to find a latitude 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-GPS module with serial number
YGNSSMK1-123456 which you have named "MyModule", and for which you have given the latitude
function the name "MyFunction". The following five calls are strictly equivalent, as long as
"MyFunction" is defined only once.
latitude = YLatitude.FindLatitude("YGNSSMK1-123456.latitude")
latitude = YLatitude.FindLatitude("YGNSSMK1-123456.MyFunction")
latitude = YLatitude.FindLatitude("MyModule.latitude")
latitude = YLatitude.FindLatitude("MyModule.MyFunction")
latitude = YLatitude.FindLatitude("MyFunction")
YLatitude.FindLatitude returns an object which you can then use at will to control the
latitude sensor.
isOnline
The isOnline() method of the object returned by YLatitude.FindLatitude allows you to
know if the corresponding module is present and in working order.
get_latitude
The get_latitude() method of the object returned by YGps.FindGps provides the latitude
currently measured by the Yocto-GPS. The value returned is a string, the format will vary according
to the Yocto-GPS configuration. To get a floating point value, no matter the configuartion, use the
YLatitude Class.
A real example
Launch Python and open the corresponding sample script provided in the directory Examples/DocGettingStarted-Yocto-GPS of the Yoctopuce library.
In this example, you will recognize the functions explained above, but this time used with all side
materials needed to make it work nicely as a small demo.
#!/usr/bin/python
# -*- coding: utf-8 -*-
importos, sys
from yocto_api import *
from yocto_gps import *
14. Using the Yocto-GPS with Python
94www.yoctopuce.com
Loading...
+ hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.