Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagejava
titleSampleDeviceEventHandler
linenumberstrue
public class SampleDeviceEventHandler implements DeviceEventHandler {
    
    private final SamplePropertyUpdateHandler propertyHandler;
    
    public SampleDeviceEventHandler() {
        this.propertyHandler = new SamplePropertyUpdateHandler();
    }

    @Override
    public void onDeviceEvent(DeviceEvent event) {
        // This method gets called when a device is added to, or removed from, the network.
        // By default, client callbacks are called from a single thread managed by GAPI.
        // Therefore, avoid writing blocking code in this method, or other client callbacks
        // (such as PropertyUpdateHandlers, or ProtocolHandlers) may be blocked.
        
        final DeviceEventStatus eventStatus = event.getStatus();
        final Device device = event.getDevice();
        final String deviceId = device.getID();
        final String deviceType = device.getDeviceType().getType();
        
        System.out.println("Device Event: " + eventStatus);
        System.out.println("Device Id: " + deviceId);
        System.out.println("Device Type: " + deviceType);
        
        switch (eventStatus) {
        
        case DEVICE_ADDED:
            // Register a property handler, to be notified when a Property on the Device changes.
            device.addPropertyUpdateHandler(propertyHandler);
            
            // Automatically discover the device. This is a non-blocking call.
            CompletableFuture<Collection<Property>> properties = device.getProperties();
            
            // Do some extra (asynchronous) handling on the properties, once they've been discovered.
            properties.thenAccept( collection -> {
                // This code will be called from a thread managed by GAPI.
                // We should avoid writing blocking code in this section.
                for (Property p : collection) {
                    printDiscoveredProperty(p);
                }
            });

            break;

        case DEVICE_REMOVED:
            device.removePropertyUpdateHandler(propertyHandler);
            break;

        default:
            break;
        }
    }
    
    private static void printDiscoveredProperty(Property p) {
        StringBuilder sb = new StringBuilder();
        sb.append("Discovered Property: ").append(p.getName())
          .append(", with value: ").append(p.getValue())
          .append(", of type: ").append(p.getType());
        System.out.println(sb.toString());
    }
}

...