Custom Esper Rules Jumpstart

From RifidiWiki

Jump to: navigation, search

Custom Esper Rules

In addition to the normal Rifidi Services you can also create your own custom Esper rules. There is an example of this in the Northwind application as documented in the Developer's Guide.

Be sure that you understand the ReadZoneMonitorService as detailed in the Rifidi Services Jumpstart, as this guide will use the ReadZoneMonitoringService to help create the custom commands that we will use. We will add to the code already given in the previous example.

1. First, we will create some event classes that we will send through esper. These classes will have the information we want the event to contain:

public class DockDoorArrivedEvent {
	private final TagReadEvent tag;
	public DockDoorArrivedEvent(TagReadEvent tag) {
		super();
		this.tag = tag;
	}
	public TagReadEvent getTag() {
		return tag;
	}
}
public class DockDoorDepartedEvent {
	private final TagReadEvent tag;
	public DockDoorDepartedEvent(TagReadEvent tag) {
		super();
		this.tag = tag;
	}
	public TagReadEvent getTag() {
		return tag;
	}
}

2. Now, we need to add the event types in the _start() method

		addEventType(DockDoorArrivedEvent.class);
		addEventType(DockDoorDepartedEvent.class);

3. Now we will do something useful with the esper. Tags should not stay on the dock door too long, so we will create an esper rule

		StatementAwareUpdateListener dockDoorTagOnTooLongListener = new StatementAwareUpdateListener() {
			@Override
			public void update(EventBean[] arg0, EventBean[] arg1,
					EPStatement arg2, EPServiceProvider arg3) {
				if (arg0 != null) {
					TagReadEvent tag = (TagReadEvent) arg0[0]
							.get("dockarrived.tag");
					System.out.println("Tag seen for too long on the dock"
							+ " door: " + tag.getTag().getID());
				}
			}
		};
		addStatement("select dockarrived.tag from pattern "
				+ "[every dockarrived=DockDoorArrivedEvent-> "
				+ "timer:interval(" + this.dockdoor_dwelltime
				+ ") and not DockDoorDepartedEvent"
				+ "(tag.tag.ID=dockarrived.tag.tag.ID)]",
				dockDoorTagOnTooLongListener);

The "addStatement" method contains the esper itself. The "update" method of the listener will be called if an arrived event for a tag happens without a depart event for the same tag within the timelimit given by the "dwelltime" variable.

4. Now, we need to add the event into esper. We can change the methods in our subscriber class:

	@Override
	public void tagArrived(TagReadEvent tag) {
		System.out.println("Tag arrived at location " + location + ": "
				+ tag.getTag().getFormattedID());
		if (this.isDockDoor) {
			this.app.sendNorthwindEvent(new DockDoorArrivedEvent(tag));
		}
	}

	@Override
	public void tagDeparted(TagReadEvent tag) {
		System.out.println("Tag departed at location " + location + ": "
				+ tag.getTag().getFormattedID());
		if (this.isDockDoor) {
			this.app.sendNorthwindEvent(new DockDoorDepartedEvent(tag));
		}
	}
Personal tools