Logging, Exceptions, and Errors: Difference between revisions

From Phidgets Support
No edit summary
(Changed redirect target from Handling Errors and Logging to Phidget Logging)
Tag: Redirect target changed
 
(10 intermediate revisions by 5 users not shown)
Line 1: Line 1:
[[Category:Programming]]
#REDIRECT [[Phidget Logging]]
You've written your code, fixed the compiler errors, and yet, the program still isn't behaving as intended. The tools described on this page will help you further debug your program and figure out where in the code things are going wrong.
 
 
==Logging==
 
The {{Phidget22API}} supports a general logging API that supports log levels, named sources of logs, and the writing of logs to a file or to a Phidget Network Server.  The Phidget software library uses this logging system internally, so in addition to being able to log within your own software, information about what the Phidget software is doing is also available.  Refer to the ''Logging API'' in the {{Phidget22API}} for language specific information.
 
To begin, logging must be enabled
 
<syntaxhighlight lang=c>
PhidgetLog_enable(PHIDGET_LOG_DEBUG, NULL);
</syntaxhighlight>
 
Or in Java:
 
<syntaxhighlight lang=java>
Log.enable(LogLevel.DEBUG, null);
</syntaxhighlight>
 
When <code>NULL</code> is passed to <code>enable()</code> in the above examples, the logging system will output to <code>STDERR</code>.
 
There are five different logging levels, ranging from "Give me Everything!" to "Tell me only about critical problems".
 
'''CRITICAL'''
:Critical error messages.
:Errors at this level are generally non-recoverable and indicate either hardware problems, library bugs, or other serious issues.
 
'''ERROR'''
:Non-critical error messages.
:Errors at this level are generally automatically recoverable, but may help to track down issues.
 
'''WARNING'''
:Warning messages.
:Warnings are used to log behavior that is not necessarily in error, but is nevertheless odd or unexpected.
 
'''INFO'''
:Informational messages.
:Informational messages communicate useful operations and states changes within the software
 
'''VERBOSE'''
:Verbose messages.
:Verbose messages are informational messages that are expected to happen so frequently that they tend to drown out other log messages.
 
These are available in the '''Enumerations''' section of Logging API in the {{Phidget22API}} documentation.
 
=== Logging in Your Program ===
 
Logging is performed using the <code>log()</code> method from the Logging API.
 
For example, in C:
 
<syntaxhighlight lang=c>
PhidgetLog_log(PHIDGET_LOG_INFO, "Something happened in loop iteration %d!", i);
</syntaxhighlight>
 
Or in Java:
 
<syntaxhighlight lang=java>
Log.log(LogLevel.INFO, "Something happened in loop iteration " + i + "!");
</syntaxhighlight>
 
The logging API supports the concept of a ''log source'', were the ''log source'' is a textual identifier of where the log message originated.  The ''log source'' is output to log the log file along with the log message to help organize the data.
 
The following examples define and create a log source, and then write a log message using that source.
 
<syntaxhighlight lang=c>
#define MYSOURCE "mysource"
PhidgetLog_addSource(MYSOURCE, PHIDGET_LOG_INFO);
PhidgetLog_log(__FILE__, __LINE__, __func__, MYSOURCE, PHIDGET_LOG_INFO, "Something happened");
</syntaxhighlight>
 
Or in Java:
 
<syntaxhighlight lang=java>
public static final String MYSOURCE = "mysource";
Log.addSource(MYSOURCE, LogLevel.INFO);
Log.log(LogLevel.INFO, MYSOURCE, "Something happened);
</syntaxhighlight>
 
 
==Exceptions and Errors==
 
There are two different types of errors that you can use to determine where a problem exists in your program.
 
===Error Generated By Methods===
 
When an error occurs during a method invocation, either a language specific exception is thrown, or an error is returned.  It is important to check the return value from each method call, and to catch and handle exceptions.
 
For example, in C:
 
<syntaxhighlight lang=c>
  int
  main(int argc, char **argv) {
    PhidgetReturnCode res;
 
    res = PhidgetLog_enable(PHIDGET_LOG_ERROR, NULL);
    if (res != EPHIDGET_OK) {
      fprintf(stderr, "failed to enable Phidget logging: %d\n", res);
      exit(1);
    }
    exit(0);
  }
</syntaxhighlight>
 
Or in Java:
 
<syntaxhighlight lang=java>
  try {
      Log.enable(LogLevel.INFO, null);
  } catch (PhidgetException ex) {
      System.out.println("Failed to enable Phidget logging: " + ex.getMessage());
  }
</syntaxhighlight>
 
The consequence of not handling errors correctly ranges from the program crashing if an unhandled exception occurs to improper behavior.  Program should check for errors on each method call, and handle any errors.
 
====Error Codes====
 
A list of error codes can be found in the {{Phidget22API}}.  Refer to language specific exceptions in language that support them.
 
===Error Generated From The Device===
 
These errors are generated by the Phidget library during runtime.  For example, the Phidget device might be experiencing too high a temperature, and trigger an error.  This would not necessarily be due to any one function your program called; rather, the error would appear when the problem appears and would trigger an event.
 
So, these errors happen ''asynchronously'', that is, something happens apart from any function calls and an error event is triggered. You can handle these by setting up an Error Event Handler.
 
In C, this would look like:
 
<syntaxhighlight lang=cpp>
  int ErrorEventHandler (PhidgetHandle device, void *usrptr, Phidget_ErrorEventCode errorCode, const char *errorDescription) {
    printf("The description for error %d is: %s\n", errorCode, errorDescription);
    // Do something useful based on the error code
    return 0;
  }
 
  // At the beginning of your program, hook the Error Event Handler in to receive events
  LocalErrorCatcher(
      Phidget_setOnErrorHandler((PhidgetHandle) device, ErrorEventHandler, NULL));
</syntaxhighlight>
 
You'll note that the '''ErrorEventHandler''' function is what gets called when an error event occurs, and it gives you an opportunity to handle the error. 
 
You'll also note that there is a second function called '''LocalErrorCatcher'''.  This second function handles the return value from setting the  error handler.  We included it here because, as these are examples on how to handle errors, the example would leave a possibly unhandled error without it. This second type of error handling  and the '''LocalErrorCatcher''' function are [[#Phidget Return Codes|described above]].
 
In Java, it would look like this:
 
<syntaxhighlight lang=java>
  try {
    device.addErrorListener((ErrorEvent ee) -> {
            System.out.println("Error: " + ee.getDescription());
        });
    });
  } catch (PhidgetException exception) {
      system.out.println("The description for error " + Integer.toString(exception.getErrorCode()) + " is: ", exception.getDescription());
  }
 
</syntaxhighlight>
 
Like C above, the act of hooking an error listener in to the device can itself generate an error, which should be caught. 
 
These event-type errors are also how a Phidget being run over a network announces bad passwords, lost packets, and other network problems.  Locally, the errors can announce incorrect temperatures, current, and power. So, it is in your best interest to set up an error event handler and take action based on the codes and error types in the {{Phidget22API}}.
 
====Error Codes====
 
These codes are used within the Error Event. See the {{Phidget22API}} documentation for your device to see which codes can be returned by which functions. These codes can be very generalized so it’s important to look at the accompanying description. These codes are broken down into errors that stem from within the library, errors which are directly reported by Phidget hardware, and errors that occur in your software.
 
'''BADVERSION'''
:Version Mismatch Error. Usually means client and host side of a network connection are out of sync. Update the latest versions of the Phidget drivers on both the client and the host.
 
 
'''BUSY'''
:The Phidget channel has already been opened locally by another process, so it can't be opened. You can have multiple processes open the same channel if they all open it remotely (with the exception of some Phidgets like motor controllers, which only allow a single connection regardless of whether it's local or remote).
 
 
'''NETWORK'''
:An error occurred with the network communications. See the error description for more details.
 
 
'''DISPATCH'''
:An error occurred when trying to dispatch an event. It's possible that the data rate is too fast for the computer you're using and the event queue has filled up.
 
 
'''OK'''
: An error state has ended. You can use the <code>getDescription</code> method of the error event to get more information. For example, if there is an over-voltage condition occurring, this error code will be thrown when the voltage returns to acceptable levels.
 
 
'''OVERRUN'''
:Sampling overrun. Some samples were lost in firmware because the queue filled up. This error is exclusive to Phidget InterfaceKits.
 
 
'''PACKETLOST'''
:Packet(s) were lost. This error is often an indication that your event handlers are not executing fast enough. Try to remove slow processes like GUI updates or user input from your handlers.
 
 
'''WRAP'''
:A variable has wrapped. For example, the encoder position can wrap from 2,147,483,647 to -2,147,483,648 because of an integer overflow.
 
 
'''OVERTEMP'''
:Over-Temperature condition detected. See error description for more details.
 
 
'''OVERCURRENT'''
:Over-Current condition detected. See error description for more details.
 
 
'''OUTOFRANGE'''
:Out of range condition detected. Usually an input on the board is reporting a value that is outside of the allowed range.
 
 
'''BADPOWER'''
:Power supply problem detected. Either the power supply is being overloaded, or it is under-powered (possibly not plugged in).
 
 
'''SATURATION'''
:A sensor's value has reached the maximum or minimum of its sensing range. For example, a 1000 lux light sensor will throw this error event when a value greater than 1000 lux is detected. The sensor will still be reporting 1000 lux, but this error tells you that you don't know for certain how much higher than 1000 the real reading is.
 
 
'''OVERVOLTAGE'''
:Over-Voltage condition detected. Occurs in power-providing Phidgets when the output voltage exceeds the set value.
 
 
'''VOLTAGEERROR'''
:A voltage error occurs when a Phidget that provides a voltage output has the value drop below what what specified. This can happen if the device being powered draws too much current, which causes a voltage drop. Stay within output current specifications to avoid voltage errors.
 
 
'''ENERGYDUMP'''
:An energy dump occurs when a power-providing Phidget needs to dissipate its extra energy. See the [[:Category:UserGuide|User Guide]] for your device for more information.
 
== Other Problems ==
 
If your Phidget is still not behaving as expected after handling errors and exceptions, have a look at our [[General Troubleshooting]] guide to track down the problem.
 
== Further Reading ==
 
[[Phidget Programming Basics]] - Here you can find the basic concepts to help you get started with making your own programs that use Phidgets.
 
[[Data Interval/Change Trigger]] - Learn about these two properties that control how much data comes in from your sensors.
 
[[Using Multiple Phidgets]] - It can be difficult to figure out how to use more than one Phidget in your program. This page will guide you through the steps.
 
[[Polling vs. Events]] - Your program can gather data in either a polling-driven or event-driven manner. Learn the difference to determine which is best for your application.
 
[[Phidget Network Server]] - Phidgets can be controlled and communicated with over your network- either wirelessly or over ethernet.
 
[[Best Phidgets Practices]] - Good programming habits that will save you from common problems when writing code for your Phidgets.

Latest revision as of 20:30, 3 August 2023

Redirect to: