Home
User manual
Contents
1. j 15 50 15 50 i OPROIO Orang aaa oli W 2 Eol i 2 gt mreoejo D cea ar O 5 O d D lt D So A g Dwl dq 41000 p S gt C 3 R t J O d Wwyeoo p LZ Al o lo D 1O L JO goraz P C lt s cae oie E by Os a 0e o Z Q gt f ue IW4z O D J TAP Ao 2 2 50 MAX 4 5 l S I gS 1 ff me All dimensions are in mm Toutes les dimensions sont en mm A4 Yocto Relay Echelle Index A Access 95 Accessories 3 Activating 96 Advanced 107 Android 95 96 Assembly 15 16 Basic 63 Blueprint 223 C C 69 C 49 54 Callback 44 Characteristics 221 CheckLogicalName YAPI 111 Coils 16 Command 27 Compatibility 95 Components 9 Concepts 19 Configuration 12 Connections 15 D Dangerous 9 delayedPulse YRelay 183 Delphi 77 describe YModule 138 describe YRelay 184 Description 27 DisableExceptions YAPI 112 Distribution 16 download YModule 139 Dynamic 83 E Electro magnetic 16 Electrocution 9 Elements 5 6 EnableExceptions YAPI 113 EnableUSBHost YAPI 114 Error 36 47 53 61 67 74 81 87 93 105 Event 107 Examples 16 F Files 83
2. attribute type modifiable productName String read only serialNumber String read only logicalName String modifiable productId Hexadecimal number read only productRelease Hexadecimal number read only firmwareRelease String read only persistentSettings Enumerated modifiable luminosity 0 100 modifiable beacon On Off modifiable upTime Time read only usbCurrent Used current mA read only rebootCountdown Integer modifiable usbBandwidth Enumerated modifiable relay1 Relay relay2 Relay attribute type modifiable logicalName String modifiable advertisedValue String read only state A B modifiable stateAtPowerOn Enumerated modifiable maxTimeOnStateA Time modifiable maxTimeOnStateB Time modifiable output On Off modifiable pulseTimer Time modifiable delayedPulseTimer Aggregate modifiable countdown Time read only 6 3 Module control interface This interface is identical for all Yoctopuce USB modules It can be used to control the module global parameters and to enumerate the functions provided by each module productName Character string containing the commercial name of the module as set by the factory serialNumber Character string containing the serial number unique and programmed at the factory For a Yocto Relay module this serial number always starts with RELAYLO1 You can use the serial number to access a given module by software logicalName Character string containing
3. public class GettingStarted Yocto Relay extends Activity implements OnItemSelectedListener private YRelay relay null private ArrayAdapter lt String gt aa Override public void onCreate Bundle savedInstanceState super onCreate savedInstanceState setContentView R layout gettingstarted_yocto_ relay Spinner my spin Spinner findViewById R id spinner1 my spin setOnItemSelectedListener this aa new ArrayAdapter lt String gt this android R layout simple spinner item aa setDropDownViewResource android R layout simple spinner dropdown_item my spin setAdapter aa Override protected void onStart super onStart 7 try aa clear YAPI EnableUSBHost this YAPI RegisterHub usb YRelay r YRelay FirstRelay while r null String hwid r get_hardwareId aa add hwid r r nextRelay cCabich YAP Uh xcepir mom 5e i e pPrimesStackirace gt refresh Spinner with detected relay aa notifyDataSetChanged Override protected void onStop super onStop YAPI FreeAPI Override public void onItemSelected AdapterView lt gt parent View view int pos long id String hwid parent getItemAtPosition pos toString relay YRelay FindRelay hwid www yoctopuce com 99 17 Using the Yocto Relay with Android Override public void onNothingSelected AdapterView lt gt arg0 Called when the user touch
4. 76 www yoctopuce com 14 Using Yocto Relay with Delphi Delphi is a descendent of Turbo Pascal Originally Delphi was produced by Borland Embarcadero now edits it The strength of this language resides in its ease of use as anyone with some notions of the Pascal language can develop a Windows application in next to no time Its only disadvantage is to cost something Delphi libraries are provided not as VCL components but directly as source files These files are compatible with most Delphi versions To keep them simple all the examples provided in this documentation are console applications Obviously the libraries work in a strictly identical way with VCL applications You will soon notice that the Delphi API defines many functions which return objects You do not need to deallocate these objects yourself the API does it automatically at the end of the application 14 1 Preparation Go to the Yoctopuce web site and download the Yoctopuce Delphi libraries Uncompress everything in a directory of your choice add the subdirectory sources in the list of directories of Delphi libraries By default the Yoctopuce Delphi library uses the yapi di DLL all the applications you will create with Delphi must have access to this DLL The simplest way to ensure this is to make sure yapi dll is located in the same directory as the executable file of your application 14 2 Control of the Relay function Launch your Delphi envi
5. This chapter does not repeat the programming concepts described earlier in order to stay as concise as possible In case of doubt do not hesitate to go back to the chapter describing in details all configurable attributes www yoctopuce com 109 19 High level API Reference 19 1 General functions These general functions should be used to initialize and configure the Yoctopuce library In most cases a simple call to function yRegisterHub should be enough The module specific functions yFind or yFirst should then be used to retrieve an object that provides interaction with the module In order to use the functions described here you should include lt script type text javascript src yocto_api js gt lt script gt var yoctolib require yoctolib var YAPI yoctolib YAPI var YModule yoctolib YModule require_once yocto_api php include yocto_api h import yocto_api h uses yocto_api vb _ yocto_api vb yocto_api cs import com yoctopuce YoctoAPI YModule from yocto_api import Global functions yCheckLogicalName name Checks if a given string is valid as logical name for a module or a function yDisableExceptions Disables the use of exceptions to report runtime errors yEnableExceptions Re enables the use of exceptions for runtime error handling yEnableUSBHost osContext This function is used only on Android yFreeAPI Frees dynamically allocated memory blocks
6. module get_productName module module nextModule end end 14 4 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run www yoctopuce com 81 14 Using Yocto Relay with Delphi This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to i1sOnline and which could crash the software The only way to prevent this is to implement one of the two error handling techniques described below The method recommended by most programming languages for unpredictable error handling is the use of exceptions By default it is the behavior of the Yoctopuce library If an error happens while you try to access a module the li
7. 8 1 Getting ready Go to the Yoctopuce web site and download the following items e The Javascript programming library e The VirtualHub software for Windows Mac OS X or Linux depending on your OS Decompress the library files in a folder of your choice connect your modules run the VirtualHub software and you are ready to start your first tests You do not need to install any driver 8 2 Control of the Relay function A few lines of code are enough to use a Yocto Relay Here is the skeleton of a JavaScript code snipplet to use the Relay function lt SCRIPT type text javascript src yocto_apil js gt lt SCRIPI gt lt SCRIPT type text javascript src yocto rellay js gt lt SCRIPT gt Get access to your device through the VirtualHub running locally yRegisterHub http 127 0 0 1 4444 var relay yFindRelay RELAYLO1 123456 relayl Check that the module is online to handle hot plug if relay isOnline 1 Actually as soon as Opera implements support for the HTTP Access Control Allow Origin header www yoctopuce com EN libraries php 3 www yoctopuce com EN virtualhub php www yoctopuce com 31 8 Using Yocto Relay with Javascript Use relay set_state lt e Let us look at these lines in more details yocto_api js and yocto_relay js These two Javascript includes provide access to functions allowing you to manage Yoctopuce modules yocto_api js must always be included yocto re
8. Evedid se plext moduler gebUsh Curent isa emANy Switch sw Switch findViewById R id beaconswitch Log d switch beacon module get_beacon sw setChecked module getBeacon YModule BEACON_ON field TextView findViewById R id logs field setText module get_lastLogs j p j p tatata tata catch YAPI Exception e printStackTrace Override public void onItemSelected AdapterView lt gt parent View view int pos long id String hwid parent getItemAtPosition pos toString module YModule FindModule hwid DisplayModuleInfo Override public void onNothingSelected AdapterView lt gt arg0Q public void refreshInfo View view DisplayModuleInfo public void toggleBeacon View view if module null return boolean on Switch view isChecked www yoctopuce com 101 17 Using the Yocto Relay with Android try alse exo ff module setBeacon YModule BEACON_ ON else module setBeacon YModule BEACON OFF ehelay KGNPIL ipdecoiesoin 1 e printStackTrace Each property xxx of the module can be read thanks to a method of type YModule get xxxx and properties which are not read only can be modified with the help of the YModule set xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you w
9. Returns the number of functions on the module On failure throws an exception or returns a negative error code www yoctopuce com 141 19 High level API Reference module functionld YModule Retrieves the hardware identifier of the nth function on the module function functionld functionIndex function functionld functionIndex function functionld functionIndex string functionld int functionIndex NSString functionld int functionIndex function functionld functionIndex integer string function functionld ByVal functionIndex As Integer As String string functionld int functionIndex def functionld functionIndex Parameters functionIndex the index of the function for which the information is desired starting at O for the first function Returns a string corresponding to the unambiguous hardware identifier of the requested module function On failure throws an exception or returns an empty string 142 www yoctopuce com 19 High level API Reference module functionName YModule Retrieves the logical name of the nth function on the module function functionName functionIndex function functionName functionIndex function functionName functionIndex string functionName int functionIndex NSString functionName int functionindex function functionName functionIndex integer string function functionName ByVal functionIndex As Integer As String
10. function get_usbCurrent Longint v _ function get_usbCurrent As Integer int get_usbCurrent int get_usbCurrent def get_usbCurrent YModule target get_usbCurrent Returns YModule an integer corresponding to the current consumed by the module on the USB bus in milli amps On failure throws an exception or returns Y_USBCURRENT_INVALID 162 www yoctopuce com 19 High level API Reference module get_userData YModule module gt userData Returns the value of the userData attribute as previously stored using method set_userData function get_userData function get_userData function get_userData void get_userData void userData function get_userData Tobject function get_userData As Object object get_userData Object get_userData def get_userData This attribute is never touched directly by the API and is at disposal of the caller to store a context Returns the object stored previously by the caller www yoctopuce com 163 19 High level API Reference module gt isOnline YModule Checks if the module is currently reachable without raising any error 5s function isOnline node js function isOnline php function isOnline cpp _ bool isOnline BOOL isOnline pas function isOnline boolean vb function isOnline As Boolean cs _ bool isOnline java boolean isOnline
11. int ms_delay int ms_duration pas_ function delayedPulse ms_delay LongInt ms_duration Longlnt integer function delayedPulse ByVal ms_delay As Integer ByVal ms_duration As Integer As Integer int delayedPulse int ms_delay int ms_duration int delayedPulse int ms_delay int ms_duration def delayedPulse ms_delay ms_duration YRelay target delayedPulse ms_delay ms_duration Parameters ms_delay waiting time before the pulse in millisecondes ms_duration pulse duration in millisecondes Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code 184 www yoctopuce com 19 High level API Reference relay describe Returns a short text that describes the relay in the form TYP function describe function describe function describe string describe NSString describe function describe string function describe As String string describe String describe def describe More precisely TYPE is the type of the function NAME YRelay E NAME SERIAL FUNCTIONID it the name used for the first access to the function SERIAL is the serial number of the module if the module is connected or unresolved and FUNCTIONID is the hardware identifier of the function if the module is connected For example this method returns Relay MyCustomName r
12. 4 www yoctopuce com 2 Presentation A 2099 JO v 1 USB socket 4 Input of relay 1 9 Input of relay 2 2 Yocto button 5 Output A of relay 1 10 Output A of relay 2 3 Yocto led 6 Output B of relay 1 11 Output B of relay 2 7 Output A led of relay1 12 Output A led of relay 2 8 Output B led of relay 1 13 Output B led of relay 2 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 www yoctopuce com 2 Presentation Warning the USB connector is simply soldered in surface and can be pulled out if the USB plug acts as a lever In this case if the tracks stayed in position the connector can be soldered back with a good iron and using flux to avoid bridges Alternatively you can solder a USB cable directly in the 1 27mm spaced holes near the connector Yocto button The Yocto button has two functionalities First it can activate the Yocto beacon mode see below under Yocto led Second if you plug in a Yocto module while keeping this button pressed you can then reprogram its firmware with a new version Note that there is a simpler Ul based method to update the firmware but this one works even in case of severely damaged firmware Yocto led Normally the Yocto led is used to indicate that the m
13. Control of the Relay function Launch Xcode 4 2 and open the corresponding sample project provided in the directory Examples Doc GettingStarted Yocto Relay of the Yoctopuce library import lt Foundation Foundation h gt import yocto_api h import yocto_relay h static void usage void NSLog usage demo lt serial_number gt A B NSLog demo lt ilogacalliname gt MATERNA NSLog demo any A B use any discovered device exit 1 int Mein Ariaroe const char aeraw I 1 www yoctopuce com EN libraries php 2 www yoctopuce com EN article new objective c library for mac os x www yoctopuce com 57 11 Using Yocto Relay with Objective C NS Enso elas ous alse elie lt Si 4 usage autoreleasepool Setup the API to use local USB devices if YAPI RegisterHub usb amp error YAPI SUCCESS NSLog RegisterHub error error llocalizedDescription return 1 NSString target NSString stringWithUTF8String argv 1 NSString state NSString stringWithUTF8String argv 2 YRelay relay if target isEqualToString any relay YRelay FirstRelay if relay NULL NSLog No module connected check USB cable return 17 relser relay YRelay FindRelay target stringByAppendingString relayl if relay isOnline if state isEqualToString A ecileny Sie Sreya n SIPA Ale elise aslay Sie Areia Savana
14. MyModule relayl YRelay relay yFindRelay MyModule MyFunction YRelay relay yFindRelay MyFunction yFindRe lay returns an object which you can then use at will to control the relay 58 www yoctopuce com 11 Using Yocto Relay with Objective C isOnline The isOnline method of the object returned by yFindRelay allows you to know if the corresponding module is present and in working order set_state The set _state method of the objet returned by yFindRelay switches the relay position to one of its two outputs The two possible parameter values are Y STATE A for output A and Y STATE B for output B 11 2 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon import lt Foundation Foundation h gt import yocto_api h static void usage const char exe NSLog usage s lt serial or logical name gt ON OFF n exe exse ink main int arge const char argv NSError error autoreleasepool Setup the API to use local USB devices if YAPTI RegisterHub usb amp error YAPI SUCCESS NSLog RegisterHub error error localizedDescription return 1 Pivarge 2 usage argv 0 NSString serial or name NSString stringWithUTF8String argv 1 YModule mod
15. RELAYLO1 000CC Product name Yocto Relay Firmware 3375 C _ Logical name Luminosity Device s functions Each function of the device have two names a physical name and a logical name You can change the logical name using the rename button RELAYLO1 000CC relay1 rename RELAYLO1 000CC relay2 rename Save Cancel Yocto Relay 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 in command line 3 www yoctopuce com EN virtualhub php 4 More information available in the virtual hub documentation 12 www yoctopuce com 4 First steps Logical name of the module The logical name is a name that you choose which allows you to access your module in the same
16. arguments the caller specific context object the receiving function object and the error code or YAPT_SUCCESS context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback www yoctopuce com 207 19 High level API Reference relay nextRelay YRelay Continues the enumeration of relays started using yFirstRelay is __ function nextRelay node js function nextRelay php _ function nextRelay Y Relay nextRelay YRelay nextRelay function nextRelay TYRelay function nextRelay As YRelay YRelay nextRelay Y Relay nextRelay def nextRelay Returns a pointer to a YRelay object corresponding to a relay currently online or a nul 1 pointer if there are no more relays to enumerate 208 www yoctopuce com 19 High level API Reference relay pulse YRelay Sets the relay to output B active for a specified duration then brings it automatically back to output A idle state function pulse ms_duration function pulse ms_duration function pulse ms_duration int pulse int ms_duration int pulse int ms_duration function pulse ms_duration LongInt integer function pulse ByVal ms_duration As Integer As Integer int pulse int ms_duration int pulse int ms_duration def pulse ms_duration YRelay target pulse ms_duration Parameters ms_duration pul
17. check identification and USB cable 13 4 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon using System Using ovstem Collections Generic www yoctopuce com 71 13 Using Yocto Relay with C using System Ling using System Text namespace ConsoleApplicationl ellass Program static void usage string execname System AppDomain CurrentDomain FriendlyName Console WriteLine Usage Console WriteLine execname lt serial or logical name gt ON OFF Sysitem Threading Thread Sleep 2500 Environment Exit 0 static void Main string args YModule m string errmsg if YAPI RegisterHub usb ref errmsg YAPI SUCCESS Console WriteLine RegisterHub error errmsg Environment Exit 0 alae eae o kengt Nie iL usage m YModule FindModule args 0 use serial or logical name if m isOnline if args Length gt 2 i ie ans loupper ON miset beacon YModuile n BEACONTOND if args 1 ToUpper OFF m set_beacon YModule BEACON OFF Console WriteLine serial Le me Gers eriaLNumbenra i Console WriteLine logical name m get_logicalName Console WriteLine luminosity miget minos yi hosters Eno ON Console Write beacon ae
18. def isOnline If there are valid cached values for the module that have not yet expired the device is considered reachable No exception is raised if there is an error while trying to contact the requested module Returns true if the module can be reached and false otherwise 164 www yoctopuce com 19 High level API Reference module gt isOnline_async YModule Checks if the module is currently reachable without raising any error function isOnline_async callback context function isOnline_async callback context If there are valid cached values for the module that have not yet expired the device is considered reachable No exception is raised if there is an error while trying to contact the requested module This asynchronous version exists only in Javascript It uses a callback instead of a return value in order to avoid blocking Firefox Javascript VM that does not implement context switching during blocking I O calls Parameters callback callback function that is invoked when the result is known The callback function receives three arguments the caller specific context object the receiving module object and the boolean result context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback www yoctopuce com 165 19 High level API Reference module load YModule Preloads the module cache with a specifi
19. from the Solution Explorer window right click on the DLL select Properties and in the Properties panel set the Copy to output folder to always You are now ready to use your Yoctopuce modules from Visual Studio In order to keep them simple all the examples provided in this documentation are console applications Naturally the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface 13 3 Control of the Relay function A few lines of code are enough to use a Yocto Relay Here is the skeleton of a C code snipplet to use the Relay function eae string errmsg YRelay relay Get access to your device connected locally on USB for instance YAPI RegisterHub usb errmsg relay YRelay FindRelay RELAYLO1 123456 relayl Hot plug is easy just check that the device is online if relay isOnline ue Use rellayvasetmstanel an mn 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 YRelay FindRelay The YRelay FindRelay function allows you to find a relay from the serial nu
20. func This function does not require that the module is online at the time it is invoked The returned object is nevertheless valid Use the method YModule isOnline to test if the module is indeed online at a given time In case of ambiguity when looking for a module by logical name no error is notified the first instance found is returned The search is performed first by hardware name then by logical name Parameters func a string containing either the serial number or the logical name of the desired module Returns a YModule object allowing you to drive the module or get additional information on the module www yoctopuce com 137 19 High level API Reference YModule FirstModule YModule yFirstModule Starts the enumeration of modules currently accessible function yFirstModule nodejs function FirstModule function yFirstModule cpp _ YModule yFirstModule m YModule yFirstModule function yFirstModule TYModule function yFirstModule As YModule YModule FirstModule YModule FirstModule def FirstModule Use the method yModule nextModule to iterate on the next modules Returns a pointer to a YModule object corresponding to the first module currently online or a null pointer if there are none 138 www yoctopuce com 19 High level API Reference module describe Returns a descriptive text that identifies the module function d
21. int load long msValidity def load msValidity By default whenever accessing a device all function attributes are kept in cache for the standard duration 5 ms This method can be used to temporarily mark the cache as valid for a longer period in order to reduce network trafic for instance Parameters msValidity an integer corresponding to the validity attributed to the loaded function parameters in milliseconds Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code 206 www yoctopuce com 19 High level API Reference relay load_async YRelay Preloads the relay cache with a specified validity duration asynchronous version function load_async msValidity callback context function load_async msValidity callback context By default whenever accessing a device all function attributes are kept in cache for the standard duration 5 ms This method can be used to temporarily mark the cache as valid for a longer period in order to reduce network trafic for instance This asynchronous version exists only in Javascript It uses a callback instead of a return value in order to avoid blocking the Javascript virtual machine Parameters msValidity an integer corresponding to the validity of the loaded function parameters in milliseconds callback callback function that is invoked when the result is known The callback function receives three
22. int64 integer function set_maxTimeOnStateA ByVal newval As Long As Integer int set_maxTimeOnStateA long newval int set_maxTimeOnStateA long newval def set_maxTimeOnStateA newval Y Relay target set_maxTimeOnStateA newval Use zero for no maximum time Parameters newval an integer Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code 212 www yoctopuce com 19 High level API Reference relay set_maxTimeOnStateB YRelay relay setMaxTimeOnStateB Sets the maximum time ms allowed for THEFUNCTIONSS to stay in state B before automatically switching back in to A state function set_maxTimeOnStateB newval function set_maxTimeOnStateB newval function set_maxTimeOnStateB newval int set_maxTimeOnStateB s64 newval int setMaxTimeOnStateB s64 newval function set_maxTimeOnStateB newval int64 integer function set_maxTimeOnStateB ByVal newval As Long As Integer int set_maxTimeOnStateB long newval int set_maxTimeOnStateB long newval def set_maxTimeOnStateB newval YRelay target set_maxTimeOnStateB newval Use zero for no maximum time Parameters newval an integer Returns YAPI_SUCCESS if the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 213 19 High level API Reference relay set_output YRelay relay setOutput Changes th
23. s64 get_countdown s64 countdown function get_countdown int64 function get_countdown As Long long get_countdown long get_countdown def get_countdown YRelay target get_countdown Returns an integer corresponding to the number of milliseconds remaining before a pulse delayedPulse call When there is no scheduled pulse returns zero On failure throws an exception or returns Y_COUNTDOWN_INVALID www yoctopuce com 187 19 High level API Reference relay get_errorMessage YRelay relay errorMessage Returns the error message of the latest error with the relay function get_errorMessage function get_errorMessage function get_errorMessage string get_errorMessage NSString errorMessage function get_errorMessage string function get_errorMessage As String string get_errorMessage String get_errorMessage def get_errorMessage This method is mostly useful when using the Yoctopuce library with exceptions disabled Returns a string corresponding to the latest error message that occured while using the relay object 188 www yoctopuce com 19 High level API Reference relay get_errorType YRelay relay errorType Returns the numerical error code of the latest error with the relay function get_errorType function get_errorType function get_errorType YRETCODE get_errorType function get_errorType YRETCODE
24. string functionName int functionIndex def functionName functionIndex Parameters functionIndex the index of the function for which the information is desired starting at O for the first function Returns a string corresponding to the logical name of the requested module function On failure throws an exception or returns an empty string www yoctopuce com 143 19 High level API Reference module functionValue YModule Retrieves the advertised value of the nth function on the module function functionValue functionIndex function functionValue functionIndex function functionValue functionIndex string functionValue int functionIndex NSString functionValue int functionIndex function functionValue functionIndex integer string function functionValue ByVal functionIndex As Integer As String string functionValue int functionindex def functionValue functionIndex Parameters functionIndex the index of the function for which the information is desired starting at O for the first function Returns a short string up to 6 characters corresponding to the advertised value of the requested module function On failure throws an exception or returns an empty string 144 www yoctopuce com 19 High level API Reference module get_beacon module gt beacon Returns the state of the localization beacon function get_beacon function get_beacon fun
25. way a file name allows you to access its content A logical name has a maximum length of 19 characters Authorized characters are A Z a z 0 9 _ and If you assign the same logical name to two modules connected to the same computer and you try to access one of them through this logical name behavior is undetermined you have no way of knowing which of the two modules answers Luminosity This parameter allows you to act on the maximal intensity of the leds of the module This enables you if necessary to make it a little more discreet while limiting its power consumption Note that this parameter acts on all the signposting leds of the module including the Yocto led If you connect a module and no led turns on it may mean that its luminosity was set to zero Logical names of functions Each Yoctopuce module has a serial number and a logical name In the same way each function on each Yoctopuce module has a hardware name and a logical name the latter can be freely chosen by the user Using logical names for functions provides a greater flexibility when programming modules The only functions of the Yocto Relay module correspond to the embedded relays and have the hardware names relay1 and relay2 www yoctopuce com 13 14 www yoctopuce com 5 Assembly and connections This chapter provides important information regarding the use of the Yocto Relay module in real world situations Make sure to read it carefully bef
26. yUnregisterHub url Setup the Yoctopuce library to no more use modules connected on a previously registered machine with RegisterHub yUpdateDeviceList errmsg Triggers a re detection of connected Yoctopuce modules yUpdateDeviceList_async callback context Triggers a re detection of connected Yoctopuce modules www yoctopuce com 111 19 High level API Reference YAPI CheckLogicalName yCheckLogicalName Checks if a given string is valid as logical name for a module or a function function yCheckLogicalName name node js function CheckLogicalName name function yCheckLogicalName name bool yCheckLogicalName const string amp name BOOL yCheckLogicalName NSSiring name function yCheckLogicalName name string boolean function yCheckLogicalName ByVal name As String As Boolean bool CheckLogicalName string name boolean CheckLogicalName String name def CheckLogicalName name YAPI A valid logical name has a maximum of 19 characters allamongA 2Z a z 0 9 _ and If you try to configure a logical name with an incorrect string the invalid characters are ignored Parameters name a string containing the name to check Returns true if the name is valid false otherwise 112 www yoctopuce com 19 High level API Reference YAPI DisableExceptions YAPI yDisableExceptions Disables the use of exceptions to report runtime errors function yDisableExceptions
27. High level API Reference relay set_logicalName relay setLogicalName YRelay Changes the logical name of the relay function set_logicalName newval function set_logicalName newval function set_logicalName newval int set_logicalName const string amp newval int setLogicalName NSString newval function set_logicalName newval string integer function set_logicalName ByVal newval As String As Integer int set_logicalName string newval int set_logicalName String newval def set_logicalName newval YRelay target set_logicalName newval You can use yCheckLogicalName prior to this call to make sure that your parameter is valid Remember to call the saveToF lash method of the module if the modification must be kept Parameters newval a string corresponding to the logical name of the relay Returns YAPI_SUCCESS if the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 211 19 High level API Reference relay set_maxTimeOnStateA YRelay relay setMaxTimeOnStateA Sets the maximum time ms allowed for S THEFUNCTIONSS to stay in state A before automatically switching back in to B state function set_maxTimeOnStateA newval function set_maxTimeOnStateA newval function set_maxTimeOnStateA newval int set_maxTimeOnStateA s64 newval int setMaxTimeOnStateA s64 newval function set_maxTimeOnStateA newval
28. 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 6 6 Programming where to start At this point of the user s guide you should know the main theoretical points of your Yocto Relay It is now time to practice You must download the Yoctopuce library for your favorite programming language from the Yoctopuce web site Then skip directly to the chapter corresponding to the chosen programming language All the examples described in this guide are available in the programming libraries For some languages the libraries also include some complete graphical applications with their source code When you have mastered the basic programming of your module you can turn to the chapter on advanced programming that describes some techniques that will help you make the most of your Yocto Relay 2 http www yoctopuce com EN libraries php www yoctopuce com 25 6 Programming general concepts 26 www yoctopuce com 7 Using the Yocto Relay in
29. RELAYLO1 12346 get_logicalName Changing the settings of the module When you want to change the settings of a module simply use the corresponding set xxx command However this change happens only in the module RAM if the module restarts the changes are lost To store them permanently you must tell the module to save its current configuration in its nonvolatile memory To do so use the saveToFlash command Inversely it is possible to force the module to forget its current settings by using the revert FromFlash method For example YModule RELAYLO1 12346 set_logicalName MonPremierModule YModule RELAYLO1 12346 saveToFlash Note that you can do the same thing in a single command with the s option YModule s RELAYLO1 12346 set_logicalName MonPremierModule Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop 7 5 Limitations The command line API has the same limitation than the other APIs there can be only one application at a given time which can access the modules natively By default the command line API works in native mode You can easily wor
30. String args try setup the API to use local VirtualHub YAPI RegisterHub 127 0 0 1 meate MAP Te hs cepienoOnmex iar Soten out PEEM Cannon Contact VirevaliHubmons 12770 Oces et ex getLocalizedMessage System out printin Ensure that the VirtualHub application is running System exit 1 YRelay relay ae args lengent 0 4 relay YRelay FindRelay args 0 else relay YRelay FirstRelay if relay null System out printim No module connected check USB cabile 90 www yoctopuce com 16 Using the Yocto Relay with Java System exit 1 ery System out printin Switch relay to B relay set_state YRelay STATE B YAPI Sleep 1000 System out printin Switch relay to A relay set_state YRelay STATE A Pecalich VAPT I Rxcepiaon rex i System out printin Module t trelay describe not connected check identification and USB cable YAPI FreeAPi G 16 3 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon import com yoctopuce YoctoAPI import java util logging Level import java util logging Logger public class Demo public static void main String args try setup the API to use local VirtualHub YAPI SReGrsteshub lA 7 Or OI i Gabich VAP Oh xcep Ed
31. YModule YModule get_module YModule get_module def get_module If the function cannot be located on any module the returned instance of YModu1e is not shown as on line Returns an instance of YModule www yoctopuce com 197 19 High level API Reference relay get_module_async YRelay relay module_async Gets the YModul1e object for the device on which the function is located asynchronous version function get_module_async callback context function get_module_async callback context If the function cannot be located on any module the returned YModule object does not show as on line This asynchronous version exists only in Javascript It uses a callback instead of a return value in order to avoid blocking Firefox javascript VM that does not implement context switching during blocking I O calls See the documentation section on asynchronous Javascript calls for more details Parameters callback callback function that is invoked when the result is known The callback function receives three arguments the caller specific context object the receiving function object and the requested YModule object context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback 198 www yoctopuce com 19 High level API Reference relay get_output YRelay relay output Returns the output state of the relays w
32. function DisableExceptions function yDisableExceptions void yDisableExceptions void yDisableExceptions procedure yDisableExceptions procedure yDisableExceptions void DisableExceptions def DisableExceptions When exceptions are disabled every function returns a specific error value which depends on its type and which is documented in this reference manual www yoctopuce com 113 19 High level API Reference YAPI EnableExceptions YAPI yEnableExceptions Re enables the use of exceptions for runtime error handling function yEnableExceptions node js function EnableExceptions function yEnableExceptions void yEnableExceptions void yEnableExceptions procedure yEnableExceptions procedure yEnableExceptions cs void EnableExceptions def EnableExceptions Be aware than when exceptions are enabled every function that fails triggers an exception If the exception is not caught by the user code it either fires the debugger or aborts i e crash the program On failure throws an exception or returns a negative error code 114 www yoctopuce com 19 High level API Reference YAPI EnableUSBHost YAPI yEnableUSBHost This function is used only on Android synchronized static void EnableUSBHost Object osContext Before calling yRegisterHub usb you need to activate the USB host port of the system This function takes as argument an object of class android
33. function get_errorType As YRETCODE YRETCODE get_errorType int get_errorType def get_errorType This method is mostly useful when using the Yoctopuce library with exceptions disabled Returns a number corresponding to the code of the latest error that occured while using the relay object www yoctopuce com 189 19 High level API Reference relay get_friendlyName YRelay relay friendlyName Returns a global identifier of the relay in the format MODULE_NAME FUNCT ION_NAME function get_friendlyName function get_friendlyName function get_friendlyName string get_friendlyName NSString friendlyName string get_friendlyName String get_friendlyName def get_friendlyName The returned string uses the logical names of the module and of the relay if they are defined otherwise the serial number of the module and the hardware identifier of the relay for exemple MyCustomName relayl1l Returns a string that uniquely identifies the relay using logical names ex MyCustomName relay1 On failure throws an exception or returns Y_FRIENDLYNAME_INVALID 190 www yoctopuce com 19 High level API Reference relay get_functionDescriptor relay functionDescriptor Returns a unique identifier of type YFUN_DESCR corresponding to the function function get_functionDescriptor function get_functionDescriptor function get_functionDescriptor YFUN_D
34. gt lt a href javascript switchIt rl false gt Switch relay 1 to output A lt a gt lt br gt lt a href javascript switchIt r2 true gt Switch relay 2 to output B lt a gt lt br gt lt a href javascript switchIt r2 false gt Switch relay 2 to output A lt a gt lt br gt lt BODY gt lt HTML gt 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 lt HTML gt lt HEAD gt lt TITLE gt Module Control lt TITLE gt lt SCRIPT type text javascript src yocto_api js gt lt SCRIPT gt lt SCRIPT language javascriptl 5 type text JavaScript gt S Use explicit error handling rather than exceptions yDisableExceptions www yoctopuce com 33 8 Using Yocto Relay with Javascript Setup the API to use the VirtualHub on local machine if yRegisterHub http 127 0 0 1 4444 YAPI SUCCESS eulyeneie Me eholavone Contacti Vireen Hubklon Ib27 Ole Oloab4 2 var module function refresh var serial document getElementById serial value if serial Detect any conected module suitable for the demo module yFirstModule nextModule if module serial module get_serialNumber document getElementBylId serial value serial module yFindModule serial if module isOnline d
35. have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to i1sOnline and which could crash the software The only way to prevent this is to implement one of the two error handling techniques described below The method recommended by most programming languages for unpredictable error handling is the use of exceptions By default it is the behavior of the Yoctopuce library If an error happens while you try to access a module the library throws an exception In this case there are three possibilities e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwis
36. is performed only in the random access memory RAM of the module if the module is restarted the modifications are lost To memorize them persistently it is necessary to ask the module to save its current configuration in its permanent memory To do so use the saveToFlash method Inversely it is possible to force the module to forget its current settings by using the revertFromFlash method The short example below allows you to modify the logical name of a module include lt iostream gt include lt stdlib h gt include yocto_api h using namespace std static void usage const char exe cerr lt lt usage exit 1 int Meinjink arger Const char argv i string errmsg Setup the API to use local USB devices dst VRE Gassieraiuloy MUlslon ean S eral SUCCESS i cerr ca REGS ter baeiaO a lt lt a Ems Gm e end Eeen ily Ti heanoqe lt 2 usage argv 0 NK eee e serie ne whogucalName gt Us lt lt sends 52 www yoctopuce com 10 Using Yocto Relay with C YModule module yFindModule argv 1 use serial or logical name if module gt isOnline if arge gt 3 string newname argv 2 if yCheckLogicalName newname cerr lt lt Invalid name lt lt newname lt lt lt lt endl usage argv 0 module gt set_logicalName newname module gt saveToFlash COU CUE ren EM cne i lt module qe eulogaleal Namen
37. its content module gt functionCount Returns the number of functions beside the module interface available on the module module functionld functionIndex Retrieves the hardware identifier of the nth function on the module module functionName functionIndex Retrieves the logical name of the nth function on the module module functionValue functionIndex Retrieves the advertised value of the nth function on the module module get_beacon Returns the state of the localization beacon module get_errorMessage Returns the error message of the latest error with this module object module get_errorType Returns the numerical error code of the latest error with this module object module get_firmwareRelease Returns the version of the firmware embedded in the module module get_hardwareld Returns the unique hardware identifier of the module module get_icon2d 134 www yoctopuce com 19 High level API Reference Returns the icon of the module module get_lastLogs Returns a string with last logs of the module module get_logicalName Returns the logical name of the module module get_luminosity Returns the luminosity of the module informative leds from 0 to 100 module get_persistentSettings Returns the current state of persistent module settings module get_productld Returns the USB device identifier of the module module get_productName Returns the commercial n
38. manages the low level communications with the modules The source files in Visual C manage the high level part of the API Therefore your need both this DLL and the cs files of the sources directory to create a project managing Yoctopuce modules Configuring a Visual C project The following indications are provided for Visual Studio Express 2010 but the process is similar for other versions Start by creating your project Then on the Solution Explorer panel right click on your project and select Add and then Add an existing item A file selection window opens Select the yocto_api cs file and the files corresponding to the functions of the Yoctopuce modules that your project is going to manage If in doubt select all the files You then have the choice between simply adding these files to your project or to add them as links the Add button is in fact a scroll down menu In the first case Visual Studio copies the selected files into your project In the second case Visual Studio simply keeps a link on the original files We recommend you to use links which makes updates of the library much easier 1 http www microsoft com visualstudio en us products 2010 editions visual csharp express www yoctopuce com EN libraries php 3 The sources of this DLL are available in the C API www yoctopuce com 69 13 Using Yocto Relay with C Then add in the same manner the yapi d11 DLL located in the Sources d11 directory Then
39. 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 mod
40. nonvolatile memory of the module function saveToFlash function saveToFlash function saveToFlash int saveToFlash int saveToFlash function saveToFlash Longint function saveToFlash As Integer int saveToFlash int saveToFlash def saveToFlash YModule target saveToFlash YModule Warning the number of allowed save operations during a module life is limited about 100000 cycles Do not call this function within a loop Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 171 19 High level API Reference module set_beacon module setBeacon Turns on or off the module localization beacon function set_beacon newval function set_beacon newval function set_beacon newval int set_beacon Y_BEACON_enum newval int setBeacon Y_BEACON_enum newval function set_beacon newval Integer integer v function set_beacon ByVal newval As Integer As Integer int set_beacon int newval int set_beacon int newval def set_beacon newval YModule target set_beacon newval Parameters newval either Y_BEACON_OFF or Y_BEACON_ON Returns YAPI SUCCESS if the call succeeds On failure throws an exception or returns a negative error code YModule 172 www yoctopuce com 19 High level API Reference module set_logicalName YModule module gt setLogical
41. or logical name procedure refresh module Tymodule begin if module isOnline then begin Writeln Writeln Serial 7 modulenge reser Number k Writeln Logical name module get_logicalName Writeln Luminosity intToStr module get_luminosity Write Beacon oan if module get_beacon Y_ BEACON ON then Writeln on tise Wisse eHiay ovtetal yy Writeln uptime em Toote Mme FGiSic Rup Time Cliny IMO arise p Writeln USB current ge ae intToStr module get_usbCurrent mA Writeln Logs S Mg Writeln module get_lastlogs Writeln Writeln r refresh b beacon ON space beacon off end else Writeln Module not connected check identification and USB cable end www yoctopuce com 79 14 Using Yocto Relay with Delphi procedure beacon module Tymodule state integer begin module set_beacon state refresh module end var module TYModule E enay errmsg string begin Setup the API to use local USB devices if yRegisterHub usb errmsg lt gt YAPI SUCCESS then begin Write RegisterHub error errmsg exit end module yFindModule serial refresh module repedt read c 7 case c of r refresh module b beacon module Y BEACON ON beacon module Y BEACON OFF end ont a Yar end Each property xxx of the module can be read thanks to a method of type get _xxxx and properties which are
42. 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 e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the most
43. 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 Relay 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 40 www yoctopuce com 9 Using Yocto Relay with PHP lt HTML gt lt HEAD gt lt TITLE gt Hello World lt TITLE gt lt HEAD gt lt BODY gt lt FORM method get gt lt php include yocto_api php include yocto_relay php Use explicit error handling rather than exceptions yDisableExceptions Setup the API to use the VirtualHub on local machine if yRegisterHub http 127 0 0 1 4444 Serrmsg YAPT SUCCESS drelmcannok Contacti Ninel Hub ena 10r Oma Sserial GET serial ane Scene JS Wup Ff Check if a specified module is available online Srelayl yFindRelay serial relayl Srelay2 yFindRelay serial relay2 if relayl gt isOnline die Module not connected check serial and USB cable else or use any connected module suitable for the demo note that the order of enumeration may vary Srelayl yFirstRelay if is null relayl die No modu
44. setUserData Stores a user context provided as argument in the userData attribute of the function function set_userData data function set_userData data function set_userData data void set_userData void data void setUserData void data procedure set_userData data Tobject procedure set_userData ByVal data As Object void set_userData object data void set_userData Object data def set_userData data This attribute is never touched by the API and is at disposal of the caller to store a context Parameters data any kind of object to be stored 176 www yoctopuce com 19 High level API Reference module triggerFirmwareUpdate Schedules a module reboot into special firmware update mode function triggerFirmwareUpdate secBeforeReboot function triggerFirmwareUpdate secBeforeReboot function triggerFirmwareUpdate secBeforeReboot int triggerFirmwareUpdate int secBeforeReboot int triggerFirmwareUpdate int secBeforeReboot function triggerFirmwareUpdate secBeforeReboot Longint Longint function triggerFirmwareUpdate As Integer int triggerFirmwareUpdate int secBeforeReboot int triggerFirmwareUpdate int secBeforeReboot def triggerFirmwareUpdate secBeforeReboot YModule target triggerFirmwareUpdate secBeforeReboot YModule Parameters secBeforeReboot number of seconds before rebooting Returns YAPI_SUCCESS when the call succeeds On failure t
45. the expected bounds for the returned value In the case of functions which do not normally return information the return value is YAPI SUCCESS if everything went well and a different error code in case of failure When you work without exceptions you can obtain an error code and an error message explaining the source of the error You can request them from the object which returned the error calling the errType and errMessage methods Their returned values contain the same information as in the exceptions when they are active www yoctopuce com 87 88 www yoctopuce com 16 Using the Yocto Relay with Java Java is an object oriented language created by Sun Microsystem Beside being free its main strength is its portability Unfortunately this portability has an excruciating price In Java hardware abstraction is so high that it is almost impossible to work directly with the hardware Therefore the Yoctopuce API does not support native mode in regular Java The Java API needs a Virtual Hub to communicate with Yoctopuce devices 16 1 Getting ready Go to the Yoctopuce web site and download the following items The Java programming library e The VirtualHub software for Windows Mac OS X or Linux depending on your OS The library is available as source files as well as a jar file Decompress the library files in a folder of your choice connect your modules run the VirtualHub so
46. triggering a reboot of the module usbBandwidth Number of USB interfaces used by the device If this parameter is set to DOUBLE the device can send twice as much data but this may saturate the USB hub Remember to call the saveToFlash method and then to reboot the module to apply this setting 6 4 Relay function interface The Yoctopuce application programming interface allows you to switch the relay state This change is not persistent the relay will automatically return to its idle position whenever power is lost or if the module is restarted The library can also generate automatically short pulses of determined duration On devices with two output for each relay double throw the two outputs are named A and B with output A corresponding to the idle position at power off and the output B corresponding to the active state If you prefer the alternate default state simply switch your cables on the board logicalName Character string containing the logical name of the relay 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 relay directly If two relays 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
47. unique identifier of type YF UN_DESCR corresponding to the function relay get_functionld Returns the hardware identifier of the relay without reference to the module relay get_hardwareld www yoctopuce com 179 19 High level API Reference Returns the unique hardware identifier of the relay in the form SERIAL FUNCTIONID relay get_logicalName Returns the logical name of the relay relay get_maxTimeOnStateA Retourne the maximum time ms allowed for THEFUNCTIONSS to stay in state A before automatically switching back in to B state relay get_maxTimeOnStateB Retourne the maximum time ms allowed for THEFUNCTIONSS to stay in state B before automatically switching back in to A state relay get_module Gets the YModule object for the device on which the function is located relay get_module_async callback context Gets the YModule object for the device on which the function is located asynchronous version relay get_output Returns the output state of the relays when used as a simple switch single throw relay get_pulseTimer Returns the number of milliseconds remaining before the relays is returned to idle position state A during a measured pulse generation relay get_state Returns the state of the relays A for the idle position B for the active position relay get_stateAtPowerOn Returns the state of the relays at device startup A fo
48. used by the Yoctopuce library yGetAP Version Returns the version identifier for the Yoctopuce library in use yGetTickCount Returns the current value of a monotone millisecond based time counter yHandleEvents errmsg Maintains the device to library communication channel ylnitAPI mode errmsg Initializes the Yoctopuce programming library explicitly yPreregisterHub url errmsg Fault tolerant alternative to RegisterHub yRegisterDeviceArrivalCallback arrivalCallback Register a callback function to be called each time a device is pluged yRegisterDeviceRemovalCallback removalCallback Register a callback function to be called each time a device is unpluged yRegisterHub url errmsg Setup the Yoctopuce library to use modules connected on a given machine yRegisterHubDiscoveryCallback callback 110 www yoctopuce com 19 High level API Reference Register a callback function to be called each time a network hub or a VirtualHub is detected on the local network yRegisterLogFunction logfun Registers a log callback function ySelectArchitecture arch Select the architecture or the library to be loaded to access to USB ySetDelegate object Objective C only Register an object that must follow the procol YDeviceHotPlug ySetTimeout callback ms_timeout arguments Invoke the specified calloack function after a given timeout ySleep ms_duration errmsg Pauses the execution flow for a specified duration
49. which returned the error calling the errType and errMessage methods Their returned values contain the same information as in the exceptions when they are active www yoctopuce com 37 38 www yoctopuce com 9 Using Yocto Relay with PHP PHP is like Javascript an atypical language when interfacing with hardware is at stakes Nevertheless using PHP with Yoctopuce modules provides you with the opportunity to very easily create web sites which are able to interact with their physical environment and this is not available to every web server This technique has a direct application in home automation a few Yoctopuce modules a PHP server and you can interact with your home from anywhere on the planet as long as you have an internet connection PHP is one of those languages which do not allow you to directly access the hardware layers of your computer Therefore you need to run a virtual hub on the machine on which your modules are connected To start your tests with PHP you need a PHP 5 3 or more server preferably locally on you machine If you wish to use the PHP server of your internet provider it is possible but you will probably need to configure your ADSL router for it to accept and forward TCP request on the 4444 port 9 1 Getting ready Go to the Yoctopuce web site and download the following items The PHP programming library e The VirtualHub software for Windows Mac OS X or Linux depending on your
50. you can find complete examples illustrating the concepts presented here in the programming libraries of each language To remain as concise as possible examples provided in this chapter do not perform any error handling Do not copy them as is in a production application 18 1 Event programming The methods to manage Yoctopuce modules which we presented to you in preceding chapters were polling functions consisting in permanently asking the API if something had changed While easy to understand this programming technique is not the most efficient nor the most reactive Therefore the Yoctopuce programming API also provides an event programming model This technique consists in asking the API to signal by itself the important changes as soon as they are detected Each time a key parameter is modified the API calls a callback function which you have defined in advance Detecting module arrival and departure Hot plug management is important when you work with USB modules because sooner or later you will have to connect or disconnect a module when your application is running The API is designed to manage module unexpected arrival or departure in a transparent way But your application must take this into account if it wants to avoid pretending to use a disconnected module Event programming is particularly useful to detect module connection disconnection Indeed it is simpler to be told of new connections rather than to have to permanentl
51. you should not need to interact directly with it it is provided as a DLL under Windows as a so files under UNIX and as a dylib file under Mac OS X Everything was done to ensure the simplest possible interaction from Python the distinct versions of the dynamic library corresponding to the distinct operating systems and architectures are stored in the cdll directory The API automatically loads the correct file during its initialization You should not have to worry about it If you ever need to recompile the dynamic library its complete source code is located in the Yoctopuce C library In order to keep them simple all the examples provided in this documentation are console applications Naturally the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface 15 3 Control of the Relay function A few lines of code are enough to use a Yocto Relay Here is the skeleton of a Python code snipplet to use the Relay function 1 http www python org download www yoctopuce com EN libraries php www yoctopuce com 83 15 Using the Yocto Relay with Python erences errmsg YRef Param Get access to your device connected locally on USB for instance YAPI RegisterHub usb errmsg relay YRelay FindRelay RELAYLO1 123456 relayl Hot plug is easy just check that the device is online if relay isOnline Use relayesee State eel Let s look at the
52. 123456 MyFunction relay YRelay FindRelay MyModule relay1 relay YRelay FindRelay MyModule MyFunction relay YRelay FindRelay MyFunction YRelay FindRelay returns an object which you can then use at will to control the relay isOnline The isOnline method of the object returned by YRelay FindRelay allows you to know if the corresponding module is present and in working order set_state The set _state method of the objet returned by YRelay FindRelay switches the relay position to one of its two outputs The two possible parameter values are YRelay STATE A for output A and YRelay STATE B for output B 98 www yoctopuce com 17 Using the Yocto Relay with Android A real example Launch you Java environment and open the corresponding sample project provided in the directory Examples Doc Examples of the Yoctopuce library In this example you can recognize the functions explained above but this time used with all the side materials needed to make it work nicely as a small demo package com yoctopuce doc_examples import android app Activity import android os Bundle import android view View import android widget AdapterView import android widget AdapterView OnItemSelectedListener import android widget ArrayAdapter import android widget Spinner import com yoctopuce YoctoAPI YAPI import com yoctopuce YoctoAPI YAPI Exception import com yoctopuce YoctoAPI YRelay
53. 15 Using the Yocto Relay with Python print USB current Dh StrimygerwuUSsbeuETenic sip smAn print logs n m get_lastLogs algas PEIneE sys argy Mitr ainoot connected check rdent fication andiUSB Cable Each property xxx of the module can be read thanks to a method of type YModule get_xxxx and properties which are not read only can be modified with the help of the YModule set_xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding YModule set_xxx function However this modification is performed only in the random access memory RAM of the module if the module is restarted the modifications are lost To memorize them persistently it is necessary to ask the module to save its current configuration in its permanent memory To do so use the YModule saveToFlash method Inversely it is possible to force the module to forget its current settings by using the YModule revertFromFlash method The short example below allows you to modify the logical name of a module usr bin python coding u utf 8 import os sys from yocto api import def usage sys exit usage demo lt serial or logical name gt lt new logical name gt if len sys argv 3 usage errmsg YRefParam if YAPI RegisterHub usb errmsg YAPI SUCCESS Syor exii U
54. Ay Bo Console WriteLine execnamet lt logical name gt eve es es Console WriteLine execnamet any A TE IE System Threading Thread Sleep 2500 End End Sub Sub Main Dim argv As String System Environment GetCommandLineArgs Dim errmsg As String Dim target As String Dim relay As YRelay Dim state As Char If argv Length lt 3 Then Usage target argv 1 state CChar Mid argv 2 1 1 ToUpper REM Setup the API to use local USB devices TE Reeta nko Usb errs lt gt ART oUCEHS 5 MINEN Console WriteLine RegisterHub error errmsg End Ene If Tf target any Then relay yFirstRelay hi relay TS Nothing Then Console WriteLine No module connected check USB cable End End If Else relay yFindRelay target relayl End E If relay isOnline Then DE erete UA Thiem Tele Set Swen SWAIN A mles Telemast Swee N STAND i Else Console WriteLine Module not connected check identification and USB cable End If End Sub End Module 12 4 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon Imports System 10 Imports System Environment Module Modulel Sub usage Console WriteLine usage demo lt serial or logical name gt ON OFF End End Sub www yoctopuce com 65 12 Using Y
55. DLL for instance C VisualBasic or Delphi the character string includes as well the DLL version for instance 1 01 5535 1 01 5439 If you want to verify in your code that the library version is compatible with the version that you have used during development verify that the major number is strictly equal and that the minor number is greater or equal The build number is not relevant with respect to the library compatibility Returns a character string describing the library version www yoctopuce com 117 19 High level API Reference YAPI GetTickCount YAPI yGetTickCount Returns the current value of a monotone millisecond based time counter function yGetTickCount nodejs function GetTickCount function yGetTickCount u64 yGetTickCount u64 yGetTickCount function yGetTickCount u64 vo _ function yGetTickCount As Long ulong GetTickCount long GetTickCount def GetTickCount This counter can be used to compute delays in relation with Yoctopuce devices which also uses the millisecond as timebase Returns a long integer corresponding to the millisecond counter 118 www yoctopuce com 19 High level API Reference YAPI HandleEvents YAPI yHandleEvents Maintains the device to library communication channel function yHandleEvents errmsg function HandleEvents errmsg function yHandleEvents amp errmsg YRETCODE yHandleEvents string a
56. ESCR get_functionDescriptor YFUN_DESCR functionDescriptor function get_functionDescriptor YFUN_DESCR function get_functionDescriptor As YFUN_DESCR YFUN_DESCR get_functionDescriptor String get_functionDescriptor def get_functionDescriptor YRelay This identifier can be used to test if two instances of YFunct ion reference the same physical function on the same physical device Returns an identifier of type YFUN_DESCR If the function has never been contacted the returned value is Y_FUNCTIONDESCRIPTOR_INVALID www yoctopuce com 191 19 High level API Reference relay get_functionld YRelay relay functionld Returns the hardware identifier of the relay without reference to the module function get_functionld function get_functionld function get_functionld string get_functionld NSString functionld vo function get_functionld As String string get_functionld String get_functionld def get_functionld For example relayl Returns a string that identifies the relay ex relayl On failure throws an exception or returns Y_FUNCTIONID_INVALID 192 www yoctopuce com 19 High level API Reference relay get_hardwareld YRelay relay hardwareld Returns the unique hardware identifier of the relay in the form SERIAL FUNCTIONID function get_hardwareld function get_hardwareld function get_hardwareld string get
57. Filters 44 FindModule YModule 136 FindRelay YRelay 181 FirstModule YModule 137 FirstRelay YRelay 182 Fixing 15 FreeAPI YAPI 115 functionCount YModule 140 functionld YModule 141 functionName YModule 142 Functions 110 functionValue YModule 143 G General 19 27 110 get_advertisedValue YRelay 185 get_beacon YModule 144 get_countdown YRelay 186 get_errorMessage YModule 145 get_errorMessage YRelay 187 get_errorType YModule 146 get_errorType YRelay 188 get_firmwareRelease YModule 147 get_friendlyName YRelay 189 get_functionDescriptor YRelay 190 get_functionld YRelay 191 get_hardwareld YModule 148 get_hardwareld YRelay 192 get_icon2d YModule 149 get_lastLogs YModule 150 get_logicalName YModule 151 get_logicalName YRelay 193 get_luminosity YModule 152 get_maxTimeOnStateA YRelay 194 get_maxTimeOnStateB YRelay 195 get_module YRelay 196 get_module_async YRelay 197 get_output YRelay 198 get_persistentSettings YModule 153 get_productld YModule 154 get_productName YModule 155 get_productRelease YModule 156 get_pulseTimer YRelay 199 get_rebootCountdown YModule 157 get_serialNumber YModule 158 get_state YRelay 200 get_stateAtPowerOn YRelay 201 get_upTime YModule 159 get_usbBandwidth YModule 160 get_usbCurrent YModule 161 get_userData YModule 162 get_userData YRelay 202 GetAPIVersion YAPI 116 GetTickCount YAPI 117 H HandleEvents YAPI 118 Hazards 9 High level 109 HTTP 44 In
58. Name Changes the logical name of the module function set_logicalName newval function set_logicalName newval function set_logicalName newval int set_logicalName const string amp newval int setLogicalName NSString newval function set_logicalName newval string integer function set_logicalName ByVal newval As String As Integer int set_logicalName string newval int set_logicalName String newval def set_logicalName newval YModule target set_logicalName newval You can use yCheckLogicalName prior to this call to make sure that your parameter is valid Remember to call the saveToF lash method of the module if the modification must be kept Parameters newval a string corresponding to the logical name of the module Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 173 19 High level API Reference module set_luminosity YModule module setLuminosity Changes the luminosity of the module informative leds function set_luminosity newval function set_luminosity newval function set_luminosity newval int set_luminosity int newval int setLuminosity int newval function set_luminosity newval LongInt integer v function set_luminosity ByVal newval As Integer As Integer int set_luminosity int newval int set_luminosity int newval def set_luminosity newval YMod
59. OS 17 2 Getting ready Go to the Yoctopuce web site and download the Java for Android programming library The library is available as source files and also as a jar file Connect your modules decompress the library files in the directory of your choice and configure your Android programming environment so that it can find them To keep them simple all the examples provided in this documentation are snippets of Android applications You must integrate them in your own Android applications to make them work However your can find complete applications in the examples provided with the Java for Android library 17 3 Compatibility In an ideal world you would only need to have a smart phone running under Android to be able to make Yoctopuce modules work Unfortunately it is not quite so in the real world A machine running under Android must fulfil to a few requirements to be able to manage Yoctopuce USB modules natively 1 www yoctopuce com EN libraries php www yoctopuce com 95 17 Using the Yocto Relay with Android Android 4 x Android 4 0 api 14 and following are officially supported Theoretically support of USB host functions since Android 3 1 But be aware that the Yoctopuce Java for Android API is regularly tested only from Android 4 onwards USB host support Naturally not only must your machine have a USB port this port must also be able to run in host mode In host mode the machine literally takes
60. OS Decompress the library files in a folder of your choice accessible to your web server connect your modules run the VirtualHub software and you are ready to start your first tests You do not need to install any driver 9 2 Control of the Relay function A few lines of code are enough to use a Yocto Relay Here is the skeleton of a PHP code snipplet to use the Relay function include yocto_api php inelude Vyockon relay php 1A couple of free PHP servers easyPHP for Windows MAMP for Mac OS X www yoctopuce com EN libraries php 3 www yoctopuce com EN virtualhub php www yoctopuce com 39 9 Using Yocto Relay with PHP Get access to your device through the VirtualHub running locally yRegisterHub http 127 0 0 1 4444 Serrmsg Srelay yFindRelay RELAYLO1 123456 relayl Check that the module is online to handle hot plug if relay gt isOnline Hie UKE SGUIE E Siecle oa Let s look at these lines in more details yocto_api php and yocto_relay php These two PHP includes provides access to the functions allowing you to manage Yoctopuce modules yocto api php must always be included yocto relay php is necessary to manage modules containing a relay such as Yocto Relay 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 a
61. RS Lele ers HUOl error uE SEA Errmsg i m YModule FindModule sys argv 1 use serial or logical name if m isOnline newname sys argv 2 if not YAPI CheckLogicalName newname sys exit Invalid name newname m set_logicalName newname m saveToFlash do not forget this print Module serial m get_serialNumber name m get_logicalName algez SyS exit net connected check identification and USB cable Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the YModule saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the YModule yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not null Below a short example listing the connected modules usr bin python coding utf 8 importe OS SVS from yocto api import errmsg YRef Param 86 www yoctopuce com 15 Using the Yocto Relay with Python Setup
62. Relay relay state Returns the state of the relays A for the idle position B for the active position function get_state function get_state function get_state Y_STATE_enum get_state Y_STATE_enum state function get_state Integer function get_state As Integer int get_state int get_state def get_state YRelay target get_state Returns either Y_STATE_A or Y_STATE_B according to the state of the relays A for the idle position B for the active position On failure throws an exception or returns Y_STATE_INVALID www yoctopuce com 201 19 High level API Reference relay get_stateAtPowerOn YRelay relay stateAtPowerOn Returns the state of the relays at device startup A for the idle position B for the active position UNCHANGED for no change function get_stateAtPowerOn function get_stateAtPowerOn function get_stateAtPowerOn Y_STATEATPOWERON_enum get_stateAtPowerOn Y_STATEATPOWERON_ enum stateAtPowerOn pas_ function get_stateAtPowerOn Integer vb function get_stateAtPowerOn As Integer int get_stateAtPowerOn int get_stateAtPowerOn def get_stateAtPowerOn YRelay target get_stateAtPowerOn Returns a value among Y_STATEATPOWERON_UNCHANGED Y_STATEATPOWERON_A and Y_STATEATPOWERON_B corresponding to the state of the relays at device startup A for the idle position B for the active position UNCHANGED for no change On
63. SYSTEM usb ATTR idVendor 24e0 MODE 0666 Example 2 51 yoctopuce_group rules This rule authorizes the yoctogroup group to have read and write access to Yoctopuce USB peripherals Access rights for all other peripherals are not modified If this scenario suits you you 1 http www yoctopuce com FR virtualhub php www yoctopuce com 219 20 Troubleshooting only need to copy the 51 yoctopuce_group rules file into the etc udev rules d directory and restart your system udev rules to allow write access to all users of yoctogroup for Yoctopuce USB devices SUBSYSTEM usb ATTR idVendor 24e0 MODE 0664 GROUP yoctogroup 20 2 ARM Platforms HF and EL There are two main flavors of executable on ARM HF Hard Float binaries and EL EABI Little Endian binaries These two families are not compatible at all The compatibility of a given ARM platform with of one of these two families depends on the hardware and on the OS build ArmHL and ArmEL compatibility problems are quite difficult to detect Most of the time the OS itself is unable to make a difference between an HF and an EL executable and will return meaningless messages when you try to use the wrong type of binary All pre compiled Yoctopuce binaries are provided in both formats as two separate ArmHF et ArmEL executables If you do not know what family your ARM platform belongs to just try one executable from each family 220 www yoctopuce co
64. Sly Pacis cua NSLog Module not connected check identification and USB cable n return 0 There are only a few really important lines in this example We will look at them in details yocto_api h et yocto_relay h These two import files provide access to the functions allowing you to manage Yoctopuce modules yocto api h must always be used yocto relay h is necessary to manage modules containing a relay such as Yocto Relay 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 yFindRelay The yFindRelay function allows you to find a relay 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 Relay module with serial number RELA YLO1 123456 which you have named MyModule and for which you have given the relay function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once YRelay relay yFindRelay RELAYLO1 123456 relayl YRelay relay yFindRelay RELAYLO1 123456 MyFunction YRelay relay yFindRelay
65. YModule The unique hardware identifier is made of the device serial number followed by string module Returns a string that uniquely identifies the module www yoctopuce com 149 19 High level API Reference module gt get_icon2d YModule module gt icon2d Returns the icon of the module function get_icon2d node js function get_icon2d function get_icon2d string get_icon2d NSData icon2d function get_icon2d TByteArray function get_icon2d As Byte def get_icon2d YModule target get_icon2d The icon is a PNG image and does not exceeds 1536 bytes Returns a binary buffer with module icon in png format 150 www yoctopuce com 19 High level API Reference module gt get_lastLogs module gt lastLogs Returns a string with last logs of the module function get_lastLogs function get_lastLogs function get_lastLogs string get_lastLogs NSString lastLogs function get_lastLogs string function get_lastLogs As String string get_lastLogs String get_lastLogs def get_lastLogs YModule target get_lastLogs This method return only logs that are still in the module Returns a string with last logs of the module YModule www yoctopuce com 151 19 High level API Reference module gt get_logicalName module gt logicalName Returns the logical name of the module function get_logic
66. Yocto Relay User s guide Table of contents Me METRO GUCUIOIN ccsstescpuectaes teeta criaiind ea atte delat reat ated anc e G 1 TA PREFEQUISITOS a a a a a a a a aea a eaaa A Raa aaa iaa maa reaa Paaa aaa i iari iredi 1 1 2 Optional AcCCessori ES as iiaae ae a a a a a eea TA 3 2 PreseMtation sonin e areare a oera EEE aE A EE 5 21 COMMON SlOMONIS ooren a A N GE 5 22r SPOCINIC eeM S a e aa a Ae A aea EE ea D eare Ea 6 3 Electrocution hazards one cece cece ceseeseeseeseeseseesneeseeseeseeseeseesnssnseneeseeaeseneeeseneeeeeneeens 9 3 1 Dangerous COMPONMEMIS e622 ccc cates ede ee edena E E ie E ee E se Adie eee eerie 9 As First Steps erer aeea A EE ikke de a aie Ea EEE 11 4i Localization renren enr e a EAEE e AA a a a dee i A Aen 11 4 2 Pestofthe mod le aai aaa Taa Ea a aae a a Aaa a a A naaa ni d aada daanin ia ioiii 11 4 3 CONIQUIATION viia ar eieae T e a hid a e a ee 12 5 Assembly and connections oon cccecce esses eeseeseeseesesseeeessesceneeneeneensseeseeseeneeeeeneesens 15 Bil FIXING E E E EAE E AS E S E an sheeeiees 15 S NETO E100 91E E A E E A covet ucoeeeeeae do an eee ener ees 16 5 3 Electro magnetic relays and COIS s seseeseseeesrresrrnrsirrnsrrnnnstrnnatrnntsttnnttranttnnaettenasennnnenanae 16 5 4 USB power dIStribUtiOn 0 3 30 dessin ls ee ain visi nen lini dene UEa aT 16 6 Programming general concepts oon ceecc ee eee eeeeeeeneeseeteseeeeeseesteneeneeneeens 19 6 1 Programming paradigm aiii cect lid en eactenee
67. _hardwareld NSString hardwareld function get_hardwareld As String string get_hardwareld String get_hardwareld def get_hardwareld The unique hardware identifier is composed of the device serial number and of the hardware identifier of the relay for example RELAYLO1 123456 relayl Returns a string that uniquely identifies the relay ex RELAYLO1 123456 relayl1 On failure throws an exception or returns Y_HARDWAREID_INVALID www yoctopuce com 193 19 High level API Reference relay get_logicalName YRelay relay logicalName Returns the logical name of the relay function get_logicalName function get_logicalName function get_logicalName string get_logicalName NSString logicalName function get_logicalName string function get_logicalName As String string get_logicalName String get_logicalName def get_logicalName YRelay target get_logicalName Returns a string corresponding to the logical name of the relay On failure throws an exception or returns Y_LOGICALNAME INVALID 194 www yoctopuce com 19 High level API Reference relay get_maxTimeOnStateA YRelay relay maxTimeOnStateA Retourne the maximum time ms allowed for THEFUNCTIONS to stay in state A before automatically switching back in to B state function get_maxTimeOnStateA function get_maxTimeOnStateA function get_maxTimeOnStateA s64 get_maxTimeOnSt
68. ake tale aTe MEPA E E E T AEI EA 36 9 Using Yocto Relay with PHP oon cccs ee cesesseseesceneeseseeeneneeseeeeneenesneees 39 9 T GOting Tedy reina gni e eben E a iaie 39 9 2 Control of the Relay function sssesesssesssiesrnrssrrnnsrnrastrnesrrnnsttnattrnasttnnatiannnnnnnannnnneennnanenne 39 9 3 Control of the Module Part ccececceeeeeeseeeceeeeeeeeseaeeeetenesseeaneeeesesnadacceneesesseaeneesasatsaeaceenes 41 9 4 HTTP callback API and NAT filters oo ccc ccccccccccceeeeeeeeceeeeeceeeeeceseeeeusseeeeeeeeeeeeeeeseeeeeaes 44 9 5 Error Wand ling r aa a a aa a ae e aa ataaeaecesheabcs lean cad aAA Aae EEE Eae cul deiadubeaeeyvevsbichet ch 47 10 Using Yocto Relay with C occ esesseeseesneseesnesnsenseneeseeseeenesnseneeneess 49 10 1 Control of the Relay function esssssssssesrrssssrnessrnrsesrnnsrernsrnratrrntnetrnnnsetnnattannnennetnennennnnne 49 10 2 Control of the module part sssesssssssssresssrrssrrnrsrnrnssrnnnrrnannttnntnetantttnnttenatntansnannetnannnennnannnnne 51 KO Eea AONAIS UAT M EEEE ene E EATA E E AE ET 53 10 4 Integration variants for the C Yoctopuce library ccccccceeeeceeeeeeeeeeeeeeneeeeeeeeeeeneeeeeeees 54 11 Using Yocto Relay with Objective C oo cece eeeestesteeseeteeseenen 57 11 1 Control of the Relay function oo eeeeeeeeneeeeeeeeeeeeeaeeeteeaeeeeeeaeeeeseaeeeeseaeeeeseeaeeseaaeeey 57 12 Controkor the module Part a thee thei nvaad eee e aie 59 11 3 ErrORhangling ccceeciist Sess
69. alName function get_logicalName function get_logicalName string get_logicalName NSString logicalName function get_logicalName string function get_logicalName As String string get_logicalName String get_logicalName def get_logicalName YModule target get_logicalName Returns a string corresponding to the logical name of the module On failure throws an exception or returns Y_LOGICALNAME_INVALID YModule 152 www yoctopuce com 19 High level API Reference module gt get_luminosity YModule module gt luminosity Returns the luminosity of the module informative leds from 0 to 100 function get_luminosity function get_luminosity function get_luminosity int get_luminosity int luminosity function get_luminosity LongInt function get_luminosity As Integer int get_luminosity int get_luminosity def get_luminosity YModule target get_luminosity Returns an integer corresponding to the luminosity of the module informative leds from 0 to 100 On failure throws an exception or returns Y_LUMINOSITY_INVALID www yoctopuce com 153 19 High level API Reference module gt get_persistentSettings YModule module gt persistentSettings Returns the current state of persistent module settings function get_persistentSettings function get_persistentSettings function get_persistentSettings Y_PERSISTENTSETTINGS_ en
70. ally the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface 12 3 Control of the Relay function A few lines of code are enough to use a Yocto Relay Here is the skeleton of a Visual Basic code snipplet to use the Relay function e Dim errmsg As String errmsg Dim relay As YRelay REM Get access to your device connected locally on USB for instance yRegisterHub usb errmsg relay yFindRelay RELAYLO1 123456 relay1 REM Hot plug 1s easy Just Cheek Ghat the device is online If relay isOnline Then REM USE PEETAV OERS tcl iene i meter End If Let s look at these lines in more details yRegisterHub The yRegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for When used with the parameter usb it will use the modules locally connected to the computer running the library If the initialization does not succeed this function returns a value different from YAPI SUCCESS and errmsg contains the error message yFindRelay The yFindRelay function allows you to find a relay 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 Relay module with serial number RELA YLO1 123456 which you have named MyModule and for which you have given the relay function the name MyFunction The follo
71. ame of the module as set by the factory module get_productRelease Returns the hardware release version of the module module get_rebootCountdown Returns the remaining number of seconds before the module restarts or zero when no reboot has been scheduled module gt get_serialNumber Returns the serial number of the module as set by the factory module get_upTime Returns the number of milliseconds spent since the module was powered on module get_usbBandwidth Returns the number of USB interfaces used by the module module get_usbCurrent Returns the current consumed by the module on the USB bus in milli amps module get_userData Returns the value of the userData attribute as previously stored using method set_userData module gt isOnline Checks if the module is currently reachable without raising any error module isOnline_async callback context Checks if the module is currently reachable without raising any error module load msValidity Preloads the module cache with a specified validity duration module load_async msValidity callback context Preloads the module cache with a specified validity duration asynchronous version module nextModule Continues the module enumeration started using yFirstModule module gt reboot secBeforeReboot Schedules a simple module reboot after the given number of seconds module gt revertFromFlash Reloads the settings stored in the n
72. ameters removalCallback a procedure taking a YModule parameter or null www yoctopuce com 123 19 High level API Reference YAPI RegisterHub YAPI yRegisterHub Setup the Yoctopuce library to use modules connected on a given machine function yRegisterHub url errmsg node js function RegisterHub url errmsg php function yRegisterHub url amp errmsg YRETCODE yRegisterHub const string amp url string amp errmsg YRETCODE yRegisterHub NSString url NSError errmsg function yRegisterHub url string var errmsg string integer function yRegisterHub ByVal url As String ByRef errmsg As String As Integer int RegisterHub string url ref string errmsg synchronized static int RegisterHub String url def RegisterHub url errmsg None The parameter will determine how the API will work Use the follwing values usb When the usb keyword is used the API will work with devices connected directly to the USB bus Some programming languages such a Javascript PHP and Java don t provide direct access to USB harware so usb will not work with these In this case use a VirtualHub or a networked YoctoHub see below X X X X or hostname The API will use the devices connected to the host with the given IP address or hostname That host can be a regular computer running a VirtualHub or a networked YoctoHub such as YoctoHub Ethernet or YoctoHub Wireless If you want to use the VirtualHub running on you lo
73. ant 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 package com yoctopuce doc_ examples import android app Activity import android os Bundle import android view View import android widget AdapterView import android widget AdapterView OnItemSelectedListener import android widget ArrayAdapter import android widget EditText import android widget Spinner import android widget TextView import android widget Toast import com yoctopuce YoctoAPI YAPI import com yoctopuce YoctoAPI YAPI Exception import com yoctopuce YoctoAPI YModule public class SaveSettings extends Activity implements OnItemSelectedListener private ArrayAdapter lt String gt aa private YModule module null Override public void onCreate Bundle savedInstanceState super onCreate savedinstancestate setContentView R layout savesettings Spinner my spin Spinner
74. appnotes app_pdfs 13c3236 pdf 16 www yoctopuce com 5 Assembly and connections In theory a USB port provides 100mA and may provide up to 500mA if available and requested by the device In the case of a hub without external power supply 100mA are available for the hub itself and the hub should distribute no more than 100mA to each of its ports This is it and this is not much In particular it means that in theory it is not possible to connect USB devices through two cascaded hubs without external power supply In order to cascade hubs it is necessary to use self powered USB hubs that provide a full 500mA to each subport In practice USB would not have been as successful if it was really so picky about power distribution As it happens most USB hub manufacturers have been doing savings by not implementing current limitation on ports they simply connect the computer power supply to every port and declare themselves as self powered hub even when they are taking all their power from the USB bus in order to prevent any power consumption check in the operating system This looks a bit dirty but given the fact that computer USB ports are usually well protected by a hardware current limitation around 2000mA it actually works in every day life and seldom makes hardware damage What you should remember if you connect Yoctopuce modules through one or more USB hub without external power supply you have no safe guard and you depend e
75. ascript It uses a callback instead of a return value in order to avoid blocking Firefox javascript VM that does not implement context switching during blocking I O calls See the documentation section on asynchronous Javascript calls for more details Parameters msValidity an integer corresponding to the validity of the loaded module parameters in milliseconds callback callback function that is invoked when the result is known The callback function receives three arguments the caller specific context object the receiving module object and the error code or YAPT_SUCCESS context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback www yoctopuce com 167 19 High level API Reference module gt nextModule YModule Continues the module enumeration started using yFirstModule is _ function nextModule node js function nextModule php_ function nextModule cpp _ YModule nextModule YModule nextModule function nextModule TYModule vb _ function nextModule As YModule YModule nextModule YModule nextModule def nextModule Returns a pointer to a YModu1e object corresponding to the next module found or a nu11 pointer if there are no more modules to enumerate 168 www yoctopuce com 19 High level API Reference module reboot Schedules a simple module reboo
76. at the device is online if relay isOnline Use relay set_state lh ee ool Let us look at these lines in more details YAPI EnableUSBHost The YAPI EnableUSBHost function initializes the API with the Context of the current application This function takes as argument an object of the android content Context class or of a subclass If you intend to connect your application only to other machines through the network this function is facultative YAPI RegisterHub The yAPI RegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for The parameter is the address of the virtual hub able to see the devices If the string usb is passed as parameter the API works with modules locally connected to the machine If the initialization does not succeed an exception is thrown YRelay FindRelay The YRelay FindRelay function allows you to find a relay 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 Relay module with serial number RELAYLO1 123456 which you have named MyModule and for which you have given the relay7 function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once relay YRelay FindRelay RELAYLO1 123456 relayl relay YRelay FindRelay RELAYLO1
77. ateA s64 maxTimeOnStateA function get_maxTimeOnStateA int64 function get_maxTimeOnStateA As Long long get_maxTimeOnStateA long get_maxTimeOnStateA def get_maxTimeOnStateA YRelay target get_maxTimeOnStateA Zero means no maximum time Returns an integer On failure throws an exception or returns Y_MAXTIMEONSTATEA_INVALID www yoctopuce com 195 19 High level API Reference relay get_maxTimeOnStateB YRelay relay maxTimeOnStateB Retourne the maximum time ms allowed for THEFUNCTIONS to stay in state B before automatically switching back in to A state function get_maxTimeOnStateB function get_maxTimeOnStateB function get_maxTimeOnStateB s64 get_maxTimeOnStateB s64 maxTimeOnStateB function get_maxTimeOnStateB int64 function get_maxTimeOnStateB As Long long get_maxTimeOnStateB long get_maxTimeOnStateB def get_maxTimeOnStateB Y Relay target get_maxTimeOnStateB Zero means no maximum time Returns an integer On failure throws an exception or returns Y_MAXTIMEONSTATEB_INVALID 196 www yoctopuce com 19 High level API Reference relay get_module YRelay relay module Gets the YModu1e object for the device on which the function is located function get_module function get_module function get_module YModule get_module YModule module function get_module TYModule function get_module As
78. ation of the timeout in milliseconds arguments additional arguments to be passed to the callback function can be provided if needed not supported on Microsoft Internet Explorer Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 129 19 High level API Reference YAPI Sleep YAPI ySleep Pauses the execution flow for a specified duration function ySleep ms_duration errmsg function Sleep ms_duration errmsg function ySleep ms_duration amp errmsg YRETCODE ySleep unsigned ms_duration string amp errmsg YRETCODE ySleep unsigned ms_duration NSError errmsg function ySleep ms_duration integer var errmsg string integer function ySleep ByVal ms_duration As Integer ByRef errmsg As String As Integer int Sleep int ms_duration ref string errmsg int Sleep long ms_duration def Sleep ms_duration errmsg None This function implements a passive waiting loop meaning that it does not consume CPU cycles significatively The processor is left available for other threads and processes During the pause the library nevertheless reads from time to time information from the Yoctopuce modules by calling yHandleEvents in order to stay up to date This function may signal an error in case there is a communication problem while contacting a module Parameters ms_duration an integer corresponding to the duratio
79. bBandwidth YModule 174 set_userData YModule 175 set_userData YRelay 216 SetDelegate YAPI 127 SetTimeout YAPI 128 Sleep YAPI 129 Source 83 Start 25 T Test 11 triggerFirmwareUpdate YModule 176 Troubleshooting 219 U UnregisterHub YAPI 130 UpdateDeviceList YAPI 131 UpdateDeviceList_async YAPI 132 V Variants 54 VirtualHub 95 Visual 63 69 W wait_async YModule 177 wait_async YRelay 217 Y YAPI 111 132 yCheckLogicalName 111 yDisableExceptions 112 yEnableExceptions 113 yEnableUSBHost 114 yFindModule 136 yFindRelay 181 yFirstModule 137 yFirstRelay 182 yFreeAPI 115 yGetAPIVersion 116 yGetTickCount 117 yHandleEvents 118 ylnitAPI 119 YModule 136 177 Yocto Relay 20 27 31 39 49 57 63 69 77 83 89 95 yPreregisterHub 120 yRegisterDeviceArrivalCallback 121 yRegisterDeviceRemovalCallback 122 yRegisterHub 123 yRegisterHubDiscoveryCallback 124 yRegisterLogFunction 125 YRelay 181 217 ySelectArchitecture 126 ySetDelegate 127 ySetTimeout 128 ySleep 129 yUnregisterHub 130 yUpdateDeviceList 131 yUpdateDeviceList_async 132
80. braries 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 OCC Kase Wy Batear ioe yochoSstent oul Bayne plane an muelo LAO handed Integration as a dynamic library Integration of the Yoctopuce library as a dynamic library allows you to produce an executable smaller than with the two previous methods and to possibly update this library if a patch reveals itself necessary without needing to recompile the source code of the application On the other hand it is an integration mode which systematically requires you to copy the dynamic library on the target machine where the application will run yocto dll for Windows libyocto so 1 0 1 for Mac OS X and Linux To integrate the dynamic Yoctopuce library to your project you must include the Sources directory of the Yoctopuce library into your IncludePath and add the sub directory Binaries corresponding to your operating system into your LibPath Then for you project to build correctly you need to link with your project the dynamic Yoctopuce library and the prerequisite system libraries e For Windows yocto lib e For Mac OS X libyocto l OKit framework and CoreFoundation framework e For Linux libyocto libm libpthread libusb1 0 and libstdc With GCC the command line to compile is simply cic S52 Sllvereteo ilink a oaeee Iiulsioy ik y Sllishuckesrsr www y
81. brary throws an exception In this case there are three possibilities e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the most desirable the Yoctopuce library offers another possibility for error handling allowing you to create a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get _state method returns a Y STATE INVALID value a get _currentValue method returns a Y CURRENTVALUE INVALID value and so on In any case the returned value is of the expected type and is not a null pointer which would risk crashing your program At worst if you display the value without testing it it will be outside the expected bounds for the returned value In the case of functions which do not normally return information the return value is YAPI_ SUCCESS if everything
82. cal computer use the IP address 127 0 0 1 callback that keywork make the API run in HTTP Callback mode This a special mode allowing to take control of Yoctopuce devices through a NAT filter when using a VirtualHub ou a networked YoctoHub You only need to configure your hub to call your server script on a regular basis This mode is currently available for PHP and Node JS only Be aware that only one application can use direct USB access at a given time on a machine Multiple access would cause conflicts while trying to access the USB modules In particular this means that you must stop the VirtualHub software before starting an application that uses direct USB access The workaround for this limitation is to setup the library to use the VirtualHub rather than direct USB access If acces control has been activated on the hub virtual or not you want to reach the URL parameter should look like http username password adresse port You can call RegisterHub several times to connect to several machines Parameters url a string containing either usb callback or the root URL of the hub to monitor errmsg a string passed by reference to receive any error message Returns YAPI SUCCESS when the call succeeds On failure throws an exception or returns a negative error code 124 www yoctopuce com 19 High level API Reference YAPI RegisterHubDiscoveryCallback YAPI yRegisterHubDiscoveryCallback Regi
83. case there are three possibilities e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the most desirable the Yoctopuce library offers another possibility for error handling allowing you to create a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get _state method returns a Y STATE INVALID value a get _currentValue method returns a Y CURRENTVALUE INVALID value and so on In any case the returned value is of the expected type and is not a null pointer which would risk crashing your program At worst if you display the value without testing it it will be outside the expected bounds for the 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 co
84. ceArrivalCallback yDeviceUpdateFunc arrivalCallback synchronized static void RegisterDeviceArrivalCallback DeviceArrivalCallback arrivalCallback def RegisterDeviceArrivalCallback arrivalCallback This callback will be invoked while yUpdat eDeviceList is running You will have to call this function on a regular basis Parameters arrivalCallback a procedure taking a YModule parameter or null 122 www yoctopuce com 19 High level API Reference YAPI RegisterDeviceRemovalCallback YAPI yRegisterDeviceRemovalCallback Register a callback function to be called each time a device is unpluged function yRegisterDeviceRemovalCallback removalCallback function RegisterDeviceRemovalCallback removalCallback function yRegisterDeviceRemovalCallback removalCallback void yRegisterDeviceRemovalCallback yDeviceUpdateCallback removalCallback void yRegisterDeviceRemovalCallback yDeviceUpdateCallback removalCallback procedure yRegisterDeviceRemovalCallback removalCallback yDeviceUpdateFunc procedure yRegisterDeviceRemovalCallback ByVal removalCallback As yDeviceUpdateFunc void RegisterDeviceRemovalCallback yDeviceUpdateFunc removalCallback synchronized static void RegisterDeviceRemovalCallback DeviceRemovalCallback removalCallback def RegisterDeviceRemovalCallback removalCallback This callback will be invoked while yUpdateDeviceList is running You will have to call this function on a regular basis Par
85. cesState setContentView R layout modulecontrol Spinner my spin Spinner findViewById R id spinner1 my spin setOnItemSelectedListener this aa new ArrayAdapter lt String gt this android R layout simple spinner item aa setDropDownViewResource android R layout simple spinner dropdown_item my spin setAdapter aa Override protected void onStart 100 www yoctopuce com 17 Using the Yocto Relay with Android super onStart 7 ry aa clear YAPI EnableUSBHost this YAPI RegisterHub usb YModule r YModule FirstModule while r null String hwid r get_hardwareId aa add hwid r r nextModule k Gewei CIAR Mpxcicjpicseim I enprime otac kurace refresh Spinner with detected relay aa notifyDataSetChanged Override protected void onStop super onstop YAPI FreeAPI private void DisplayModuleInfo TextView field if module null iste wucins ery field field se field field se field field se field field se TextView findViewById R id serialfield Text module getSerialNumber TextView findViewById R id logicalnamefield Text module getLogicalName TextView findViewById R id luminosityfield Text String format Sd3 5 module getLuminosity TextView findViewById R id uptimefield Text nodule getUpTime 1000 sec field TextView findViewById R id usbcurrentfield
86. ch Other versions of the Linux kernel and even other UNIX variants are very likely to work as well as Linux support is implemented through the standard libusb API Yoctopuce is frequently testing its modules on Linux kernel 2 6 Android versions currently supported are Android 3 1 and later Moreover it is necessary for the tablet or phone to support the Host USB mode Yoctopuce is frequently testing its modules on Android 4 x on a Nexus 7 and a Samsung Galaxy S3 with the Java for Android library A USB cable type A micro B USB connectors exist in three sizes the standard size that you probably use to connect your printer the very common mini size to connect small devices and finally the micro size often used to connect mobile phones as long as they do not exhibit an apple logo All USB modules manufactured by Yoctopuce use micro size connectors The most common USB 2 connectors A B Mini B Micro A Micro B To connect your Yocto Relay 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 Relay module with a USB cable of type A micro B 2 The HID driver is the one that takes care of the mouse the keyboard etc 3 Although they
87. 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 e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the most desirable the Yoctopuce library offers another possibility for error handling allowing you to
88. command line When you want to perform a punctual operation on your Yocto Relay such as reading a value assigning a logical name and so on you can obviously use the Virtual Hub but there is a simpler faster and more efficient method the command line API The command line API is a set of executables one by type of functionality offered by the range of Yoctopuce products These executables are provided pre compiled for all the Yoctopuce officially supported platforms OS Naturally the executable sources are also provided 7 1 Installing Download the command line API You do not need to run any setup simply copy the executables corresponding to your platform OS in a directory of your choice You may add this directory to your PATH variable to be able to access these executables from anywhere You are all set you only need to connect your Yocto Relay open a shell and start working by typing for example YRelay any set_state B To use the command API on Linux you need either have root privileges or to define an udev rule for your system See the Troubleshooting chapter for more details 7 2 Use general description All the command line API executables work on the same principle They must be called the following way 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 sa
89. content Context or any subclasee It is not necessary to call this function to reach modules through the network Parameters osContext an object of class android content Context or any subclass www yoctopuce com 115 19 High level API Reference YAPI FreeAPI YAPI yFreeAPI Frees dynamically allocated memory blocks used by the Yoctopuce library is _ function yFreeAPI node js function FreeAPI php _ function yFreeAPI void yFreeAPI void yFreeAPI procedure yFreeAPI procedure yFreeAPI void FreeAPI synchronized static void FreeAPI def FreeAPI It is generally not required to call this function unless you want to free all dynamically allocated memory blocks in order to track a memory leak for instance You should not call any other library function after calling yF reeAPI or your program will crash 116 www yoctopuce com 19 High level API Reference YAPI GetAPIVersion YAPI yGetAPIVersion Returns the version identifier for the Yoctopuce library in use function yGetAPIVersion function GetAPIVersion function yGetAPIVersion string yGetAPIVersion NSString yGetAP IVersion function yGetAPIVersion string function yGetAPIVersion As String String GetAPIVersion String GetAPIVersion def GetAP IVersion The version is a string in the form Major Minor Build for instance 1 01 5535 For languages using an external
90. control of the devices which are connected to it The USB ports of a desktop computer for example work in host mode The opposite of the host mode is the device mode USB keys for instance work in device mode they must be controlled by a host Some USB ports are able to work in both modes they are OTG On The Go ports It so happens that many mobile devices can only work in device mode they are designed to be connected to a charger or a desktop computer and nothing else It is therefore highly recommended to pay careful attention to the technical specifications of a product working under Android before hoping to make Yoctopuce modules work with it Unfortunately having a correct version of Android and USB ports working in host mode is not enough to guaranty that Yoctopuce modules will work well under Android Indeed some manufacturers configure their Android image so that devices other than keyboard and mass storage are ignored and this configuration is hard to detect As things currently stand the best way to know if a given Android machine works with Yoctopuce modules consists in trying Supported hardware The library is tested and validated on the following machines e Samsung Galaxy S3 e Samsung Galaxy Note 2 e Google Nexus 5 e Google Nexus 7 e Acer Iconia Tab A200 e Asus Tranformer Pad TF300T e Kurio 7 If your Android machine is not able to control Yoctopuce modules natively you still have the possibility to remotely contr
91. create a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get _state method returns a Y STATE INVALID value a get _currentValue method returns a Y CURRENTVALUE INVALID value and so on In any case the returned value is of the expected type and is not a null pointer which would risk crashing your program At worst if you display the value without testing it it will be outside the expected bounds for the returned value In the case of functions which do not normally return information the return value is YAPI SUCCESS if everything went well and a different error code in case of failure When you work without exceptions you can obtain an error code and an error message explaining the source of the error You can request them from the object which returned the error calling the 74 www yoctopuce com 13 Using Yocto Relay with C errType and errMessage methods Their returned values contain the same information as in the exceptions when they are active www yoctopuce com 75
92. ction get_beacon Y_BEACON_enum get_beacon Y_BEACON_enum beacon function get_beacon Integer function get_beacon As Integer int get_beacon int get_beacon def get_beacon YModule target get_beacon Returns YModule either Y_BEACON_OFF or Y_BEACON_ON according to the state of the localization beacon On failure throws an exception or returns Y_BEACON_INVALID www yoctopuce com 145 19 High level API Reference module get_errorMessage module errorMessage Returns the error message of the latest error with this module object function get_errorMessage function get_errorMessage function get_errorMessage string get_errorMessage NSString errorMessage function get_errorMessage string function get_errorMessage As String string get_errorMessage String get_errorMessage def get_errorMessage This method is mostly useful when using the Yoctopuce library with exceptions disabled YModule Returns a string corresponding to the latest error message that occured while using this module object 146 www yoctopuce com 19 High level API Reference module get_errorType YModule module errorType Returns the numerical error code of the latest error with this module object function get_errorType function get_errorType function get_errorType YRETCODE get_errorType function get_errorType YRETCODE function get_e
93. ctive By default the light of these leds is rather strong but you can modify the luminosity www yoctopuce com 7 www yoctopuce com 3 Electrocution hazards While the Yocto Relay module is perfectly able to manage a 160V voltage we strongly discourage you to work on a voltage high enough to present risks Nevertheless if you decide to override this advice respect these recommendations they may well protect you from an embarrassing nomination to the Darwin Awards e Use your head your luck won t last forever e Don t work if you are tired Brilliant decisions taken at 2 a m tend to lose their shine at first light e Do not work under the influence of euphoriant substances Beware of family reunions they are known for their large amount of die offs among the DIY population e Don t work alone If things go bad you can then hope to be rescued fast enough 3 1 Dangerous components Some components of the Yocto Relay module find themselves directly on the relay working tension Make sure to never touch them when the module is powered on These components must never be in contact with a conductive component of your project look out for metallic enclosures Even more important make sure that your project end user can never touch these components even accidentally fi m o 2 Jaisi ea f e a per gt m l c emo eL io G m9 SX m o 3 e h eg zamra 5 H e Ll Potentially dangerous components of the Yoct
94. d Yocto Relay of the Yoctopuce library In this example you will recognize the functions explained above but this time used with all side materials needed to make it work nicely as a small demo using System using oystem Collections Cenere using System Ling using System Text namespace ConsoleApplicationl class Program static void usage string execname System AppDomain CurrentDomain FriendlyName Console WriteLine Usage ConsolerWrilttelmme excename tues lt s erm cllemumber gt ay Arse ui Console Writehine excename te lt Logucal inane s AN S Bi 5 Console WriteLine execnamet any A B System Threading Thread Sleep 2500 Environment Exit 0 static void Main string args string errmsg string target YRelay relay string state if args Length lt 2 usage target args 0 ToUpper state args 1 ToUpper if YAPI RegisterHub usb ref errmsg YAPI SUCCESS Console WriteLine RegisterHub error errmsg Environment Exit 0 if target ANY relay YRelay FirstRelay if relay null Console WriteLine No module connected check USB cable Environment Exit 0 else sellay YR lay HindRelayltarge t rellayi if relay isOnline aie stews WAH wedleny ger _sicchtee MRSleny SVAMI 20 e olee relay SSI _SieeicS YRelay STATE B else Console WriteLine Module not connected
95. d to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the saveToF lash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not NULL Below a short example listing the connected modules import lt Foundation Foundation h gt i EUMD Ore Eau uy O Ct okap mmi 60 www yoctopuce com 11 Using Yocto Relay with Objective C int maim Vink arge const char cise NSError error autoreleasepool Setup the API to use local USB devices if yRegisterHub usb amp error YAPT SUCCESS NSLog RegisterHub error n error localizedDescription return 1 NSLog Device list n YModule module yFirstModule while module nil NSLog S 3 module serialNumber module productName module module nextModule return 0 11 3 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is
96. ddress 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 yFindRelay The yFindRelay function allows you to find a relay 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 Relay module with serial number RELA YLO1 123456 which you have named MyModule and for which you have given the relay function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once Srelay yFindRelay RELAYLO1 123456 relayl Srelay yFindRelay RELAYLO1 123456 MyFunction Srelay yFindRelay MyModule relayl Srelay yFindRelay MyModule MyFunction Srelay yFindRelay MyFunction yFindRe lay returns an object which you can then use at will to control the relay isOnline The isOnline method of the object returned by yFindRelay allows you to know if the corresponding module is present and in working order set_state The set _state method of the objet returned by yFindRelay switches the relay position to one of its two outputs The two possible parameter values are Y STATE A for output A and Y STATE _B for output B A real example Open your preferred text editor copy the code
97. de 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 68 www yoctopuce com 13 Using Yocto Relay with C C pronounced C Sharp is an object oriented programming language promoted by Microsoft it is somewhat similar to Java Like Visual Basic and Delphi it allows you to create Windows applications quite easily All the examples and the project models are tested with Microsoft C 2010 Express freely available on the Microsoft web site 13 1 Installation Download the Visual C Yoctopuce library from the Yoctopuce web site There is no setup program simply copy the content of the zip file into the directory of your choice You mostly need the content of the Sources directory The other directories contain the documentation and a few sample programs All sample projects are Visual C 2010 projects if you are using a previous version you may have to recreate the projects structure from scratch 13 2 Using the Yoctopuce API in a Visual C project The Visual C NET Yoctopuce library is composed of a DLL and of source files in Visual C The DLL is not a NET DLL but a classic DLL written in C which
98. desirable the Yoctopuce library offers another possibility for error handling allowing you to create a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get _state method returns a Y STATE INVALID value a get _currentValue method returns a Y CURRENTVALUE INVALID value and so on In any case the returned value is of the expected type and is not a null pointer which would risk crashing your program At worst if you display the value without testing it it will be outside the expected bounds for the returned value In the case of functions which do not normally return information the return value is YAPI SUCCESS if everything went well and a different error code in case of failure When you work without exceptions you can obtain an error code and an error message explaining the source of the error You can request them from the object which returned the error calling the errType and errMessage methods Their returned values contain the same information as in the exceptions when they are act
99. e the exception makes your program crash bang As this latest situation is not the most desirable the Yoctopuce library offers another possibility for error handling allowing you to create a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get state method returns a Y STATE INVALID value a get _currentValue method returns a Y CURRENTVALUE INVALID value and so on In any 36 www yoctopuce com 8 Using Yocto Relay with Javascript 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
100. e error handling is the use of exceptions By default it is the behavior of the Yoctopuce library If an error happens while you try to access a module the library throws an exception In this case there are three possibilities e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the most desirable the Yoctopuce library offers another possibility for error handling allowing you to create a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get _state method returns a Y STATE INVALID value 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
101. e fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to i1sOnline and which could crash the software In the Java API error handling is implemented with exceptions Therefore you must catch and handle correctly all exceptions that might be thrown by the API if you do not want your software to crash as soon as you unplug a device www yoctopuce com 93 94 www yoctopuce com 17 Using the Yocto Relay with Android To tell the truth Android is not a programming language it is an operating system developed by Google for mobile appliances such as smart phones and tablets But it so happens that under Android everything is programmed with the same programming language Java Nevertheless the programming paradigms and the possibilities to access the hardware are slightly different from classical Java and this justifies a separate chapter on Android programming 17 1 Native access and VirtualHub In the opposite to the classical Java API the Java for Android API can access USB modules natively However as there is no VirtualHub running under Android it is not possible to remotely control Yoctopuce modules connected to a machine under Android Naturally the Java for Android API remains perfectly able to connect itself to a VirtualHub running on another
102. e 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 lt HTML gt lt HEAD gt lt TITLE gt Change module settings lt TITLE gt 34 www yoctopuce com 8 Using Yocto Relay with Javascript lt SCRIPT type text javascript sre yocto api js gt lt SCRIPI gt lt SCRIPT language javascriptl 5 type text JavaScript gt Bho Use explicit error handling rather than exceptions yDisableExceptions Setup the API to use the VirtualHub on local machine if yRegisterHub http 127 0 0 1 4444 YAPI_ SUCCESS alene Mcannot contact VariualHub on T27 0N0 Tni var module function refresh var Serial document gethillementByid serrall value if serial Detect any conected module suitable for the demo module yFirstModule nextModule if module serial module wget serialliNumbex document getElementBylId seria
103. e output state of the relays when used as a simple switch single throw function set_output newval function set_output newval function set_output newval int set_output Y_OUTPUT_enum newval int setOutput Y_OUTPUT_enum newval pas function set_output newval Integer integer vo function set_output ByVal newval As Integer As Integer int set_output int newval int set_output int newval def set_output newval YRelay target set_output newval Parameters newval either Y_OUTPUT_OFF or Y_OUTPUT_ON according to the output state of the relays when used as a simple switch single throw Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code 214 www yoctopuce com 19 High level API Reference relay set_state relay setState Changes the state of the relays A for the idle position B for the active position function set_state newval function set_state newval function set_state newval int set_state Y_STATE_enum newval int setState Y_STATE_enum newval function set_state newval Integer integer function set_state ByVal newval As Integer As Integer int set_state int newval int set_state int newval def set_state newval YRelay target set_state newval Parameters B for the active position Returns YAPI SUCCESS if the call succeeds On failure throws an exception or returns a ne
104. e read thanks to a method of type YModule get xxxx and properties which are not read only can be modified with the help of the YModule set xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding YModule set xxx function However this modification is performed only in the random access memory RAM of the module if the module is restarted the modifications are lost To memorize them persistently it is necessary to ask the module to save its current configuration in its permanent memory To do so use the YModule saveToFlash method Inversely it is possible to force the module to forget its current settings by using the YModule revertFromFlash method The short example below allows you to modify the logical name of a module import com yoctopuce YoctoAPI public class Demo pabiros tarbe Vold maim SEn AJIT args cEy 4 setup the API to use local VirtualHub VARI Regis terHub T en 10r ar nha catch YAPT Exception ex SVSECMOUE OE Intlin Uwe anne contd cies Mirecud l HuUbkron len ORO ex getLocalizedMessage System out printin Ensure that the VirtualHub application is running System exit 1 if args length 2 System out printin usage demo lt serial or logical name gt lt new logical name gt System exit 1 YModule m String ne
105. eToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the YModule yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not null Below a short example listing the connected modules using System USING oystem Collections Gener ie using System Ling using System Text namespace ConsoleApplicationl www yoctopuce com 73 13 Using Yocto Relay with C class Program static void Main string args YModule m string errmsg wi r if YAPI RegisterHub usb ref errmsg YAPI SUCCESS Console Wrabelane MRegusterhub errors A errno Environment Exit 0 Console WriteLine Device list m YModule FirstModule while m null1 Console WriteLine m get serialNumber m get productName m m nextModule m E 13 5 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your
106. ed the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software In the Java API for Android error handling is implemented with exceptions Therefore you must catch and handle correctly all exceptions that might be thrown by the API if you do not want your software to crash soon as you unplug a device www yoctopuce com 105 106 www yoctopuce com 18 Advanced programming The preceding chapters have introduced in each available language the basic programming functions which can be used with your Yocto Relay module This chapter presents in a more generic manner a more advanced use of your module Examples are provided in the language which is the most popular among Yoctopuce customers that is C Nevertheless
107. ed validity duration is__ function load msValidity node js function load msValidity php function load msValidity YRETCODE load int msValidity YRETCODE load int msValidity function load msValidity integer YRETCODE function load ByVal msValidity As Integer As YRETCODE YRETCODE load int msValidity int load long msValidity def load msValidity By default whenever accessing a device all module attributes are kept in cache for the standard duration 5 ms This method can be used to temporarily mark the cache as valid for a longer period in order to reduce network trafic for instance Parameters msValidity an integer corresponding to the validity attributed to the loaded module parameters in milliseconds Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code 166 www yoctopuce com 19 High level API Reference module load_async YModule Preloads the module cache with a specified validity duration asynchronous version function load_async msValidity callback context function load_async msValidity callback context By default whenever accessing a device all module attributes are kept in cache for the standard duration 5 ms This method can be used to temporarily mark the cache as valid for a longer period in order to reduce network trafic for instance This asynchronous version exists only in Jav
108. elayl RELAY module is already con therefore be used ina LO1 123456 relayl if the nected or Relay BadCustomeName relay has not yet been connected This method does not trigger any USB or TCP transaction and can debugger unresolved if the module Returns a string that describes the relay ex Relay MyCustomName relayl RELAYLO1 123456 relayl www yoctopuce com 185 19 High level API Reference relay get_advertisedValue YRelay relay advertisedValue Returns the current value of the relay no more than 6 characters function get_advertisedValue function get_advertisedValue function get_advertisedValue string get_advertisedValue NSString advertisedValue function get_advertisedValue string function get_advertisedValue As String string get_advertisedValue String get_advertisedValue def get_advertisedValue YRelay target get_advertisedValue Returns a string corresponding to the current value of the relay no more than 6 characters On failure throws an exception or returns Y_ADVERTISEDVALUE_INVALID 186 www yoctopuce com 19 High level API Reference relay get_countdown YRelay relay countdown Returns the number of milliseconds remaining before a pulse delayedPulse call When there is no scheduled pulse returns zero function get_countdown function get_countdown function get_countdown
109. enca 2 usage argv 0 YModule module yFindModule argv 1 use serial or logical name if module gt isOnline sae fence S 2 if string argv 2 ON else module gt set_beacon Y_ BEACON ON module gt set_beacon Y_ BEACON OFF cout lt lt serial lt lt module gt get_serialNumber lt lt endl cout lt lt logical name lt lt module gt get_logicalName lt lt endl COE lt lt Lume Satya lt lt module gt get_luminosity lt lt endl cout lt lt beacon ue if module gt get_beacon Y_BEACON_ON cout lt ON lt endl else cout lt OFP lt lt endl cout lt lt upTime u oee moguls ger votime h 1000 lt lt H EEN lt lt encu COU lt lt USB current H cs TOCNE Seis Wisloleuhemsine lt lt 4 wv lt lt lt e cout lt lt logs lt lt endl lt lt module get lasithoegs lt lt endl else cout lt lt argv 1 lt lt not connected check identification and USB cable lt lt endl return 0 Each property xxx of the module can be read thanks to a method of type get _xxxx and properties which are not read only can be modified with the help of the set xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding set xxx function However this modification
110. errmsg synchronized static int PreregisterHub String url def PreregisterHub url errmsg None This function has the same purpose and same arguments as RegisterHub but does not trigger an error when the selected hub is not available at the time of the function call This makes it possible to register a network hub independently of the current connectivity and to try to contact it only when a device is actively needed 7 Parameters url a string containing either usb callback or the root URL of the hub to monitor errmsg a string passed by reference to receive any error message Returns YAP I SUCCESS when the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 121 19 High level API Reference YAPI RegisterDeviceArrivalCallback YAPI yRegisterDeviceArrivalCallback Register a callback function to be called each time a device is pluged function yRegisterDeviceArrivalCallback arrivalCallback nodejs function RegisterDeviceArrivalCallback arrivalCallback function yRegisterDeviceArrivalCallback arrivalCallback void yRegisterDeviceArrivalCallback yDeviceUpdateCallback arrivalCallback void yRegisterDeviceArrivalCallback yDeviceUpdateCallback arrivalCallback procedure yRegisterDeviceArrivalCallback arrivalCallback yDeviceUpdateFunc procedure yRegisterDeviceArrivalCallback ByVal arrivalCallback As yDeviceUpdateFunc void RegisterDevi
111. es the button State A public void setStateA View view Do something in response to button click if relay null Ley 4 relay setState YRelay STATE A Hecatchy VAP REx cepETon se 4 e printStackTrace Called when the user touches the button State B public void setStateB View view Do something in response to button click if relay null Ley 4 relay setState YRelay STATE B lice toh VAP TE EIcep Elon aa e printStackTrace 17 6 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon package com yoctopuce doc_ examples import android app Activity import android os Bundle import android util Log import android view View import android widget AdapterView import android widget AdapterView OnItemSelectedListener import android widget ArrayAdapter import android widget Spinner import android widget Switch import android widget TextView import com yoctopuce YoctoAPI YAPI import com yoctopuce YoctoAPI YAPI Exception import com yoctopuce YoctoAPI YModule public class ModuleControl extends Activity implements OnItemSelectedListener private ArrayAdapter lt String gt aa private YModule module null Override public void onCreate Bundle savedInstanceState super onCreate savedinstan
112. escribe function describe function describe string describe NSString describe function describe string function describe As String string describe String describe def describe The text may include either the logical name or the serial number of the module YModule Returns a string that describes the module www yoctopuce com 139 19 High level API Reference module download Downloads the specified built in file and returns a binary buffer with its content function download pathname function download pathname function download pathname string download string pathname NSData download NSString pathname function download pathname string TByteArray function download As Byte def download pathname YModule target download pathname Parameters pathname name of the new file to load Returns a binary buffer with the file content On failure throws an exception or returns an empty content YModule 140 www yoctopuce com 19 High level API Reference module gt functionCount YModule Returns the number of functions beside the module interface available on the module function functionCount function functionCount function functionCount int functionCount int functionCount function functionCount integer function functionCount As Integer int functionCount def functionCount
113. et_productName string get_productName NSString productName function get_productName string function get_productName As String string get_productName String get_productName def get_productName YModule target get_productName Returns a string corresponding to the commercial name of the module as set by the factory On failure throws an exception or returns Y_PRODUCTNAME_INVALID YModule 156 www yoctopuce com 19 High level API Reference module get_productRelease module gt productRelease Returns the hardware release version of the module function get_productRelease function get_productRelease function get_productRelease int get_productRelease int productRelease function get_productRelease LongInt function get_productRelease As Integer int get_productRelease int get_productRelease def get_productRelease YModule target get_productRelease Returns an integer corresponding to the hardware release version of the module On failure throws an exception or returns Y_PRODUCTRELEASE_INVALID YModule www yoctopuce com 157 19 High level API Reference module gt get_rebootCountdown YModule module rebootCountdown Returns the remaining number of seconds before the module restarts or zero when no reboot has been scheduled function get_rebootCountdown function get_rebootCountdown function get_rebo
114. 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 Relay module with the RELAYLO1 123456 serial number which you have called MyModule and its relay1 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 YRelay RELAYLO1 123456 relayl describe YRelay RELAYLO1 123456 MyFunction describe YRelay MyModule relayl describe YRelay MyModule MyFunction describe YRelay MyFunction describe To work on all the Relay functions at the same time use the all target YRelay all describe For more details on the possibilities of the YRelay executable use YRelay help 7 4 Control of the module part Each module can be controlled in a similar way with the help of the YModule executable For example to obtain the list of all the connected modules use YModule inventory You can also use the following command to obtain an even more detailed list of the connected modules 28 www yoctopuce com 7 Using the Yocto Relay in command line YModule all describe Each xxx property of the module can be obtained thanks to a command of the get_xxxx type and the properties which are not read only can be modified with the set_xxx command For example YModule RELAYLO1 12346 set_logicalName MonPremierModule YModule
115. existed for some time Mini A connectors are not available anymore http www usb org developers Deprecation_Announcement_052507 pdf 2 www yoctopuce com 1 Introduction If you insert a USB hub between the computer and the Yocto Relay 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 1 2 Optional accessories The accessories below are not necessary to use the Yocto Relay module but might be useful depending on your project These are mostly common products that you can buy from your favourite hacking store To save you the tedious job of looking for them most of them are also available on the Yoctopuce shop Screws and spacers In order to mount the Yocto Relay 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
116. f lt input type radio name beacon value OFF checked gt OFF lt br gt printf upTime s sec lt br gt intVal S module gt get_upTime 1000 printf USB current smA lt br gt S module gt get_usbCurrent printf logs lt br gt lt pre gt s lt pre gt module gt get_lastLogs 2S lt input type submit value refresh gt lt FORM gt lt BODY gt lt HTML gt Each property xxx of the module can be read thanks to a method of type get _xxxx and properties which are not read only can be modified with the help of the set xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding set _xxx 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 lt HTML gt lt HEAD gt lt TITLE gt save settings lt TITLE gt lt BODY gt 42 www yoctopuce com 9 Using Yocto Relay with PHP lt FORM meth
117. f usage target string argv 1 state toupper argv 2 0 Setup the API to use local USB devices if yRegisterHub usb errmsg YAPT SUCCESS Geri lt lt Arecaceae eao W lt lt Giese lt lt Sila ewwa e etarget tany relay yFirstRelay if relay NULL cout lt lt No module connected check USB cable lt lt endl return 1 relsen relay yFindRelay target relayl if relay gt isOnline relay Soe SicenelS Sieencisy UA ee STATEA STATE else cout lt lt Module not connected check identification and USB cable lt lt endl return 0 10 2 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon include lt iostream gt include lt stdlib h gt include yocto_api h using namespace std static void usage const char exe cout lt lt usage lt lt exe lt lt lt serial or logical name gt ON OFF lt lt endl ezani int manm ane aroc const char eeano string errmsg Setup the API to use local USB devices www yoctopuce com 51 10 Using Yocto Relay with C Aig MAROC ALSteCuelshwloy MLSs Sime I swe SUCCESSE Ceri lt lt Wileenisicchelsible errora U lt lt erise lt lt iolellls ieisnewwliaigy ily el
118. f errmsg non active waiting time managing other callbacks VAP I Sileep S00 ae nerro y In a similar way it is possible to have a callback when a module is disconnected You can find a complete example implemented in your favorite programming language in the Examples Prog EventBased directory of the corresponding library Be aware that in most programming languages callbacks must be global procedures and not methods If you wish for the callback to call the method of an object define your callback as a global procedure which then calls your method 108 www yoctopuce com 19 High level API Reference This chapter summarizes the high level API functions to drive your Yocto Relay Syntax and exact type names may vary from one language to another but unless otherwise stated all the functions are available in every language For detailed information regarding the types of arguments and return values for a given language refer to the definition file for this language yocto_api as well as the other yocto_ files that define the function interfaces For languages which support exceptions all of these functions throw exceptions in case of error by default rather than returning the documented error value for each function This is by design to facilitate debugging It is however possible to disable the use of exceptions using the yDisableExceptions function in case you prefer to work with functions that return error values
119. failure throws an exception or returns Y_STATEATPOWERON_INVALID 202 www yoctopuce com 19 High level API Reference relay get_userData YRelay relay userData Returns the value of the userData attribute as previously stored using method set_userData function get_userData function get_userData function get_userData void get_userData void userData function get_userData Tobject function get_userData As Object object get_userData Object get_userData def get_userData This attribute is never touched directly by the API and is at disposal of the caller to store a context Returns the object stored previously by the caller www yoctopuce com 203 19 High level API Reference relay isOnline YRelay Checks if the relay is currently reachable without raising any error is function isOnline node js function isOnline php function isOnline cpp _ bool isOnline BOOL isOnline pas function isOnline boolean vb function isOnline As Boolean cs _ bool isOnline java boolean isOnline def isOnline If there is a cached value for the relay in cache that has not yet expired the device is considered reachable No exception is raised if there is an error while trying to contact the device hosting the relay Returns true if the relay can be reached and false otherwise 204 www yoctopuce co
120. ferent error code in case of failure When you work without exceptions you can obtain an error code and an error message explaining the source of the error You can request them from the object which returned the error calling the errType and errMessage methods Their returned values contain the same information as in the exceptions when they are active 10 4 Integration variants for the C Yoctopuce library Depending on your needs and on your preferences you can integrate the library into your projects in several distinct manners This section explains how to implement the different options Integration in source format Integrating all the sources of the library into your projects has several advantages e It guaranties the respect of the compilation conventions of your project 32 64 bits inclusion of debugging symbols unicode or ASCII characters etc It facilitates debugging if you are looking for the cause of a problem linked to the Yoctopuce library e It reduces the dependencies on third party components for example in the case where you would need to recompile this project for another architecture in many years e It does not require the installation of a dynamic library specific to Yoctopuce on the final system everything is in the executable To integrate the source code the easiest way is to simply include the Sources directory of your Yoctopuce library into your IncludePat
121. fies that you cannot a priori set up your own web server at home to control a home automation installation from the outside A solution to this problem advised by numerous home automation system dealers consists in providing outside visibility to your home automation server itself by adding a routing rule in the NAT configuration of the DSL router The issue of this solution is that it exposes the home automation server to external attacks The HTTP callback API solves this issue without having to modify the DSL router configuration The module control script is located on an external site and it is the VirtualHub which is in charge of calling it a regular intervals yoctocontrol php The HTTP callback API uses the VirtualHub which initiates the requests 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 Virtua Hub itself 4 Click on the edit button of the Outgoing callbacks section Serial Logical Name Description Action VIRTHUB0 7d1a86fb0 VirtualHub configure view log file RELAYHI 55 Yocto PowerRelay Configu
122. findViewById R id spinner1 my spin setOnItemSelectedListener this aa new ArrayAdapter lt String gt this android R layout simple spinner item aa setDropDownViewResource android R layout simple spinner dropdown_item my spin setAdapter aa Override protected void onStart super onstart cry 4 aa clear YAPI EnableUSBHost this VAPP RegusiterHulbl wasibu YModule r YModule FirstModule while r null String hwid r get_hardwareId aa add hwid 102 www yoctopuce com 17 Using the Yocto Relay with Android r r nextModule prcatch YAPTIR Cept ronie ii printStackTrace refresh Spinner with detected relay aa notifyDataSetChanged Override protected void onStop super onstop YAPI FreeAPI private void DisplayModuleInfo TextView field if module null TECUM waya 4 YAPI UpdateDeviceList fixme field TextView findViewById R id logicalnamefield field setText module getLogicalName Peate VAP TOE xcept sone e Prntstacklracel i Override public void onItemSelected AdapterView lt gt parent View view int pos long id String hwid parent getItemAtPosition pos toString module YModule FindModule hwid DisplayModuleInfo Override public void onNothingSelected AdapterView lt gt arg0 public void saveName View view if module null ime wu
123. ftware and you are ready to start your first tests You do not need to install any driver In order to keep them simple all the examples provided in this documentation are console applications Naturally the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface 16 2 Control of the Relay function A few lines of code are enough to use a Yocto Relay Here is the skeleton of a Java code snippet to use the Relay function ia ocd Get access to your device connected locally on USB for instance YAPI RegisterHub 127 0 0 1 relay YRelay FindRelay RELAYLO1 123456 relayl Hot plug is easy just check that the device is online if relay isOnline Use relay set state 1 www yoctopuce com EN libraries php 2 www yoctopuce com EN virtualhub php www yoctopuce com 89 16 Using the Yocto Relay with Java ferences Let us look at these lines in more details YAPI RegisterHub The yAPI RegisterHub function initializes the Yoctopuce API and indicates where the modules should be looked for The parameter is the address of the Virtual Hub able to see the devices If the initialization does not succeed an exception is thrown YRelay FindRelay The YRelay FindRelay function allows you to find a relay 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 i
124. gative error code YRelay newval either Y_STATE_A or Y_STATE_B according to the state of the relays A for the idle position www yoctopuce com 215 19 High level API Reference relay set_stateAtPowerOn YRelay relay setStateAtPowerOn Preset the state of the relays at device startup A for the idle position B for the active position UNCHANGED for no modification function set_stateAtPowerOn newval function set_stateAtPowerOn newval function set_stateAtPowerOn newval int set_stateAtPowerOn Y_STATEATPOWERON_enum newval int setStateAtPowerOn Y_STATEATPOWERON_ enum newval pas_ function set_stateAtPowerOn newval Integer integer v _ function set_stateAtPowerOn ByVal newval As Integer As Integer int set_stateAtPowerOn int newval int set_stateAtPowerOn int newval def set_stateAtPowerOn newval Y Relay target set_stateAtPowerOn newval Remember to call the matching module saveToFlash method otherwise this call will have no effect Parameters newval a value among Y_STATEATPOWERON_UNCHANGED Y_STATEATPOWERON_A and Y_STATEATPOWERON_B Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code 216 www yoctopuce com 19 High level API Reference relay set_userData YRelay relay setUserData Stores a user context provided as argument in the userData attribute of the function function
125. guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not NULL Below a short example listing the connected modules lt HTML gt lt HEAD gt lt TITLE gt inventory lt TITLE gt lt HEAD gt lt BODY gt lt Hl gt Device list lt H1 gt Se lt php include yocto_api php yRegisterHub http 127 0 0 1 4444 Smodule yFirstModule while is null Smodule print s s lt br gt module gt get_serialNumber www yoctopuce com 43 9 Using Yocto Relay with PHP Smodule gt get_ productName S module module gt nextModule Le lt lt ESS lt BODY gt lt HTML gt 9 4 HTTP callback API and NAT filters The PHP library is able to work in a specific mode called HTTP callback Yocto API With this mode you can control Yoctopuce devices installed behind a NAT filter such as a DSL router for example and this without needing to open a port The
126. h and to add all the files of this directory including the sub directory yapi to your project For your project to build correctly you need to link with your project the prerequisite system libraries that is e For Windows the libraries are added automatically 54 www yoctopuce com 10 Using Yocto Relay with C e For Mac OS X lOKit framework and CoreFoundation framework e For Linux libm libpthread libusb1 0 and libstdc Integration as a static library Integration of the Yoctopuce library as a static library is a simpler manner to build a small executable which uses Yoctopuce modules You can quickly compile the program with a single command You do not need to install a dynamic library specific to Yoctopuce everything is in the executable To integrate the static Yoctopuce library to your project you must include the Sources directory of the Yoctopuce library into your IncludePath and add the sub directory Binaries corresponding to your operating system into your libPath Then for you project to build correctly you need to link with your project the Yoctopuce library and the prerequisite system libraries For Windows yocto static lib e For Mac OS X libyocto static a IOKit framework and CoreFoundation framework For Linux libyocto static a libm libpthread libusb1 0 and libstdc Note under Linux if you wish to compile in command line with GCC it is generally advisable to link system li
127. he Yocto button of the module 4 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 Relay 1 www yoctopuce com EN virtualhub php 2 The interface was tested on FireFox 3 IE 6 Safari and Chrome It does not work with Opera www yoctopuce com 11 4 First steps RELAYLO1 000CC RELAYLO1 000CC is a 20x45mm board with two 220v 2Amp max 60W relay Kernel Serial RELAYLO1 000CC Product name Yocto Relay Logical name Product release 1 Firmware 3375 Consumption 26 mA Beacon Inactive tum on Luminosity 50 Actuators State of relay 1 A Switch to B State of relay 2 A Switch to B Misc Open API browser pop up Get user manual from yoctopuce com Close Properties of the Yocto Relay module This window allows you among other things to test the module relays with the switch to A switch to B buttons There is a characteristic clicking when the relays are working Moreover the leds indicating the active outputs light up Notice that the module consumption varies according to the activated outputs 4 3 Configuration When in the module list you click on the configure button corresponding to your module the configuration window is displayed RELAYLO1 000CC Edit parameters for device RELAYLO1 000CC and click on the Save button Serial
128. he 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 Modulel Sub usage Console WriteLine usage demo lt serial or logical name gt lt new logical name gt End End Sub Sub Main Dim argv As String System Environment GetCommandLineArgs Dim errmsg As String Dim newname As String Dim m As YModule If argv Length lt gt 3 Then usage 66 www yoctopuce com 12 Using Yocto Relay with Visual Basic NET REM Setup the APE to use Local USB devices If yRegisterHub usb errmsg lt gt YAPI SUCCESS Then Console WriteLine RegisterHub error errmsg End End If m yFindModule argv 1 REM use serial or logical name If m isOnline Then newname argv 2 If Not yCheckLogicalName newname Then Console WriteLine Invalid name newname End End If m set_logicalName newname m saveToFlash REM do
129. hen used as a simple switch single throw function get_output function get_output function get_output Y_OUTPUT_enum get_output Y_OUTPUT_enum output function get_output Integer function get_output As Integer int get_output int get_output def get_output YRelay target get_output Returns either Y_OUTPUT_OFF or Y_OUTPUT_ON according to the output state of the relays when used as a simple switch single throw On failure throws an exception or returns Y_OUTPUT_INVALID www yoctopuce com 199 19 High level API Reference relay get_pulseTimer YRelay relay pulseTimer Returns the number of milliseconds remaining before the relays is returned to idle position state A during a measured pulse generation function get_pulseTimer function get_pulseTimer function get_pulseTimer s64 get_pulseTimer s64 pulseTimer function get_pulseTimer int64 ve function get_pulseTimer As Long long get_pulseTimer long get_pulseTimer def get_pulseTimer YRelay target get_pulseTimer When there is no ongoing pulse returns zero Returns an integer corresponding to the number of milliseconds remaining before the relays is returned to idle position state A during a measured pulse generation On failure throws an exception or returns Y_PULSETIMER_INVALID 200 www yoctopuce com 19 High level API Reference relay get_state Y
130. hentication works as well Username yocto Password CON 4 Setup the desired frequency of notifications No less than 3 seconds between two notification But notify after 600 seconds in any case 5 Press on the Test button to check your parameters 6 When everything works press on the OK button Test fox Cancel And select Yocto API callback You then only need to define the URL of the PHP script and if need be the user name and password to access this URL Supported authentication methods are basic and digest The second method is safer than the first one because it does not allow transfer of the password on the network Usage From the programmer standpoint the only difference is at the level of the yRegisterHub function call Instead of using an IP address you must use the callback string or http callback which is equivalent inelude yoctonap phpm yRegisterHub callback The remainder of the code stays strictly identical On the Virtua Hub interface at the bottom of the configuration window for the HTTP callback API there is a button allowing you to test the call to the PHP script Be aware that the PHP script controlling the modules remotely through the HTTP callback API can be called only by the Virtua Hub Indeed it requires the information posted by the VirtualHub to function To code a web site which controls Yoctopuce modules interactively you must create a user interface which store
131. hrough a coil A very high voltage briefly appears at the ends of a coil when when one brutally cuts the current passing through it This high voltage can create an electric arc where the circuit was cut in our case inside the relay soldered on the module This electric arc can eat away the relay connections leading to premature aging Therefore we advise against controlling electric motors or transformers with an electro magnetic relay be it a Yocto Relay module or any other command system based on this technology It is possible to limit this phenomenon by inserting a TVS diode in parallel with the device containing the coil These diodes are blocking below a specified voltage and conductive beyond So if you clamp one of theses diode on your inductive load this will short cut voltage peaks You only have to choose a diode with the right clamping voltage for your application If you wish to know more Tyco published an application note about this 1 Controlling an electric motor with a relay using a protecting diode 5 4 USB power distribution Although USB means Universal Serial BUS USB devices are not physically organized as a flat bus but as a tree using point to point connections This has consequences on power distribution to make it simple every USB port must supply power to all devices directly or indirectly connected to it And USB puts some limits 1 Relay contact life Application note Tyco electronics http relays te com
132. hrows an exception or returns a negative error code www yoctopuce com 177 19 High level API Reference module wait_async YModule Waits for all pending asynchronous commands on the module to complete and invoke the user provided callback function function wait_async callback context function wait_async callback context The callback function can therefore freely issue synchronous or asynchronous commands without risking to block the Javascript VM Parameters callback callback function that is invoked when all pending commands on the module are completed The callback function receives two arguments the caller specific context object and the receiving function object context caller specific object that is passed as is to the callback function Returns nothing 178 www yoctopuce com 19 High level API Reference 19 3 Relay function interface The Yoctopuce application programming interface allows you to switch the relay state This change is not persistent the relay will automatically return to its idle position whenever power is lost or if the module is restarted The library can also generate automatically short pulses of determined duration On devices with two output for each relay double throw the two outputs are named A and B with output A corresponding to the idle position at power off and the output B corresponding to the active state If you prefer the alternate defaul
133. hub information sheet YoctoHub Ethernet and YoctoHub Wireless You can add network connectivity to your Yocto Relay thanks to the YoctoHub Ethernet and the YoctoHub Wireless The YoctoHub Ethernet provides Ethernet connectivity and the YoctoHub Wireless provides WiFi connectivity Both can drive up to three devices and behave exactly like a regular computer running a Virtua Hub Solid copper ribbon cable If you wish to solder the Yocto Relay module directly to a micro USB hub to save on the space used by USB cables consider using solid copper ribbon cable it is much easier to solder In any case you will need cable with 4 wires with 1 27mm pitch Enclosures Your Yocto Relay has been designed to be installed as is in your project Nevertheless Yoctopuce sells enclosures specifically designed for Yoctopuce devices These enclosures have removable mounting brackets and magnets allowing them to stick on ferromagnetic surfaces More details are available on the Yoctopuce web site The suggested enclosure model for your Yocto Relay is the YoctoBox Short Thick Black 4 http www yoctopuce com EN products category enclosures www yoctopuce com 3 1 Introduction You can install your Yocto Relay in an optional enclosure In some cases the magnets included in the enclosure base might interfere with the Yocto Relay working If that happens just remove the magnets from the base as described in the enclosure documentation
134. if m get_beacon YModule BEACON_ ON Console WriteLine ON else Console WriteLine OFF Console WriteLine upTime I ah aget domine 7 000 j oto Siereuiney ar 1 Sie p Console Wereeline MUSE current A m ger uUsbCurrent A ToString it A mAN Console WriteLine Logs r n m get_lastLogs else Console WriteLine args 0 not connected check identification and USB cable Each property xxx of the module can be read thanks to a method of type YModule get xxxx and properties which are not read only can be modified with the help of the YModule set xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding YModule set xxx function However this modification is performed only in the random access memory RAM of the module if the module is restarted the modifications are lost To memorize them persistently it is necessary to ask the module to save its current configuration in its permanent memory To do so use the YModule saveToFlash method Inversely it is possible to force the module to forget its current settings by using the YModule revertFromFlash method The short example below allows you to modify the logical name of a module 72 www yoctopuce com 13 Using Yocto Relay with C using System USING OVS temi eo Miec tions Gencisikey usi
135. ile ein eee ees tisha deve a AENEA 61 12 Using Yocto Relay with Visual Basic NET ow 63 127 AINStANAtON soos sec toate a heated dedi eae la A teh 63 12 2 Using the Yoctopuce API in a Visual Basic project oo eee eeeeeseeeeee enter eeneeeeeeneeeeeeneaeees 63 12 3 Control of the Relay function oo eee eee ee eeeeeeeenne eee eee nese teeeeeeteaeeeeeeaeeeeteaeeeeseeaeeseaaeeey 64 12 4 ControLof the module part sssrinin din vinnie einii ad denn ETLE eieaa 65 12 5 Error handling ac23 awn as henna Rare E TENA 67 13 Using Yocto Relay with CH oo cessessesseeseeseessesnseneeneesseseeseesneeseeneens 69 13 12 INStallation sri eit eek E ee ened ee ae ane a A ee TEE 69 13 2 Using the Yoctopuce API in a Visual C project 0 ee ceeeeeeeeeeeeeneeeeteneeeeeeneeeeeeneeeeeeas 69 13 3 Control orihe Relay tUnction nissa laine Seite deeb 70 13 4 Controlof the module part spirione beens tay eeeletele ear cieteeie neki eseeaiea en 71 TS25 SE ROCMAN GINO eane e net Sat teeecugscetecestthcde otha ae 74 14 Using Yocto Relay with Delphi oo ccc cece ee ceeeeeeeseeeeeeeesneenenes 77 141s Preparati scian alee eetnt la see ant tient ect decent aA eee 77 14 2 Control of the Relay function oo eee ee eeeeeeeeene crete nee eeeeeeeeseaeeeeseaeeeeeeaeeeeseaeaeeseaaeeey 77 14 3 Control of the module part sssrini eiiean e Haider delle 79 14 4 Error handlingiwa cia ane eee NRA ee AAE E ee a 81 15 Using the Yocto Relay with Python 20 0 0 cece cece ec eeseeseeseeee
136. inF EditText edit EditText findViewById R id newname String newname edit getText toString cry 4 if YAPI CheckLogicalName newname Toast makeText getApplicationContext Invalid name newname Toast LENGTH_ LONG show Be eUian module set_logicalName newname module saveToFlash do not forget this edit setText catch VAPT Exception ex ex printStackTrace DisplayModuleInfo Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to 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 www yoctopuce com 103 17 Using the Yocto Relay with Android Listing the modules Obtaining the list of the connected modules is performed with the YModule yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not null Below a short example listing the connected modules package com yoctopuce doc_ examples import android app Activity import android os Bundle import android view View imp
137. ing SelectArchitecture before any other call to the library Parameters arch A string containing the architecture to use Possibles value are armhf armel 1386 x86 64 32570 TO4DIET Returns nothing On failure throws an exception www yoctopuce com 127 19 High level API Reference YAPI SetDelegate YAPI ySetDelegate Objective C only Register an object that must follow the procol YDeviceHotPlug void ySetDelegate id object The methodes yDeviceArrival and yDeviceRemoval will be invoked while yUpdateDeviceList is running You will have to call this function on a regular basis Parameters object an object that must follow the procol YAP IDelegate or nil 128 www yoctopuce com 19 High level API Reference YAPI SetTimeout YAPI ySetTimeout Invoke the specified callback function after a given timeout function ySetTimeout callback ms_timeout arguments function SetTimeout callback ms_timeout arguments This function behaves more or less like Javascript set Timeout but during the waiting time it will call yHandleEvents and yUpdateDeviceList periodically in order to keep the API up to date with current devices Parameters callback the function to call after the timeout occurs On Microsoft Internet Explorer the callback must be provided as a string to be evaluated ms_timeout an integer corresponding to the dur
138. int InitAPI int mode def InitAPI mode errmsg None YAPI It is not strictly needed to call yInitAPI as the library is automatically initialized when calling yRegisterHub for the first time When Y_DETECT_NONE is used as detection mode you must explicitly use yRegisterHub to point the API to the VirtualHub on which your devices are connected before trying to access them Parameters mode an integer corresponding to the type of automatic device detection to use Possible values are Y_DETECT_NONE Y_DETECT_USB Y_DETECT_NET and Y_DET ECT ALL errmsg a string passed by reference to receive any error message Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code 120 www yoctopuce com 19 High level API Reference YAPI PreregisterHub YAPI yPreregisterHub Fault tolerant alternative to RegisterHub function yPreregisterHub url errmsg function PreregisterHub url errmsg function yPreregisterHub url amp errmsg YRETCODE yPreregisterHub const string amp url string amp errmsg YRETCODE yPreregisterHub NSString url NSError errmsg function yPreregisterHub url string var errmsg string integer function yPreregisterHub ByVal url As String ByRef errmsg As String As Integer int PreregisterHub string url ref string
139. io Express 2010 but the process is similar for other versions Start by creating your project Then on the So ution Explorer panel right click on your project and select Add and then Add an existing item A file selection window opens Select the yocto_api vb file and the files corresponding to the functions of the Yoctopuce modules that your project is going to manage If in doubt select all the files You then have the choice between simply adding these files to your project or to add them as links the Add button is in fact a scroll down menu In the first case Visual Studio copies the selected files into your project In the second case Visual Studio simply keeps a link on the original files We recommend you to use links which makes updates of the library much easier 1 http www microsoft com visualstudio en us products 2010 editions visual basic express www yoctopuce com EN libraries php 3 The sources of this DLL are available in the C API www yoctopuce com 63 12 Using Yocto Relay with Visual Basic NET Then add in the same manner the yapi d11 DLL located in the Sources d11 directory Then from the Solution Explorer window right click on the DLL select Properties and in the Properties panel set the Copy to output folder to always You are now ready to use your Yoctopuce modules from Visual Studio In order to keep them simple all the examples provided in this documentation are console applications Natur
140. itAPI YAPI 119 Installation 63 69 Installing 27 Integration 54 Interface 134 179 Introduction 1 isOnline YModule 163 isOnline YRelay 203 isOnline_async YModule 164 isOnline_async YRelay 204 J Java 89 Javascript 31 L Library 54 83 Limitations 29 Linux 219 load YModule 165 load YRelay 205 load_async YModule 166 load_async YRelay 206 Localization 11 Module 11 20 21 28 33 41 51 59 65 71 79 85 91 100 134 N Native 23 95 NET 63 nextModule YModule 167 nextRelay YRelay 207 O Objective C 57 Optional 3 P Paradigm 19 Platforms 220 Port 96 Power 16 Preparation 77 PreregisterHub YAPI 120 Prerequisites 1 Presentation 5 Programming 19 25 107 Project 63 69 pulse YRelay 208 Python 83 R reboot YModule 168 Reference 109 RegisterDeviceArrivalCallback YAPI 121 RegisterDeviceRemovalCallback YAPI 122 RegisterHub YAPI 123 RegisterHubDiscoveryCallback YAPI 124 RegisterLogFunction YAPI 125 registerValueCallback YRelay 209 Relay 22 28 31 39 49 57 64 70 77 83 89 98 179 Relays 16 revertFromFlash YModule 169 S saveToFlash YModule 170 SelectArchitecture YAPI 126 Service 23 set_beacon YModule 171 set_logicalName YModule 172 set_logicalName YRelay 210 set_luminosity YModule 173 set_maxTimeOnStateA YRelay 211 set_maxTimeOnStateB YRelay 212 set_output YRelay 213 set_state YRelay 214 set_stateAtPowerOn YRelay 215 set_us
141. ive www yoctopuce com 61 62 www yoctopuce com 12 Using Yocto Relay with Visual Basic NET VisualBasic has long been the most favored entrance path to the Microsoft world Therefore we had to provide our library for this language even if the new trend is shifting to C All the examples and the project models are tested with Microsoft VisualBasic 2010 Express freely available on the Microsoft web site 12 1 Installation Download the Visual Basic Yoctopuce library from the Yoctopuce web site There is no setup program simply copy the content of the zip file into the directory of your choice You mostly need the content of the Sources directory The other directories contain the documentation and a few sample programs All sample projects are Visual Basic 2010 projects if you are using a previous version you may have to recreate the projects structure from scratch 12 2 Using the Yoctopuce API in a Visual Basic project The Visual Basic NET Yoctopuce library is composed of a DLL and of source files in Visual Basic The DLL is not a NET DLL but a classic DLL written in C which manages the low level communications with the modules 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 Stud
142. k around this limitation by using a Virtual Hub run the VirtualHub on the concerned machine and use the executables of the command line API with the r option For example if you use YModule inventory you obtain a list of the modules connected by USB using a native access If another command which accesses the modules natively is already running this does not work But if you run a Virtual Hub and you give your command in the form YModule r 127 0 0 1 inventory it works because the command is not executed natively anymore but through the Virtual Hub Note that the Virtual Hub counts as a native application 3 http www yoctopuce com EN virtualhub php www yoctopuce com 29 30 www yoctopuce com 8 Using Yocto Relay with Javascript Javascript is probably not the first language that comes to mind to control hardware but its ease of use is a great advantage with Javascript you only need a text editor and a web browser to realize your first tests At the time of writing the Javascript library functions with any recent browser except Opera It is likely that Opera will end up working with the Yoctopuce library one of these days but it is not the case right now Javascript is one of those languages which do not allow you to directly access the hardware layers of your computer Therefore you need to run the Yoctopuce TCP IP to USB gateway named VirtualHub on the machine on which your modules are connected
143. l value serial module yFindModule serial if module isOnline document gethlementByld msgq value document getElementById curName value module get_logicalName else document getElementBylId msg value Module not connected setTimeout refresh 1000 function save var newname document getElementByld newName value if yCheckLogicalName newname alert invalid logical name CeT UTmy module set_logicalName newname module saveToFlash gt SOCR IPT lt HEAD gt lt BODY onload refresh gt Module to use lt input id serial gt lt input id msg style color red border none readonly gt lt br gt Current name lt input id curName readonly gt lt br gt New logical name lt input id newName gt lt a href javascript save gt Save lt a gt lt BODY gt lt HTML gt Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the yFirstModule function which retu
144. lay js is necessary to manage modules containing a relay such as Yocto Relay 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 yFindRelay The yFindRelay function allows you to find a relay 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 Relay module with serial number RELA YLO1 123456 which you have named MyModule and for which you have given the relay7 function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once Var relay Var relay var relay var relay var relay yFindRelay RELAYLO1 123456 relayl yFindRelay RELAYLO1 123456 MyFunction yFindRelay MyModule relayl yFindRelay MyModule MyFunction yFindRelay MyFunction yFindRe lay returns an object which you can then use at will to control the relay isOnline The isOnline method of the object returned by yFindRelay allows you to know if the corresponding module is present and in w
145. le connected check USB cable Giles Srelay2 relayl gt nextRelay serial relayl gt module gt get_serialnumber Print Module to use lt input name serial value Sserial gt lt br gt Drive the selected module ae SSeS ECEN sien yy a Sstabe S CEN staten if S state A Srellayl gt set_state Y_ STATE A if state B Srellayl gt set_state Y_ STATE B UERS EEA elaae Mistesres2 I Sstate PCEN S tatez if Sstate A Srellay2 gt set_state Y STATE A if Sstate B Srellay2 gt set_state Y STATE B gt Relay 1 lt input type radio name statel value A gt Output A lt input type radio name statel value B gt Output B lt br gt Relay 2 lt input type radio name state2 value A gt Output A lt input type radio name state2 value B gt Output B lt br gt lt input type submit gt lt FORM gt lt BODY gt lt HTML gt 9 3 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon lt HTML gt lt HEAD gt lt TITLE gt Module Control lt TITLE gt lt HEAD gt lt BODY gt lt FORM method get gt lt php include yocto_api php www yoctopuce com 41 9 Using Yocto Relay with PHP Use explicit error handling rather than exceptions
146. ll necessary functions to control the modules via this virtual hub The end users will have to start the virtual hub before running the project control software itself unless they decide to install the hub as a service deamon in which case the virtual hub starts automatically when the machine starts up The application connects itself to the virtual hub to gain access to the module The service control method 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 virtual hubs 1 www yoctopuce com EN virtualhub php 24 www yoctopuce com 6 Programming general concepts When a virtual hub is used the control application does not need to reside on the same machine as the module Whatever the selected programming language and the control paradigm used programming itself stays strictly identical From one language to another functions bear exactly the same name and have the same parameters The only differences are linked to the constraints of the languages themselves Language Native Native with DLL Virtual hub C Objective C Delphi Python VisualBasic Net C Net Javascript Node js
147. lowing you to manage Yoctopuce modules yocto api h must always be used yocto relay h is necessary to manage modules containing a relay such as Yocto Relay 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 yFindRelay The yFindRelay function allows you to find a relay 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 Relay module with serial number RELAYLO1 123456 which you have named MyModule and for which you have given the relay function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once YRelay relay YRelay relay YRelay relay YRelay relay YRelay relay yFindRelay RELAYLO1 123456 relayl yFindRelay RELAYLO1 123456 MyFunction yFindRelay MyModule relayl yFindRelay MyModule MyFunction yFindRelay MyFunction yFindRe lay returns an object which you can then use at will to control the relay isOnline The isOnline method of the object returned by yFindRelay allows y
148. lt endl module module gt nextModule return 0 10 3 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library www yoctopuce com 53 10 Using Yocto Relay with C The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to i1sOnline and which could crash the software The only way to prevent this is to implement one of the two error handling techniques described below The method recommended by most programming languages for unpredictable error handling is the use of exceptions By default it is the behavior of the Yoctopuce library If an error happens while you try to access a module the library throws an exce
149. m 19 High level API Reference relay isOnline_async YRelay Checks if the relay is currently reachable without raising any error asynchronous version function isOnline_async callback context function isOnline_async callback context If there is a cached value for the relay in cache that has not yet expired the device is considered reachable No exception is raised if there is an error while trying to contact the device hosting the requested function This asynchronous version exists only in Javascript It uses a callback instead of a return value in order to avoid blocking the Javascript virtual machine Parameters callback callback function that is invoked when the result is known The callback function receives three arguments the caller specific context object the receiving function object and the boolean result context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback www yoctopuce com 205 19 High level API Reference relay load YRelay Preloads the relay cache with a specified validity duration is__ function load msValidity nodes function load msValidity php function load msValidity YRETCODE load int msValidity YRETCODE load int msValidity function load msValidity integer YRETCODE function load ByVal msValidity As Integer As YRETCODE YRETCODE load int msValidity
150. m 21 Characteristics You can find below a summary of the main technical characteristics of your Yocto Relay module Width 20 mm Length 45 mm Weight 7g USB connector micro B Channels 2 Max switching power 60 W Max voltage 160 V Supported Operating Systems Windows Linux Intel ARM Mac OS X Android Drivers no driver needed API SDK Libraries USB TCP C Objective C C VB NET Delphi Python Java Android API SDK Libraries TCP only Javascript Node js PHP Java RoHS yes USB Vendor ID 0x24E0 USB Device ID 0x000C Suggested enclosure YoctoBox Short Thick Black www yoctopuce com 221 21 Characteristics 222 www yoctopuce com
151. mber 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 Screw terminal The two relays embedded in the Yocto Relay module are commutators which means that they can commute their input current onto one of two outputs This is why the terminal has six poles When the 1 short short short long long long short short short 2 support yoctopuce com 6 www yoctopuce com 2 Presentation module is powered off the outputs A are active Be aware the outputs A and B are wired in mirror for relay 1 and 2 ceo a a ADN EU p Sd a A A A Relay wiring inside the module Leds indicating the active outputs On the front of the terminal there are four green leds which indicate which module outputs are a
152. mber 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 Relay module with serial number RELAYLO1 123456 which you have named MyModule and for which you have given the relay7 function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once relay YRelay FindRelay RELAYLO1 123456 relayl relay YRelay FindRelay RELAYLO1 123456 MyFunction relay YRelay FindRelay MyModule relayl relay YRelay FindRelay MyModule MyFunction relay YRelay FindRelay MyFunction YRelay FindRelay returns an object which you can then use at will to control the relay isOnline The isOnline method of the object returned by YRelay FindRelay allows you to know if the corresponding module is present and in working order set_state The set _state method of the objet returned by YRelay FindRelay switches the relay position to one of its two outputs The two possible parameter values are YRelay STATE A for output A and YRelay STATE B for output B 4 Remember to change the filter of the selection window otherwise the DLL will not show 70 www yoctopuce com 13 Using Yocto Relay with C A real example Launch Microsoft Visual C and open the corresponding sample project provided in the directory Examples Doc GettingStarte
153. mecaemcllla else cout lt lt argv 1 lt lt not connected check identification and USB cable lt lt endl return 0 Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not NULL Below a short example listing the connected modules include lt iostream gt mone inde yfoyeicte eleit o hi Using Namespace std Int MaIn AAnt aroc Const char arav String errmsg Setup the API to use local USB devices if yRegisterHub usb errmsg YAPI SUCCESS cerris Reg SESCH porron lt lt Giciamsye lt lt eiololll 5 return 1 cout lt lt Device List lt lt endl YModule module yFirstModule while module NULL couci lt pmodule geiser ra NuMO ST lt lt a lE cout lt lt module gt get_productName lt
154. mp errmsg YRETCODE yHandleEvents NSError errmsg function yHandleEvents var errmsg string integer function yHandleEvents ByRef errmsg As String As YRETCODE YRETCODE HandleEvents ref string errmsg int HandleEvents def HandleEvents errmsg None If your program includes significant loops you may want to include a call to this function to make sure that the library takes care of the information pushed by the modules on the communication channels This is not strictly necessary but it may improve the reactivity of the library for the following commands This function may signal an error in case there is a communication problem while contacting a module Parameters errmsg a string passed by reference to receive any error message Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 119 19 High level API Reference YAPI InitAPI ylnitAPI Initializes the Yoctopuce programming library explicitly function yInitAPI mode errmsg node js function InitAPI mode errmsg function yInitAPI mode amp errmsg YRETCODE yInitAPI int mode string amp errmsg YRETCODE yInitAPI int mode NSError errmsg function yInitAPI mode integer var errmsg string integer _ v function ylnitAPI ByVal mode As Integer ByRef errmsg As String As Integer int InitAPI int mode ref string errmsg synchronized static
155. n 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 48 www yoctopuce com 10 Using Yocto Relay with C C is not the simplest language to master However if you take care to limit yourself to its essential functionalities this language can very well be used for short programs quickly coded and it has the advantage of being easily ported from one operating system to another Under Windows all the examples and the project models are tested with Microsoft Visual Studio 2010 Express freely available on the Microsoft web site Under Mac OS X all the examples and project models are tested with XCode 4 available on the App Store Moreover under Max OS X and under Linux you can compile the examples using a command line with GCC using the provided GNUmakefile In the same manner under Windows a Makefile allows you to compile examples using a command line fully knowing the compilation and linking arguments Yoctopuce C libraries are integrally provided as source files A section of the low level library is written in pure C but you should not need to interact directly with it everything was done to ensure the simplest possible interaction from C The library is naturally also available as binary files so
156. n of the pause in milliseconds errmsg a string passed by reference to receive any error message Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code 130 www yoctopuce com 19 High level API Reference YAPI UnregisterHub YAPI yUnregisterHub Setup the Yoctopuce library to no more use modules connected on a previously registered machine with RegisterHub function yUnregisterHub url function UnregisterHub url function yUnregisterHub url void yUnregisterHub const string amp url void yUnregisterHub NSString url procedure yUnregisterHub url string procedure yUnregisterHub ByVal url As String void UnregisterHub string url synchronized static void UnregisterHub String url def UnregisterHub url Parameters url a string containing either usb or the www yoctopuce com 131 19 High level API Reference YAPI UpdateDeviceList YAPI yUpdateDeviceList Triggers a re detection of connected Yoctopuce modules function yUpdateDeviceList errmsg node js function UpdateDeviceList errmsg function yUpdateDeviceList amp errmsg YRETCODE yUpdateDeviceList string amp errmsg YRETCODE yUpdateDeviceList NSError errmsg function yUpdateDeviceList var errmsg string integer function yUpdateDeviceList ByRef errmsg As String As YRETCODE YRETCODE UpdateDeviceList ref string errmsg int UpdateDe
157. nction that is invoked when the result is known The callback function receives three arguments the caller specific context object the result code YAP I_SUCCESS if the operation completes successfully and the error message context caller specific object that is passed as is to the callback function Returns nothing the result is provided to the callback www yoctopuce com 133 19 High level API Reference 19 2 Module control interface This interface is identical for all Yoctopuce USB modules It can be used to control the module global parameters and to enumerate the functions provided by each module In order to use the functions described here you should include lt script type text javascript src yocto_api js gt lt script gt var yoctolib require yoctolib var YAPI yoctolib YAPI var YModule yoctolib YModule require_once yocto_api php include yocto_api h import yocto_api h uses yocto_api yocto_api vb yocto_api cs import com yoctopuce YoctoAPI YModule from yocto_api import Global functions yFindModule func Allows you to find a module from its serial number or from its logical name yFirstModule Starts the enumeration of modules currently accessible YModule methods module gt describe Returns a descriptive text that identifies the module module download pathname Downloads the specified built in file and returns a binary buffer with
158. nd While End Sub End Module 12 5 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help www yoctopuce com 67 12 Using Yocto Relay with Visual Basic NET you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to i1sOnline and which could crash the software The only way to prevent this is to implement one of the two error handling techniques described below The method recommended by most programming languages for unpredictable error handling is the use of exceptions By default it is the behavior of the Yoctopuce library If an error happens while you try to access a module the library throws an exception In this
159. neeteetees 83 Wee SOULCOMICS oren nea a a a ea tenes a tetevectt aR 83 15 2 D namiC Dra y a r ea a aaea ae AAE aa E a hk etek 83 15 3 Controkot the Relay function siisi oee a a a aei 83 15 4 Gontrol of th module part Tarei eaa aeaa a aa Eaa akaa neii 85 52D EROPIMATI GINO NAAA E P A A O E E E O 87 16 Using the Yocto Relay with Java oon eceeeeeeeeeeeseeseeseetesteeteeeeenenee 89 16 12 Getting ready E E EAA EAA 89 16 2 Control of the Relay fUnCtion arrese aa iaraa eee ade a aaa 89 16 3 Control of the module Part eeeeceeeeseeceeeseeeeeeteeeeeeesaceceeaeaeseaaeesesaaaesesseneneeneneeeenanees 91 TOA EATE TELO TAS PEA E E E E E A E E AT 93 17 Using the Yocto Relay with Android ssnnsssssa111nson1rinsnrrisssnrnnsssnrrrnnenns 95 17 1 Native access and VirtualHub s sssesssssssssresrrnsssrrnsrrnrnsrrnsatrnnttrnnttnansennantnanannnanatennnetnannnenne 95 17 2 Getting TOADY a a r eE r a aaa aa r raa a ea aaa a ira ara a Aaaa Aaaa a aAa rr danian 95 17 3 Compatibilty saaier enie ateren Such a ed ai han adi hhh Haman 95 17 4 Activating the USB port under Android oo eececeeeeneeeeeeneeeeseeeeeeeaeeeeeeaeeeeseaeeeeseaeeeeneas 96 17 5 Control of the Relay function essssessssesssrsssrressrnrserrnnttrnsttrnnrintanttnnasenanatrannnennnncenanennnana 98 1 76 Control ofthe mModul part a wend inhi Ane 100 17 7 Error handling nana aaa e bale iiiveden iebetel e a 105 18 Advanced programming oa ec ree 107 18 1 Evye
160. ng System Ling using System Text namespace ConsoleApplicationl class Program static void usage string execname System AppDomain CurrentDomain FriendlyName Console WriteLine Usage Console WriteLine usage demo lt serial or logical name gt lt new logical name gt System Threading Thread Sleep 2500 Environment Exit 0 static void Main string args YModule m string errmsg string newname if args Length 2 usage if YAPI RegisterHub usb ref errmsg YAPI SUCCESS Console WriteLine RegisterHub error errmsg Environment Exit 0 m YModule FindModule args 0 use serial or logical name if m isOnline newname args 1 if YAPI CheckLogicalName newname Console WriteLine Invalid name newname Environment Exit 0 m set_logicalName newname m saveToFlash do not forget this Console Write Module serial m get_serialNumber Console WriteLine name m get_logicalName elise Console Write not connected check identification and USB cable 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 sav
161. nitialized them Let us imagine a Yocto Relay module with serial number RELAYLO1 123456 which you have named MyModule and for which you have given the relay7 function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once relay YRelay FindRelay RELAYLO1 123456 relayl relay YRelay FindRelay RELAYLO1 123456 MyFunction relay YRelay FindRelay MyModule relay1 relay YRelay FindRelay MyModule MyFunction relay YRelay FindRelay MyFunction YRelay FindRelay returns an object which you can then use at will to control the relay isOnline The isOnline method of the object returned by YRelay FindRelay allows you to know if the corresponding module is present and in working order set_state The set _state method of the objet returned by YRelay FindRelay switches the relay position to one of its two outputs The two possible parameter values are YRelay STATE A for output A and YRelay STATE B for output B A real example Launch you Java environment and open the corresponding sample project provided in the directory Examples Doc GettingStarted Yocto Relay of the Yoctopuce library In this example you will recognize the functions explained above but this time used with all the side materials needed to make it work nicely as a small demo impone COM VOCEODUCE VOCEOAP lat public class Demo public static void main
162. not forget this Console Write Modules serial em get serial Number Console Write name m get_logicalName Else Console Write not connected check identification and USB cable End If End Sub End Module Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not Nothing Belowa short example listing the connected modules Module Modulel Sub Main Dim M As ymodule Dim errmsg As String REM Setup the API to use local USB devices If yRegisterHub usb errmsg lt gt YAPI_ SUCCESS Then Console WriteLine RegisterHub error errmsg End End If Console WriteLine Device list M yFirstModule While M IsNot Nothing Cons olen Wraivetmaner Macey s crascalIN umber met anne eta ICy Clem ora cli e Namen e i M M nextModule E
163. not read only can be modified with the help of the set xxx method For more details regarding the used functions refer to the API chapters Changing the module settings When you want to modify the settings of a module you only need to call the corresponding set _xxx function However this modification is performed only in the random access memory RAM of the module if the module is restarted the modifications are lost To memorize them persistently it is necessary to ask the module to save its current configuration in its permanent memory To do so use the saveToFlash method Inversely it is possible to force the module to forget its current settings by using the revertFromFlash method The short example below allows you to modify the logical name of a module program savesettings SAPPTYPE CONSOLE uses Sysuti ls yocto_ api const serial RELAYLO1 123456 use serial number or logical name var module TYModule errmsg 8 Gieteharey newname string begin Setup the API to use local USB devices if yRegisterHub usb errmsg lt gt YAPI SUCCESS then begin Write RegisterHub error errmsg exit end module yFindModule serial if not module isOnline then begin writeln Module not connected check identification exit end and USB cable 80 www yoctopuce com 14 Using Yocto Relay with Delphi Writeln Current logical name module get_logicalName Wri
164. not require that the relay is online at the time it is invoked The returned object is nevertheless valid Use the method YRelay isOnline to test if the relay is indeed online at a given time In case of ambiguity when looking for a relay by logical name no error is notified the first instance found is returned The search is performed first by hardware name then by logical name Parameters func a string that uniquely characterizes the relay Returns a YRelay object allowing you to drive the relay 182 www yoctopuce com 19 High level API Reference YRelay FirstRelay yFirstRelay Starts the enumeration of relays currently accessible function yFirstRelay function FirstRelay function yFirstRelay YRelay yFirstRelay YRelay yFirstRelay function yFirstRelay function yFirstRelay YRelay FirstRelay YRelay FirstRelay def FirstRelay TYRelay As YRelay Use the method YRelay nextRelay to iterate on next relays YRelay Returns a pointer to a YRelay object corresponding to the first relay currently online or a nul 1 pointer if there are none www yoctopuce com 183 19 High level API Reference relay delayedPulse YRelay Schedules a pulse function delayedPulse ms_delay ms_duration function delayedPulse ms_delay ms_duration function delayedPulse ms_delay ms_duration int delayedPulse int ms_delay int ms_duration int delayedPulse
165. nt programming asistira a e a e e ea e 107 19 High level API Reference oo ce eee ceeeeeeeeseeneeteeeeeteeneeneaeeeee 109 1971 General 1UnctionS sna ies Rashard a eae Rave iie ds EE TETE EEEE 110 19 2 M du l control intertace verige ene stele cede AA aer raain ariff aiaa 134 19 3 Relay function interface ooo eee ceeesceeeeeseeeeeeceeeeneaneeecnaeeneeaneceeaneeesnaneeeensaeenenennenessaaes 179 20 Troubleshooting 242 5 ects ow Greed eee eens 219 20 1e ETNO E ae W OLST E E EEE EAE aad tt E alo ee ee eG AE 219 20 2 ARMPlatiorms HF and EL siiperi ie a E a A 220 21 Characteristics iol tt toa ea aed acer eM noel Nac tee oe Reet nedhas ota 221 Blueprint a a eee eee ddl iets aie eal eats 223 1 Introduction The Yocto Relay module is a small 45x20mm module which allows you to control small relays by USB These relays can commute up to 160V and 2A which allows you to pilot numerous equipments by acting directly on their power supply The module small dimensions enable it to be slipped almost anywhere including inside the piloted equipment The Yocto Relay module Yoctopuce thanks you for buying this Yocto Relay 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 Relay 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 sup
166. ntirely on your computer manufacturer attention to provide as much current as possible on the USB ports and to detect overloads before they lead to problems or to hardware damages When modules are not provided enough current they may work erratically and create unpredictable bugs If you want to prevent any risk do not cascade hubs without external power supply and do not connect peripherals requiring more than 100mA behind a bus powered hub In order to help controlling and planning overall power consumption for your project all Yoctopuce modules include a built in current sensor that tells with 5mA precision the consumption of the module on the USB bus www yoctopuce com 17 18 www yoctopuce com 6 Programming general concepts The Yoctopuce API was designed to be at the same time simple to use and sufficiently generic for the concepts used to be valid for all the modules in the Yoctopuce range and this in all the available programming languages Therefore when you have understood how to drive your Yocto Relay with your favorite programming language learning to use another module even with a different language will most likely take you only a minimum of time 6 1 Programming paradigm The Yoctopuce API is object oriented However for simplicity s sake only the basics of object programming were used Even if you are not familiar with object programming it is unlikely that this will be a hinderance for using Yoctopuce
167. 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 Relay module with serial number RELA YLO1 123456 which you have named MyModule and for which you have given the relay1 function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once relay yFindRelay RELAYLO1 123456 relayl relay yFindRelay RELAYLO1 123456 MyFunction relay yFindRelay MyModule relayl relay yFindRelay MyModule MyFunction relay yFindRelay MyFunction yFindRelay returns an object which you can then use at will to control the relay isOnline The isOnline method of the object returned by yFindRelay allows you to know if the corresponding module is present and in working order set_state The set _state method of the objet returned by yFindRelay switches the relay position to one of its two outputs The two possible parameter values are Y STATE A for output A and Y STATE _B for output B 14 3 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon program modulecontrol SAPPTYPE CONSOLE uses Syste t Ley yocto api const serial RELAYLO1 123456 use serial number
168. o Relay module www yoctopuce com 10 www yoctopuce com 4 First steps When reading this chapter your Yocto Relay should be connected to your computer which should have recognized it It is time to make it work Go to the Yoctopuce web site and download the Virtual Hub software It is available for Windows Linux and Mac OS X Normally the Virtual Hub software serves as an abstraction layer for languages which cannot access the hardware layers of your computer However it also offers a succinct interface to configure your modules and to test their basic functions You access this interface with a simple web browser Start the Virtual Hub software in a command line open your preferred web browser and enter the URL http 127 0 0 1 4444 The list of the Yoctopuce modules connected to your computer is displayed Serial Logical Name Description Action VIRTHUB0 7d1a fb VirtualHub beacon configure view log file RELAYLO1 000CC Yocto Relay beacon configure view log file P Show device functions Module list as displayed in your web bowser 4 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 t
169. octo Relay with Visual Basic NET Sub Main Dim argv As String System Environment GetCommandLineArgs Dim errmsg As String Dim m As ymodule TE VRegucterHulo usbLy errs ma lt VAP IO SUCEH SS sien Console WriteLine RegisterHub error errmsg End Ene at If argv Length lt 2 Then usage m yFindModule argv 1 REM use serial or logical name If m isOnline Then Le argv length gt 2 Then Tt argv 2 ON Then m set_beacon Y_ BEACON ON If argv 2 OFF Then m set_ beacon Y_ BEACON OFF End If Console WriteLine serial mee eservalliNumb er Console WriteLine logical name m get_logicalName Console WriteLine luminosity Ve Str mige t hiuminosa ty ON Console Write beacon AG rE miget beacon Y BEACON LON Then Console WriteLine ON Else Console WriteLine OFF Jajavel Ese Console WriteLine upTime War Scie Mle cet Wee 1000 ae T exe Console WriteLine USB current Hoar Shee m Cie Wis buereSialie ar wiv Console WriteLine Logs Console WriteLine m get lastLogs Else x Console WriteLine argv 1 not connected check identification and USB cable End If End Sub End Module Each property xxx of the module can be read thanks to a method of type get _xxxx and properties which are not read only can be modified with the help of the set xxx method For more details regarding the used functions refer to the API chapters Changing t
170. octopuce com 55 56 www yoctopuce com 11 Using Yocto Relay with Objective C Objective C is language of choice for programming on Mac OS X due to its integration with the Cocoa framework In order to use the Objective C library you need XCode version 4 2 earlier versions will not work available freely when you run Lion If you are still under Snow Leopard you need to be registered as Apple developer to be able to download XCode 4 2 The Yoctopuce library is ARC compatible You can therefore implement your projects either using the traditional retain release method or using the Automatic Reference Counting Yoctopuce Objective C libraries are integrally provided as source files A section of the low level library is written in pure C but you should not need to interact directly with it everything was done to ensure the simplest possible interaction from Objective C You will soon notice that the Objective C API defines many functions which return objects You do not need to deallocate these objects yourself the API does it automatically at the end of the application In order to keep them simple all the examples provided in this documentation are console applications Naturally the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface You can find on Yoctopuce blog a detailed example with video shots showing how to integrate the library into your projects 11 1
171. ocument getHlementById msg value var bemi servalls ermocdulic igetese mac lNumioers O lt pri html logical name module get logicalName lt br gt html luminosity module get_luminosity lt br gt html beacon if module get_beacon Y_BEACON_ ON html 0N lt a href javascript beacon Y BEACON OFF gt switch off lt a gt lt br gt else html OFF lt a href javascript beacon Y BEACON ON gt switch on lt a gt lt br gt html upTime parseInt module get _upTime 1000 sec lt br gt html USB current module get_usbCurrent mA lt br gt html logs lt br gt lt pre gt tmodule get_lastlogs lt pre gt lt br gt document getElementById data innerHTML html else document getHElementById msg value Module not connected setTimeout refresh 1000 function beacon state module set_beacon state refresh gt lt SCRE lt HEAD gt lt BODY onload refresh gt Module to use lt input id serial gt lt input id msg style color red border none readonly gt lt br gt lt span id data gt lt span gt lt BODY gt lt HTML gt Each property xxx of the module can be read thanks to a method of type get _xxxx and properties which are not read only can be modified with the help of the set _xxx method For more details regarding the used functions refer to the API chapters Changing th
172. od get gt lt php include T yocto api jphpi i Use explicit error handling rather than exceptions yDisableExceptions Setup the API to use the VirtualHub on local machine if yRegisterHub http 127 0 0 1 4444 Serrmsg YAPI_ SUCCESS die NCannor contact Vartvallhub en 227 10 Om Sserial CEN ser ranki ine Seika tS VN ft Check if a specified module is available online Smodule yFindModule Sserial if Smodule gt isOnline die Module not connected check serial and USB cable else or use any connected module suitable for the demo Smodule yFirstModule if module skip VirtualHub Smodule Smodule gt nextModule if is_null Smodule die No module connected check USB cable else serial module gt get_serialnumber Print Module to use lt input name serial value Sserial gt lt br gt if isset GET newname newname GET newname if yCheckLogicalName newname die Invalid name module gt set_logicalName newname Smodule gt saveToFlash prine Curmente namek ss lt bpr u smodule get logiecalName ii print New name lt input name newname value maxlength 19 gt lt br gt BS lt input type submit gt lt FORM gt lt BODY gt lt HTML gt Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing
173. odule is working smoothly The Yocto led then emits a low blue light which varies slowly mimicking breathing The Yocto led stops breathing when the module is not communicating any more as for instance when powered by a USB hub which is disconnected from any active computer When you press the Yocto button the Yocto led switches to Yocto beacon mode It starts flashing faster with a stronger light in order to facilitate the localization of a module when you have several identical ones It is indeed possible to trigger off the Yocto beacon by software as it is possible to detect by software that a Yocto beacon is on The Yocto led has a third functionality which is less pleasant when the internal software which controls the module encounters a fatal error the Yocto led starts emitting an SOS in morse 1 If this happens unplug and re plug the module If it happens again check that the module contains the latest version of the firmware and if it is the case contact Yoctopuce support 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 Relay modules this number starts with RELAYLO1 The module can be software driven using this serial nu
174. of the objet returned by YRelay FindRelay switches the relay position to one of its two outputs The two possible parameter values are YRelay STATE A for output A and YRelay STATE B for output B A real example Launch Python and open the corresponding sample script provided in the directory Examples Doc GettingStarted Yocto Relay 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 ie e EE NE ies Gl Se import os sys from yocto api import Brom ny OC eOmEe Naya mport am def usage scriptname os path basename sys argv 0 PEane Usage 84 www yoctopuce com 15 Using the Yocto Relay with Python print scriptname lt serial number gt lt channel gt A B print scriptname lt logical_name gt lt channel gt A BTI print scriptname any lt channel gt A B print Example print scriptname any 2 BY sys exit def die msg SVs che msg wm ehoc kU SBmcaliic a if len sys argv lt 3 usage target sys argv 1 upper channel sys argv 2 state sys argv 3 upper Setup the API to use local USB devices errmsg YRef Param if YAPI RegisterHub usb errmsg YAPI SUCCESS sys exit init error errmsg value if target ANY retreive any Relay then find its serial relay YRelay Fir
175. oid name android intent action MAIN gt lt action android name android hardware usb action USB DEVICE ATTACHED gt lt category android name android intent category LAUNCHER gt lt intent filter gt lt meta data android name android hardware usb action USB DEVICE ATTACHED android resource xml device filter gt 7 E lt activity gt lt application gt lt manifest gt The XML file containing the list of modules allowed to run the application must be saved in the res xml directory This file contains a list of USB vendorld and devicelD in decimal The following example runs the application as soon as a Yocto Relay or a YoctoPowerRelay is connected You can find the vendorlID and the devicelD of Yoctopuce modules in the characteristics section of the documentation lt xml version 1 0 encoding utf 8 gt lt resources gt lt usb device vendor id 9440 product id 12 gt lt usb device vendor id 9440 product id 13 gt lt resources gt www yoctopuce com 97 17 Using the Yocto Relay with Android 17 5 Control of the Relay function A few lines of code are enough to use a Yocto Relay Here is the skeleton of a Java code snippet to use the Relay function eae Retrieving the object representing the module connected here locally by USB YAPI EnableUSBHost this YAPI RegisterHub usb relay YRelay FindRelay RELAYLO1 123456 relayl Hot plug is easy just check th
176. ol modules driven by a VirtualHub on another OS or a YoctoHub 17 4 Activating the USB port under Android By default Android does not allow an application to access the devices connected to the USB port To enable your application to interact with a Yoctopuce module directly connected on your tablet on a USB port a few additional steps are required If you intend to interact only with modules connected on another machine through the network you can ignore this section In your AndroidManifest xml you must declare using the USB Host functionality by adding the lt uses feature android name android hardware usb host gt tag in the manifest section lt manifest gt lt uses feature android name android hardware usb host gt lt manifest gt When first accessing a Yoctopuce module Android opens a window to inform the user that the application is going to access the connected module The user can deny or authorize access to the device If the user authorizes the access the application can access the connected device as long as 2 Yoctohubs are a plug and play way to add network connectivity to your Yoctopuce devices more info on hittp www yoctopuce com EN products category extensions and networking 96 www yoctopuce com 17 Using the Yocto Relay with Android it stays connected To enable the Yoctopuce library to correctly manage these authorizations your must provide a pointer on the applicati
177. om lex ia System out print lim Meannoz contact Vaneualhubmont 27 Or Oe s ll ar ex getLocalizedMessage System out println Ensure that the VirtualHub application is running System exit 1 System out println usage demo serial or logical name ON OFF YModule module if args length 0 module YModule FirstModule if module null System our permet Nowmodule iconnecued check USB cable 77 System exit 1 else module YModule FindModule args 0 use serial or logical name ry 4 we args lence if args 1 equalsIgnoreCase ON module setBeacon YModule BERACON ON else module setBeacon YModule BEACON_ OFF System out printin serial module get_serialNumber System out println logical name module get_logicalName System out println luminosity module get_luminosity plete module get_beacon YModule BEACON ON System out printlin beacon ON 5 else System out printlin beacon OETAN System out printin upTime Uc mocwle Gat tomine O00 m W pechi System Out printim MUSBcurrent a i mod le igen usbeunnent METANI www yoctopuce com 91 16 Using the Yocto Relay with Java System out printin logs n module get_lastLogs Pacaech MAP TERxcepeion ex System out printlin args 1 not connected check identification and USB cable YAPI FreeAPI Each property xxx of the module can b
178. on context by calling the EnableUSBHost method of the YAPI class before the first USB access This function takes as arguments an object of the android content Context class or of a subclass As the Activity class is a subclass of Context it is simpler to call YAPI EnableUSBHost this inthe method onCreate of your application If the object passed as parameter is not of the correct type a YAPI Exception exception is generated Override public void onCreate Bundle savedInstanceState super onCreate savedinstanceState tey Pass the application Context to the Yoctopuce Library YAPI EnableUSBHost this Pacatch YAP TER xceptaon 1e i Log e Yocto e getLocalizedMessage Autorun It is possible to register your application as a default application for a USB module In this case as soon as a module is connected to the system the application is automatically launched You must add lt action android name android hardware usb action USB_DEVICE_ATTACHED gt in the section lt intent filter gt of the main activity The section lt activity gt must have a pointer to an XML file containing the list of USB modules which can run the application lt manifest xmlns android http schemas android com apk res android lt uses feature android name android hardware usb host gt lt application lt activity android name MainActivity gt lt intent filter gt lt action andr
179. onvolatile memory as when the module is powered on module gt saveToFlash Saves current settings in the nonvolatile memory of the module module set_beacon newval Turns on or off the module localization beacon www yoctopuce com 135 19 High level API Reference module set_logicalName newval Changes the logical name of the module module set_luminosity newval Changes the luminosity of the module informative leds module set_usbBandwidth newval Changes the number of USB interfaces used by the module module gt set_userData data Stores a user context provided as argument in the userData attribute of the function module triggerFirmwareUpdate secBeforeReboot Schedules a module reboot into special firmware update mode module wait_async callback context Waits for all pending asynchronous commands on the module to complete and invoke the user provided callback function 136 www yoctopuce com 19 High level API Reference YModule FindModule YModule yFindModule Allows you to find a module from its serial number or from its logical name function yFindModule func function FindModule func function yFindModule func YModule yFindModule string func YModule yFindModule NSString func function yFindModule func string TYModule function yFindModule ByVal func As String As YModule YModule FindModule string func YModule FindModule String func def FindModule
180. ore going too far into your project if you want to avoid pitfalls 5 1 Fixing While developing your project you can simply let the module hang at the end of its cable Check only that it does not come in contact with any conducting material such as your tools When your project is almost at an end you need to find a way for your modules to stop moving around Examples of assembly on supports The Yocto Relay 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 www yoctopuce com 15 5 Assembly and connections 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 5 2 Assembly examples If you obtained this Yocto Relay module it is probably because you know exactly what you intend to do with it You can nevertheless find below a few wiring examples among the simplest Pilot two light bulbs in alternation with your Yocto Relay module 5 3 Electro magnetic relays and coils Some devices that you may wish to control with your Yocto Relay module contain large coils It is in particular the case for electric motors and transformers This may cause trouble because of the auto induction generated when current goes t
181. orking order set_state The set _state method of the objet returned by yFindRelay switches the relay position to one of its two outputs The two possible parameter values are Y STATE A for output A and Y_ STATE _B for output B A real example Open your preferred text editor copy the code sample below save it in the same directory as the Yoctopuce library files and then use your preferred web browser to access this page The code is also provided in the directory Examples Doc GettingStarted Yocto Relay of the Yoctopuce library In this example you will recognize the functions explained above but this time used with all side materials needed to make it work nicely as a small demo The example is coded to be used either from a web server or directly by opening the file on the local machine Note that this latest solution does not work with some versions of Internet Explorer in particular IE 9 on Windows 7 which is not able to open network connections when working on a local file In order to use Internet Explorer you should load the example from a web server No such problem exists with Chrome Firefox or Safari 4 if you do not have a text editor use Notepad rather than Microsoft Word 32 www yoctopuce com 8 Using Yocto Relay with Javascript If your Yocto Relay 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 Rela
182. ort android widget LinearLayout import android widget TextView import com yoctopuce YoctoAPI YAPI import com yoctopuce YoctoAPI YAPI Exception import com yoctopuce YoctoAPI YModule public class Inventory extends Activity Override public void onCreate Bundle savedInstanceState super onCreate savedinstanceState setContentView R layout inventory public void refreshInventory View view LinearLayout layout LinearLayout findViewById R id inventoryList layout removeAllViews cry 4 YAPI UpdateDevicelist YModule module YModule FirstModule while module null String line module get_serialNumber module get_productName TextView tx new TextView this tx setText line layout addView tx module module nextModule earen MONIT InSeGyoieabeua Gy 5 EPpPrimestackiracel Override protected void onStart SUPE Onsicaac iy Cey YAPI EnableUSBHost this YAPE RegisterHubi usb PCaleeha VAP TH lt Cepir ton se a EPPrime stackitwacerG r refreshInventory null Override protected void onStop super onStop YAPI FreeAPI 104 www yoctopuce com 17 Using the Yocto Relay with Android 17 7 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugg
183. otCountdown int get_rebootCountdown int rebootCountdown function get_rebootCountdown Longint function get_rebootCountdown As Integer int get_rebootCountdown int get_rebootCountdown def get_rebootCountdown YModule target get_rebootCountdown Returns an integer corresponding to the remaining number of seconds before the module restarts or zero when no reboot has been scheduled On failure throws an exception or returns Y_REBOOTCOUNTDOWN_INVALID 158 www yoctopuce com 19 High level API Reference module get_serialNumber module serialNumber Returns the serial number of the module as set by the factory function get_serialNumber function get_serialNumber function get_serialNumber string get_serialNumber NSString serialNumber function get_serialNumber string function get_serialNumber As String string get_serialNumber String get_serialNumber def get_serialNumber YModule target get_serialNumber Returns a string corresponding to the serial number of the module as set by the factory On failure throws an exception or returns Y_SERTALNUMBER_INVALID YModule www yoctopuce com 159 19 High level API Reference module get_upTime YModule module upTime Returns the number of milliseconds spent since the module was powered on is _ function get_upTime node js function get_upTime php_ function ge
184. ou to know if the corresponding module is present and in working order set_state The set _state method of the objet returned by yFindRelay switches the relay position to one of its two outputs The two possible parameter values are Y STATE A for output A and Y STATE _B for output B A real example Launch your C environment and open the corresponding sample project provided in the directory Examples Doc GettingStarted Yocto Relay 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 Tinclude yocto api hi include yocto_ relay h include lt iostream gt include lt ctype h gt include lt stdlib h gt using namespace std 50 www yoctopuce com 10 Using Yocto Relay with C static void usage void cout lt lt usage demo lt serial number gt By lt lt sendy cout lt lt demo lt logical_name gt aA Bl lt endl Come lt lt demo any A B use any discovered device lt lt endl u64 now yGetTickCount dirty active wait loop while yGetTickCount now lt 3000 exit Ly A l int penbe arge Const ehar enson String es EMsG String EGEE YRelay relay char state nse leuas lt lt S i
185. port 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 Relay 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 1 support yoctopuce com www yoctopuce com 1 Introduction Yoctopuce provides software libraries to drive its modules for the following operating systems Windows Mac OS X Linux and Android Yoctopuce modules do not require installing any specific system driver as they leverage the standard HID driver provided with every operating system Windows versions currently supported are Windows XP Windows 2003 Windows Vista and Windows 7 Both 32 bit and 64 bit versions are supported Yoctopuce is frequently testing its modules on Windows XP and Windows 7 Mac OS X versions currently supported are 10 6 Snow Leopard Mac OS X 10 7 Lion and 10 8 Mountain Lion Yoctopuce is frequently testing its modules on Mac OS X 10 6 and 10 7 Linux kernels currently supported are the 2 6 branch and the 3 0 bran
186. products Note that you will never need to allocate or deallocate an object linked to the Yoctopuce API it is automatically managed There is one class per Yoctopuce function type The name of these classes always starts with a Y followed by the name of the function for example YTemperature YRelay YPressure etc There is also a YModule class dedicated to managing the modules themselves and finally there is the static YAPI class that supervises the global workings of the API and manages low level communications Low level handling Module handling Feature handling YAPI YModule YTemperature YPressure YRelay Y XXX Structure of the Yoctopuce API In the Yoctopuce API priority was put on the ease of access to the module functions by offering the possibility to make abstractions of the modules implementing them Therefore it is quite possible to work with a set of functions without ever knowing exactly which module are hosting them at the hardware level This tremendously simplifies programming projects with a large number of modules www yoctopuce com 19 6 Programming general concepts From the programming stand point your Yocto Relay 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
187. ption In this case there are three possibilities e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relatively easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the most desirable the Yoctopuce library offers another possibility for error handling allowing you to create a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get _state method returns a Y STATE INVALID value a get _currentValue method returns a Y CURRENTVALUE INVALID value and so on In any case the returned value is of the expected type and is not a null pointer which would risk crashing your program At worst if you display the value without testing it it will be outside the expected bounds for the 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 dif
188. r the idle position B for the active position UNCHANGED for no change relay get_userData Returns the value of the userData attribute as previously stored using method set_userData relay isOnline Checks if the relay is currently reachable without raising any error relay isOnline_async callback context Checks if the relay is currently reachable without raising any error asynchronous version relay load msValidity Preloads the relay cache with a specified validity duration relay load_async msValidity callback context Preloads the relay cache with a specified validity duration asynchronous version relay nextRelay Continues the enumeration of relays started using yFirstRelay relay pulse ms_duration Sets the relay to output B active for a specified duration then brings it automatically back to output A idle state relay registerValueCallback callback Registers the callback function that is invoked on every change of advertised value relay set_logicalName newval Changes the logical name of the relay relay set_maxTimeOnStateA newval Sets the maximum time ms allowed for THEFUNCTIONSS to stay in state A before automatically switching back in to B state relay set_maxTimeOnStateB newval 180 www yoctopuce com 19 High level API Reference Sets the maximum time ms allowed for THEFUNCTIONSS to stay in state B before automatically switching back in to A state
189. re view log fie beacon TMPSENS1 0S5E7F Yocto Temperature configure view log file beacon l Show device functions Click on the configure button on the first line www yoctopuce com 45 9 Using Yocto Relay with PHP VIRTHUBO 7d1a86fb09 Edit parameters for VIRTHUBO 7d1a86f009 and click on the Save button Serial VIRTHUB0 7d1a86fb09 Product name VirtualHub Software version 10789 Logical name Incoming connections Authentication to read information from the devices NO edit Authentication to make changes to the devices NO gait Outgoing callbacks Callback URL octoHub Gi Delay between callbacks min 3 s max 600 s This VirtualHub can post the advertised values of all devices on a specific URL on a regular basis If you wish to use this feature choose the callback type follow the steps below carefully 1 Specify the Type of callback you want to use Yocto API callback z Yoctopuce devices can be controled through remote PHP scripts That Yocto AFP caliback protocol is designed so it can pass trough NAT filters without opening ports See your device user manual PHP programming section for more details 2 Specify the URL to use for reporting values HTTPS protocol is not yet supported Callback URL http iwww mysite com yoctotest yoctocontrol php 3 If your callback requires authentication enter credentials here Digest authentication is recommended but Basic aut
190. relay set_output newval Changes the output state of the relays when used as a simple switch single throw relay set_state newval Changes the state of the relays A for the idle position B for the active position relay set_stateAtPowerOn newval Preset the state of the relays at device startup A for the idle position B for the active position UNCHANGED for no modification relay set_userData data Stores a user context provided as argument in the userData attribute of the function relay wait_async callback context Waits for all pending asynchronous commands on the module to complete and invoke the user provided callback function www yoctopuce com 181 19 High level API Reference YRelay FindRelay YRelay yFindRelay Retrieves a relay for a given identifier function yFindRelay func node js function FindRelay func function yFindRelay func YRelay yFindRelay const string amp func m _ YRelay yFindRelay NSString func function yFindRelay func string TYRelay function yFindRelay ByVal func As String As YRelay cs _ YRelay FindRelay string func java YRelay FindRelay String func def FindRelay func The identifier can be specified using several formats e FunctionLogicalName ModuleSerialNumber Functionldentifier e ModuleSerialNumber FunctionLogicalName e ModuleLogicalName Functionldentifier e ModuleLogicalName FunctionLogicalName This function does
191. rivileges of the non root users are limited to read access To avoid having to run the VirtualHub as root you need to create a new udev rule to authorize one or several users to have write access to the Yoctopuce peripherals To add a new udev rule to your installation you must add a file with a name following the arbitraryName rules format in the etc udev rules d directory When the system is starting udev reads all the files with a rules extension in this directory respecting the alphabetical order for example the 51 custom rules file is interpreted AFTER the 50 udev default rules file The 50 udev default file contains the system default udev rules To modify the default behavior you therefore need to create a file with a name that starts with a number larger than 50 that will override the system default rules Note that to add a rule you need a root access on the system In the udev_ conf directory of the Virtua Hub for Linux archive there are two rule examples which you can use as a basis Example 1 51 yoctopuce rules This rule provides all the users with read and write access to the Yoctopuce USB peripherals Access rights for all other peripherals are not modified If this scenario suits you you only need to copy the 51 yoctopuce all rules file into the etc udev rules d directory and to restart your system udev rules to allow write access to all users for Yoctopuce USB devices SUB
192. rns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not NULL Below a short example listing the connected modules lt HTML gt lt HEAD gt lt TITLE gt Modules inventory lt TITLE gt lt SCRIPT type text javascript srce yocto_api js gt lt SCRIPI gt www yoctopuce com 35 8 Using Yocto Relay with Javascript lt SCRIPT language javascriptl 5 type text JavaScript gt lt Use explicit error handling rather than exceptions yDisableExceptions Setup the API to use the VirtualHub on local machine if yRegisterHub http 127 0 0 1 4444 YAPI SUCCESS aller tMe cannot Contact Nir tela limon om Tnm Oc Orn function refresh yUpdateDeviceList var htmlcode var module yFirstModule while module htmlcode module get_serialNumber module get_productName lt br gt module module nextModule document getElementById list innerHTML htmlcode setTimeout refresh 500 gt lt SCRIPT gt lt HEAD gt lt BODY onload refresh gt lt H1 gt Device list lt H1 gt lt tt gt lt span id list gt lt span gt lt tt gt lt BODY gt lt HTML gt 8 4 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will
193. ronment copy the yapi dll DLL in a directory create a new console application in the same directory and copy paste the piece of code below program helloworld SAPPTYPE CONSOLE uses Seuss yocto api yocto_ relay 1 Actually Borland provided free versions for personal use of Delphi 2006 and 2007 Look for them on the Internet you may still be able to download them 2 Delphi libraries are regularly tested with Delphi 5 and Delphi XE2 www yoctopuce com EN libraries php 4 Use the Tools Environment options menu www yoctopuce com 77 14 Using Yocto Relay with Delphi procedure usage var execname string begin execname ExtractFileName paramstr 0 WriteLn Usage WriteLn execname lt serial number lt channel gt WriteLn execname lt logical_name gt lt channel gt Ln Ln Wanye lt chamne l TEANNEN MATRE FANTE Writel execname Writel Example WriteLn execname slicepi 2 500 halt end ae ebony 2 BUNT var errmsg target state channel string relay TYRelay m TYModule began if paramcount lt 3 then usage parse command line target lt UpperCase paramstr 1 7 channel paramstr 2 state UpperCase paramstr 3 Setup the API to use local USB devices if YRegisterHub usb errmsg lt gt YAPI SUCCESS then begin writeln RegisterHub error errmsg halt end if target ANY then begin try to find the first
194. rrorType As YRETCODE YRETCODE get_errorType int get_errorType def get_errorType This method is mostly useful when using the Yoctopuce library with exceptions disabled Returns a number corresponding to the code of the latest error that occured while using this module object www yoctopuce com 147 19 High level API Reference module gt get_firmwareRelease module gt firmwareRelease Returns the version of the firmware embedded in the module function get_firmwareRelease function get_firmwareRelease function get_firmwareRelease string get_firmwareRelease NSString firmwareRelease function get_firmwareRelease string function get_firmwareRelease As String string get_firmwareRelease String get_firmwareRelease def get_firmwareRelease YModule target get_firmwareRelease Returns a string corresponding to the version of the firmware embedded in the module On failure throws an exception or returns Y_F TRMWARERELEASE_INVALID YModule 148 www yoctopuce com 19 High level API Reference module get_hardwareld module gt hardwareld Returns the unique hardware identifier of the module function get_hardwareld function get_hardwareld function get_hardwareld string get_hardwareld NSString hardwareld function get_hardwareld As String string get_hardwareld String get_hardwareld def get_hardwareld
195. s 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 46 www yoctopuce com 9 Using Yocto Relay with PHP Common issues For the HTTP callback API to work the PHP option allow_url_fopen must be set Some web site hosts do not set it by default The problem then manifests itself with the following error error URL file access is disabled in the server configuration To set this option you must create in the repertory where the control PHP script is located an htaccess file containing the following line php flag allow_url_fopen On Depending on the security policies of the host it is sometimes impossible to authorize this option at the root of the web site or even to install PHP scripts receiving data from a POST HTTP In this case place the PHP script in a subdirectory Limitations This method that allows you to go through NAT filters cheaply has nevertheless a price Communications being initiated by the VirtualHub at a more or less regular interval reaction time to an event is clearly longer than if the Yoctopuce modules were driven directly You can configure the reaction time in the specific window of the Virtua Hub but it is at least of a few seconds in the best case The HTTP callback Yocto API mode is currently available in PHP and Node JS only 9 5 Error handling When you implement a program which m
196. se duration in millisecondes Returns YAPI_SUCCESS if the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 209 19 High level API Reference relay registerValueCallback Registers the callback function that is invoked on every change of advertised value is __ function registerValueCallback callback node js function registerValueCallback callback php function registerValueCallback callback int registerValueCallback YRelayValueCallback callback int registerValueCallback YRelayValueCallback callback pas function registerValueCallback callback TYRelayValueCallback LongInt vo function registerValueCallback As Integer int registerValueCallback ValueCallback callback int registerValueCallback UpdateCallback callback def registerValueCallback callback YRelay The callback is invoked only during the execution of ySleep or yHandleEvents This provides control over the time when the callback is triggered For good responsiveness remember to call one of these two functions periodically To unregister a callback pass a null pointer as argument Parameters callback the callback function to call or a null pointer The callback function should take two arguments the function object of which the value has changed and the character string describing the new advertised value 210 www yoctopuce com 19
197. se 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 YRelay FindRelay The YRelay FindRelay function allows you to find a relay 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 Relay module with serial number RELAYLO1 123456 which you have named MyModule and for which you have given the relay7 function the name MyFunction The following five calls are strictly equivalent as long as MyFunction is defined only once relay YRelay FindRelay RELAYLO1 123456 relayl relay YRelay FindRelay RELAYLO1 123456 MyFunction relay YRelay FindRelay MyModule relay1 relay YRelay FindRelay MyModule MyFunction relay YRelay FindRelay MyFunction YRelay FindRelay returns an object which you can then use at will to control the relay isOnline The isOnline method of the object returned by YRelay FindRelay allows you to know if the corresponding module is present and in working order set_state The set _state method
198. set_userData data function set_userData data function set_userData data void set_userData void data void setUserData void data procedure set_userData data Tobject procedure set_userData ByVal data As Object void set_userData object data void set_userData Object data def set_userData data This attribute is never touched by the API and is at disposal of the caller to store a context Parameters data any kind of object to be stored www yoctopuce com 217 19 High level API Reference relay wait_async YRelay Waits for all pending asynchronous commands on the module to complete and invoke the user provided callback function function wait_async callback context function wait_async callback context The callback function can therefore freely issue synchronous or asynchronous commands without risking to block the Javascript VM Parameters callback callback function that is invoked when all pending commands on the module are completed The callback function receives two arguments the caller specific context object and the receiving function object context caller specific object that is passed as is to the callback function Returns nothing 218 www yoctopuce com 20 Troubleshooting 20 1 Linux and USB To work correctly under Linux the the library needs to have write access to all the Yoctopuce USB peripherals However by default under Linux USB p
199. siie aeeie erar ALa dl deeded eevee 19 6 2 The Yocto Relay Module iii nei ed ee ee Tan Mae ia east 20 6 3 Module control interface rianan ieaiaia r Eao erta otita TEANA LE Eaa iaa Feii ETETE 21 6 4 Relay function Interface siiin iena bininin intar nina trena harane iiien a rrada oaa aana Din aida irana d asiana aiaia 22 6 5 What interface Native DLL or Service u sssssssesssrrseesrrrrreesrrrrresrrrrrerrrrrrnrrrrrsnrrrrenserreeene 23 6 6 Programming where to Start a onenaren atie ea aaa a ega a e eaaa arra draaien 25 7 Using the Yocto Relay in command line ooo ccc tc ee ee eeteeteeeeeeees 27 HEV TASTALIAG aaa aaa a i a tee Ghee tyevyoetasn scene a aaa iE 27 7 2Usez general GSScription aea a a a T aa a a a AA Eaa aea E AAEE ER EERE 27 7 3 Control of the Relay function essesssssesssresrsrsssrrnnsrnrnstrnnnrnnnttnatnrnantttnnttennnentnncennneennaanenne 28 7 4 Control of the Mod le part i e aa AA ik a a Ee aAa ieee iede AKEE a es 28 Fe EMMMILATIONS ps Sed evesseek ce leeck a vee dese doused obaevsidicbesveovaceasedecenisesiueveseeedee 29 8 Using Yocto Relay with Javascript 2 0 0 cc cee ceeeeeseeseeseeseeteeneeeeeneeeens 31 8 1 Getting ready i aa araa ea lee deleeee a a aaa ea Ea e E e 31 8 2 Control of the Relay function sssesesssesssiesrrrrssrrnssrnrnssrnenrrntnntnnnetrnaettnnttnnantnnnantnnnennnnnenne 31 8 3c Gontro of the module part denn aeiaaeeo aaa aaa Ta ae Ar AAEE Ea aaa Aa esa eis eee eee 33 8 4 A o
200. so use the saveToFlash method Inversely it is possible to force the module to forget its current settings by using the revertFromFlash method The short example below allows you to modify the logical name of a module import lt Foundation Foundation h gt import yocto_api h static void usage const char exe NSLog usage s lt serial gt lt newLogicalName gt n exe exit 1 Ine Man Vink eeen Conse char w arg NSError error autoreleasepool Setup the API to use local USB devices if yRegisterHub usb amp error YAPT SUCCESS NSlog RegaisterHub ernnor 26 enrer llocalizedbescription i return 1 Lijarce 2 usage argv 0 NSString serial or name NSString stringWithUTF8String argv 1 YModule module yFindModule serial or name use serial or logical name if module isOnline Te arge z 3 NSString newname NSString stringWithUTF8String argv 2 if yCheckLogicalName newname NSLog Invalid name n newname usage argv 0 module logicalName newname module saveToFlash NSLog Current name n module logicalName Melsen NSLog not connected check identification and USB cable n serial or name return 0 Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linke
201. stRelay if relay is None die No module connected m relay get_module target m get_serialNumber print using target relay YRelay FindRelay target relay channel if not relay isOnline die device not connected if state A relay set_state YRelay STATE A else relay set_output YRelay STATE _B 15 4 Control of the module part Each module can be controlled in a similar manner you can find below a simple sample program displaying the main parameters of the module and enabling you to activate the localization beacon usr bin python coding utf 8 import os sys from yocto api import def usage sys exit usage demo lt serial or logical name gt ON OFF errmsg YRefParam if YAPI RegisterHub usb errmsg YAPI SUCCESS sys exit RegisterHub error str errmsg if len sys argv lt 2 usage m YModule FindModule sys argv 1 use serial or logical name Heh mess Onllanmer ie if len sys argv gt 2 if sys argv 2 upper ON m set_beacon YModule BEACON_ON if sys argv 2 upper OFF m set_beacon YModule BEACON_ OFF print serial m get_serialNumber print logical name m get_logicalName print luminosity sea mmc Ceameumbm Oseatsya 9 y if m get_beacon YModule BEACON ON print beacon ON elses print beacon print upTime OFF Use mance emu ame 0 O00 Eas eeu www yoctopuce com 85
202. ster a callback function to be called each time a network hub or a VirtualHub is detected on the local network void RegisterHubDiscoveryCallback NewHubCallback callback Parameters callback a procedure taking a two string as parameter or null www yoctopuce com 125 19 High level API Reference YAPI RegisterLogFunction YAPI yRegisterLogFunction Registers a log callback function void yRegisterLogFunction yLogFunction logfun void yRegisterLogFunction yLogCallback logfun procedure yRegisterLogFunction logfun yLogFunc procedure yRegisterLogFunction ByVal logfun As yLogFunc cs void RegisterLogFunction yLogFunc logfun java _ void RegisterLogFunction LogCallback logfun def RegisterLogFunction logfun This callback will be called each time the API have something to say Quite usefull to debug the API Parameters logfun a procedure taking a string parameter or nul 1 126 www yoctopuce com 19 High level API Reference YAPI SelectArchitecture YAPI ySelectArchitecture Select the architecture or the library to be loaded to access to USB def SelectArchitecture arch By default the Python library automatically detects the appropriate library to use However for Linux ARM it not possible to reliably distinguish between a Hard Float armhf and a Soft Float armel install For in this case it is therefore recommended to manually select the proper architecture by call
203. t after the given number of seconds function reboot secBeforeReboot function reboot secBeforeReboot function reboot secBeforeReboot int reboot int secBeforeReboot int reboot int secBeforeReboot function reboot secBeforeReboot Longint Longint function reboot As Integer int reboot int secBeforeReboot int reboot int secBeforeReboot def reboot secBeforeReboot YModule target reboot secBeforeReboot YModule Parameters secBeforeReboot number of seconds before rebooting Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 169 19 High level API Reference module gt revertFromFlash YModule Reloads the settings stored in the nonvolatile memory as when the module is powered on 5s function revertFromFlash koasjs function revertFromFlash prp function revertFromFlash cep_ int revertFromFlash int revertFromFlash eas _ function revertFromFlash Longint vo function revertFromFlash As Integer cs _ intrevertFromFlash java int revertFromFlash def revertFromFlash YModule target revertFromFlash Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code 170 www yoctopuce com 19 High level API Reference module saveToFlash Saves current settings in the
204. t state simply switch your cables on the board In order to use the functions described here you should include lt script type text javascript src yocto_relay js gt lt script gt var yoctolib require yoctolib var YRelay yoctolib Y Relay require_once yocto_relay php include yocto_relay h import yocto_relay h uses yocto_relay yocto_relay vb yocto_relay cs import com yoctopuce YoctoAPI YRelay from yocto_relay import Global functions yFindRelay func Retrieves a relay for a given identifier yFirstRelay Starts the enumeration of relays currently accessible YRelay methods relay delayedPulse ms_delay ms_duration Schedules a pulse relay describe Returns a short text that describes the relay in the form TYPE NAME SERIAL FUNCTIONID relay get_advertisedValue Returns the current value of the relay no more than 6 characters relay get_countdown Returns the number of milliseconds remaining before a pulse delayedPulse call When there is no scheduled pulse returns zero relay get_errorMessage Returns the error message of the latest error with the relay relay get_errorType Returns the numerical error code of the latest error with the relay relay get_friendlyName Returns a global identifier of the relay in the format MODULE_NAME FUNCTION_NAME relay get_functionDescriptor Returns a
205. t_upTime s64 get_upTime s64 upTime function get_upTime int64 v _ function get_upTime As Long long get_upTime long get_upTime def get_upTime YModule target get_upTime Returns an integer corresponding to the number of milliseconds spent since the module was powered on On failure throws an exception or returns Y_UPTIME_INVALID 160 www yoctopuce com 19 High level API Reference module get_usbBandwidth YModule module usbBandwidth Returns the number of USB interfaces used by the module function get_usbBandwidth function get_usbBandwidth function get_usbBandwidth Y_USBBANDWIDTH_enum get_usbBandwidth Y_USBBANDWIDTH_enum usbBandwidth function get_usbBandwidth Integer function get_usbBandwidth As Integer int get_usbBandwidth int get_usbBandwidth def get_usbBandwidth YModule target get_usbBandwidth Returns either Y_USBBANDWIDTH_SIMPLE or Y_USBBANDWIDTH_DOUBLE according to the number of USB interfaces used by the module On failure throws an exception or returns Y_USBBANDWIDTH_INVALID www yoctopuce com 161 19 High level API Reference module gt get_usbCurrent module gt usbCurrent Returns the current consumed by the module on the USB bus in milli amps function get_usbCurrent function get_usbCurrent function get_usbCurrent int get_usbCurrent int usbCurrent pas
206. te Enter new name Readin newname if not yCheckLogicalName newname then began Writeln invalid logical name exit end module set_logicalName newname module saveToFlash Writeln logical name is now module get_logicalName end Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not nil Below a short example listing the connected modules program inventory SAPPTYPE CONSOLE uses Sysutils yocto api var module TYModule errmsg 2 String pegin Setup the API to use local USB devices if yRegisterHub usb errmsg lt gt YAPT SUCCESS then begin Write RegisterHub error errmsg exit end Writeln Device list module yFirstModule while module lt gt nil do begin Writeln module get_serialNumber
207. that you can link it directly if you prefer You will soon notice that the C API defines many functions which return objects You do not need to deallocate these objects yourself the API does it automatically at the end of the application In order to keep them simple all the examples provided in this documentation are console applications Naturally the libraries function in a strictly identical manner if you integrate them in an application with a graphical interface You will find in the last section of this chapter all the information needed to create a wholly new project linked with the Yoctopuce libraries 10 1 Control of the Relay function A few lines of code are enough to use a Yocto Relay Here is the skeleton of a C code snipplet to use the Relay function oe lines Moree eljsil ol include yocto relay h Leal String errmsg YRelay relay Get access to your device connected locally on USB for instance yRegisterHub usb errmsg relay yFindRelay RELAYLO1 123456 relayl 1 http www microsoft com visualstudio en us products 2010 editions visual cpp express www yoctopuce com EN libraries php www yoctopuce com 49 10 Using Yocto Relay with C Hot plug is easy just check that the device is online if relay gt isOnline Vi a aa SC tmcrat el imma Let s look at these lines in more details yocto_api h et yocto_relay h These two include files provide access to the functions al
208. the API to use local USB devices if YAPI RegisterHub usb errmsg YAPI SUCCESS sys exit init error str errmsg print O Device Gst module YModule FirstModule while module is not None print module get serialNumber module get productName module module nextModule a 15 5 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library The simplest way to work around the problem is the one used in the short examples provided in this chapter before accessing a module check that it is online with the isOnline function and then hope that it will stay so during the fraction of a second necessary for the following code lines to run This method is not perfect but it can be sufficient in some cases You must however be aware that you cannot completely exclude an error which would occur after the call to isOnline and which could crash the software The only way to prevent this is to implement one of the two error handling techniques described below The method recommended by most programming languages for unpredictabl
209. 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 12 at the factory productRelease Release number of the module hardware preprogrammed at the factory www yoctopuce com 21 6 Programming general concepts 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
210. the relay that will be automatically advertised up to the parent hub For a relay the advertised value is the the relays state A for the idle position B for the active position state Active output of the relays A for the idle position B for the active position 22 www yoctopuce com 6 Programming general concepts stateAtPowerOn Active output of the relays at device power up A for the idle position B for the active position UNCHANGED to leave the relay as is maxTimeOnStateA Maximum time ms allowed for relays to stay in state A before automatically switching back in to B state Z ro means no maximum time maxTimeOnStateB Maximum time ms allowed for relays to stay in state B before automatically switching back in to A state Z ro means no maximum time output Output state of the relays when used as a simple switch single throw pulseTimer Time during which the relays should be kept in state B active before returning automatically to state A idle state Any explicit state change issued afterwards will cancel the automated switch delayedPulseTimer Delayed pulse parameters countdown Waiting delay before next pulse delayed pulse case 6 5 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 Objec
211. tively 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 www yoctopuce com 23 6 Programming general concepts same for all languages the effort to support a new language is limited to coding the small library which controls the DLL From the end user stand point there are few differences one must simply make sure that the DLL is installed on the end user s computer at the same time as the main software The application uses the DLL to natively control the locally connected module Control by service Some languages do simply not allow you to easily gain access to the hardware layers of the machine It is the case for Javascript for instance To deal with this case Yoctopuce provides a solution in the form of a small piece of software called Virtual Hub It can access the modules and your application only needs to use a library which offers a
212. typical application is to control Yoctopuce devices located on a private network from a public web site The NAT filter advantages and disadvantages A DSL router which translates network addresses NAT works somewhat like a private phone switchboard a PBX internal extensions can call each other and call the outside but seen from the outside there is only one official phone number that of the switchboard itself You cannot reach the internal extensions from the outside www mysite com 192 168 0 1 64 136 20 37 a A i lt i 192 168 0 102 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 response Responses from request from LAN machines are routed 44 www yoctopuce com 9 Using Yocto Relay with PHP request i But requests from the outside are blocked Seeing Internet without being seen provides an enormous security advantage However this signi
213. ule YModule FindModule serial or name use serial or logical name if module isOnline 1 Verge 2 4 if stremp argv 2 ON 0 module setBeacon Y BEACON ON else module setBeacon Y BEACON OFF NSLog serial S n module serialNumber NSLog logical name n module logicalName NSLog luminosity Sd n module luminosity NSLog beacon ies if module beacon Y BEACON ON NSLog ON n else NSLog OFF n NSLog upTime d sec n module upTime 1000 NSLog USB current d mA n module usbCurrent NSLog logs n module get_lastLogs else NSLog not connected check identification and USB cable n serial or name return 0 Each property xxx of the module can be read thanks to a method of type get xxxx and properties which are not read only can be modified with the help of the set xxx method For more details regarding the used functions refer to the API chapters www yoctopuce com 59 11 Using Yocto Relay with Objective C 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
214. ule can be disconnected after the control software has started The isOnline method available in all the classes is then very helpful Access to the modules Even if it is perfectly possible to build a complete project while making a total abstraction of which function is hosted on which module the modules themselves are also accessible from the API In fact they can be handled in a way quite similar to the functions They are assigned a serial number at the factory which allows you to find the corresponding object with YModule Find You can also assign arbitrary logical names to the modules to make finding them easier Finally the YModule class contains the YModule FirstModule and nextModule enumeration methods allowing you to list the connected modules Functions Module interaction From the API standpoint the modules and their functions are strongly uncorrelated by design Nevertheless the API provides the possibility to go from one to the other Thus the get_module method available for each function class allows you to find the object corresponding to the module hosting this function Inversely the YModule class provides several methods allowing you to enumerate the functions available on a module 6 2 The Yocto Relay module The Yocto Relay module provides two instances of Relay function corresponding to the two relays of the module module Module 20 www yoctopuce com 6 Programming general concepts
215. ule target set_luminosity newval The parameter is a value between 0 and 100 Remember to call the saveToFlash method of the module if the modification must be kept Parameters newval an integer corresponding to the luminosity of the module informative leds Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code 174 www yoctopuce com 19 High level API Reference module set_usbBandwidth YModule module setUsbBandwidth Changes the number of USB interfaces used by the module function set_usbBandwidth newval function set_usbBandwidth newval function set_usbBandwidth newval int set_usbBandwidth Y_USBBANDWIDTH_enum newval int setUsbBandwidth Y_USBBANDWIDTH_enum newval function set_usbBandwidth newval Integer integer function set_usbBandwidth ByVal newval As Integer As Integer int set_usbBandwidth int newval int set_usbBandwidth int newval def set_usbBandwidth newval YModule target set_usbBandwidth newval You must reboot the module after changing this setting Parameters newval either Y_USBBANDWIDTH_SIMPLE or Y_USBBANDWIDTH_DOUBLE according to the number of USB interfaces used by the module Returns YAPI_ SUCCESS if the call succeeds On failure throws an exception or returns a negative error code www yoctopuce com 175 19 High level API Reference module set_userData YModule module
216. um get_persistentSettings Y_PERSISTENTSETTINGS_ enum persistentSettings pas _ function get_persistentSettings Integer v _ function get_persistentSettings As Integer int get_persistentSettings int get_persistentSettings def get_persistentSettings YModule target get_persistentSettings Returns a value among Y_PERSISTENTSETTINGS_LOADED Y_PERSISTENTSETTINGS_SAVED and Y_PERSISTENTSETTINGS_MODIFIED corresponding to the current state of persistent module settings On failure throws an exception or returns Y_PERSISTENTSETTINGS_INVALID 154 www yoctopuce com 19 High level API Reference module gt get_productld module gt productld Returns the USB device identifier of the module function get_productld function get_productld function get_productld int get_productld int productld function get_productld LongInt function get_productld As Integer int get_productld int get_productld def get_productld YModule target get_productld Returns an integer corresponding to the USB device identifier of the module On failure throws an exception or returns Y_PRODUCTID_INVALID YModule www yoctopuce com 155 19 High level API Reference module get_productName module gt productName Returns the commercial name of the module as set by the factory function get_productName function get_productName function g
217. ust 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 e If your code catches the exception and handles it everything goes well e If your program is running in debug mode you can relativel
218. vavailable relay relay YFirstRelay if relay nil then begin writeln No module connected check USB cable halt end retreive the hosting device serial Ne Sere lave ge ummodullen iy Langer H ma Ger ese ruc Number s end Writeln using target retreive the right channel relay YFindRelay target relay channel lets switch the relay if relay isOnline then begin ae ereta GUN wasii Teileyo Ss Sta Owigotie Yn OUP UI ONI else relay set_output Y_ OUTPUT OFF end else writeln Module not connected check identification and USB cable end There are only a few really important lines in this sample example We will look at them in details yocto_api and yocto_relay These two units provide access to the functions allowing you to manage Yoctopuce modules yocto_ api must always be used yocto_relay is necessary to manage modules containing a relay such as Yocto Relay 78 www yoctopuce com 14 Using Yocto Relay with Delphi 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 yFindRelay The yFindRelay function allows you to find a relay from the serial
219. ve its configuration after executing the command target is the name of the module or of the function to which the command applies Some very generic commands do not need a target You can also use the aliases any and all or a list of names separated by comas without space lif you want to recompile the command line API you also need the C API 2 http www yoctopuce com EN libraries php www yoctopuce com 27 7 Using the Yocto Relay in command line command is the command you want to run Almost all the functions available in the classic programming APIs are available as commands You need to respect neither the case nor the underlined characters in the command name parameters logically are the parameters needed by the command At any time the command line API executables can provide a rather detailed help Use for instance executable help to know the list of available commands for a given command line API executable or even executable command help to obtain a detailed description of the parameters of a command 7 3 Control of the Relay function To control the Relay function of your Yocto Relay you need the YRelay executable file For instance you can launch YRelaymanyes SEES CASB This example uses the any target to indicate that we want to work on the first Relay function found among all those available on the connected Yoctopuce modules when running This prevents you from having to know the
220. viceList def UpdateDeviceList errmsg None The library searches the machines or USB ports previously registered using yRegisterHub and invokes any user defined callback function in case a change in the list of connected devices is detected This function can be called as frequently as desired to refresh the device list and to make the application aware of hot plug events Parameters errmsg a string passed by reference to receive any error message Returns YAPI_SUCCESS when the call succeeds On failure throws an exception or returns a negative error code 132 www yoctopuce com 19 High level API Reference YAPI UpdateDeviceList_async YAPI yUpdateDeviceList_async Triggers a re detection of connected Yoctopuce modules function yUpdateDeviceList_async callback context function UpdateDeviceList_async callback context The library searches the machines or USB ports previously registered using yRegisterHub and invokes any user defined callback function in case a change in the list of connected devices is detected This function can be called as frequently as desired to refresh the device list and to make the application aware of hot plug events This asynchronous version exists only in Javascript It uses a callback instead of a return value in order to avoid blocking Firefox Javascript VM that does not implement context switching during blocking I O calls Parameters callback callback fu
221. w a short example listing the connected modules import com yoctopuce YoctoAPI public class Demo publies tarie vVordimna Norc mg lacs try setup the API to use local VirtualHub YAPI RegisterHub 127 0 0 1 catch YAPT Exception ex System ouk praintin M annor contact Vartualbub ion 127700 ld 1 ex getLocalizedMessage System out printin Ensure that the VirtualHub application is running System exit 1 Oys Cem outprint IMIADEV ICE ISEAN YModule module YModule FirstModule while module null try System out printin module get_serialNumber Moduler Ger EroduceNamer isa iy catch YAPT Exception ex longe alkay module module nextModule YAPI FreeAPI 16 4 Error handling When you implement a program which must interact with USB modules you cannot disregard error handling Inevitably there will be a time when a user will have unplugged the device either before running the software or even while the software is running The Yoctopuce library is designed to help you support this kind of behavior but your code must nevertheless be conceived to interpret in the best possible way the errors indicated by the library 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 th
222. 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 82 www yoctopuce com 15 Using the Yocto Relay with Python Python is an interpreted object oriented language developed by Guido van Rossum Among its advantages is the fact that it is free and the fact that it is available for most platforms Windows as well as UNIX It is an ideal language to write small scripts on a napkin The Yoctopuce library is compatible with Python 2 6 and 3 It works under Windows Mac OS X and Linux Intel as well as ARM The library was tested with Python 2 6 and Python 3 2 Python interpreters are available on the Python web site 15 1 Source files The Yoctopuce library classes for Python that you will use are provided as source files Copy all the content of the Sources directory in the directory of your choice and add this directory to the PYTHONPATH environment variable If you use an IDE to program in Python refer to its documentation to configure it so that it automatically finds the API source files 15 2 Dynamic library A section of the low level library is written in C but
223. wing five calls are strictly equivalent as long as MyFunction is defined only once relay yFindRelay RELAYLO1 123456 relayl1 relay yFindRelay RELAYLO1 123456 MyFunction relay yFindRelay MyModule relayl relay yFindRelay MyModule MyFunction relay yFindRelay MyFunction yFindRe lay returns an object which you can then use at will to control the relay isOnline The isOnline method of the object returned by yFindRelay allows you to know if the corresponding module is present and in working order set_state The set _state method of the objet returned by yFindRelay switches the relay position to one of its two outputs The two possible parameter values are Y STATE A for output A and Y STATE _B for output B 4 Remember to change the filter of the selection window otherwise the DLL will not show 64 www yoctopuce com 12 Using Yocto Relay with Visual Basic NET A real example Launch Microsoft VisualBasic and open the corresponding sample project provided in the directory Examples Doc GettingStarted Yocto Relay of the Yoctopuce library In this example you will recognize the functions explained above but this time used with all side materials needed to make it work nicely as a small demo Module Modulel Private Sub Usage Dim execname System AppDomain CurrentDomain FriendlyName Console WriteLine Usage Console Writehinel execnamet lt seriallnumber gt
224. wname m YModule FindModule args 0 use serial or logical name cry 4 newname args 1 if YAPI CheckLogicalName newname System out printin Invalid name newname System exit 1 m set_logicalName newname m saveToFlash do not forget this System our print in Module serial pamiget serial Number i System out printlin name m get_logicalName Gace Ch w VAP Te Brae peje i mex ma System out println Module args 0 not connected check identification and USB cable System out printin ex getMessage System exit 1 YAPI FreeAPI 92 www yoctopuce com 16 Using the Yocto Relay with Java Warning the number of write cycles of the nonvolatile memory of the module is limited When this limit is reached nothing guaranties that the saving process is performed correctly This limit linked to the technology employed by the module micro processor is located at about 100000 cycles In short you can use the YModule saveToFlash function only 100000 times in the life of the module Make sure you do not call this function within a loop Listing the modules Obtaining the list of the connected modules is performed with the YModule yFirstModule function which returns the first module found Then you only need to call the nextModule function of this object to find the following modules and this as long as the returned value is not null Belo
225. y easily determine where the problem happened and view the explanatory message linked to the exception e Otherwise the exception makes your program crash bang As this latest situation is not the most desirable the Yoctopuce library offers another possibility for error handling allowing you to create a robust program without needing to catch exceptions at every line of code You simply need to call the yDisableExceptions function to commute the library to a mode where exceptions for all the functions are systematically replaced by specific return values which can be tested by the caller when necessary For each function the name of each return value in case of error is systematically documented in the library reference The name always follows the same logic a get state method returns a Y STATE INVALID value a get _currentValue method returns a Y CURRENTVALUE INVALID value and so on In any case the returned value is of the expected type and is not a null pointer which would risk crashing your program At worst if you display the value without testing it it will be outside the expected www yoctopuce com 47 9 Using Yocto Relay with PHP 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 obtai
226. y is connected and where you run the VirtualHub lt HTML gt lt HEAD gt lt TITLE gt Hello World lt TITLE gt lt SCRIPT type text javascript src yocto_api js gt lt SCRIPI gt lt SCREPT Seype WEext Javascripti Sre yOClLo mellay jist lt SCRIBIS lt SCRIPT language javascriptl 5 type text JavaScript gt 2S Setup the API to use the VirtualHub on local machine if yRegisterHub http 127 0 0 1 4444 YAPI SUCCESS alex ti tCannor Contacti vir cual HUG On 12700 ni varn CIP E2 function refresh var serial document getHlementBylId serial value if serial Detect any conected module suitable for the demo rl yFirstRelay aie Gey serial rl module PgetescrialNumber document getElementBylId serial value serial rl yFindRelay serial relayl r2 yFindRelay serial relay2 fief tells Onley at document gethlementByid msgq value else document getElementBylId msg value Module not connected setTimeout refresh 500 function switchIt relay state Iie tate relay nicer sicdec Ms oiAusEnmE it else relayo Ser Siente SEAH JAJE gt lt SCRIPT gt lt HEAD gt lt BODY onload refresh gt Module to use lt input id serial gt lt input id msg style color red border none readonly gt lt br gt lt a href javascript switchIt rl true gt Switch relay 1 to outpout B lt a gt lt br
227. y list the connected modules to deduce which ones just arrived and which ones left To be warned as soon as a module is connected you need three pieces of code The callback The callback is the function which is called each time a new Yoctopuce module is connected It takes as parameter the relevant module static void deviceArrival YModule m Console WriteLine New module m get_serialNumber www yoctopuce com 107 18 Advanced programming Initialization You must then tell the API that it must call the callback when a new module is connected YAPI RegisterDeviceArrivalCallback deviceArrival Note that if modules are already connected when the callback is registered the callback is called for each of the already connected modules Triggering callbacks A classis issue of callback programming is that these callbacks can be triggered at any time including at times when the main program is not ready to receive them This can have undesired side effects such as dead locks and other race conditions Therefore in the Yoctopuce API module arrival departure callbacks are called only when the UpdateDeviceList function is running You only need to call UpdateDeviceList at regular intervals from a timer or from a specific thread to precisely control when the calls to these callbacks happen waiting loop managing callbacks while true module arrival departure callback YAP UpdateDevicelist re
228. yDisableExceptions Setup the API to use the VirtualHub on local machine if yRegisterHub http 127 0 0 1 4444 Serrmsg YAPI_SUCCESS die Cannot contact VirtualHub on 127 0 0 1 Serrmsg Sserial CEN serialik renser Ii Y UD 4 Check if a specified module is available online Smodule yFindModule Sserial if Smodule gt isOnline die Module not connected check serial and USB cable else or use any connected module suitable for the demo Smodule yFirstModule if Smodule skip VirtualHub Smodule Smodule gt nextModule ji if is_ null module die No module connected check USB cable else serial module gt get_serialnumber Print Module to use lt input name serial value Sserial gt lt br gt if isset _GET beacon if _GET beacon ON module gt set_beacon Y BEACON ON else Smodule gt set_beacon Y BEACON OFF printi serial ss lt br gt module gt get_serialNumber printf logical name ss lt br gt module gt get_logicalName printf luminosity s lt br gt module gt get_luminosity PEImMe beacons if S module gt get_beacon Y_ BEACON ON printf lt input type radio name beacon value ON checked gt ON printf lt input type radio name beacon value OFF gt OFF lt br gt else printf lt input type radio name beacon value ON gt ON print
Download Pdf Manuals
Related Search
Related Contents
Copyright © All rights reserved.
Failed to retrieve file