Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (c) SiteWhere, LLC. All rights reserved. http://www.sitewhere.com
   *
   * The software in this package is published under the terms of the CPAL v1.0
   * license, a copy of which has been included with this distribution in the
   * LICENSE.txt file.
   */
  package com.sitewhere.server.device;
  
 import java.util.Date;
 import java.util.List;
 import java.util.Map;
 import java.util.UUID;
 
 
Used to load a default site/devices/assignments/events so that there is demo data in the system. The server only offers this functionality if no sites already exist.

Author(s):
Derek
 
Static logger instance
 
 	private static Logger LOGGER = Logger.getLogger(DefaultDeviceModelInitializer.class);

Prefix for create site log message
 
 	public static final String PREFIX_CREATE_SITE = "[Create Site]";

Prefix for create device log message
	public static final String PREFIX_CREATE_DEVICE = "[Create Device]";

Prefix for create assignment log message
	public static final String PREFIX_CREATE_ASSIGNMENT = "[Create Assignment]";

Prefix for create zone log message
	public static final String PREFIX_CREATE_ZONE = "[Create Zone]";

Prefix for create event log message
	public static final String PREFIX_CREATE_EVENTS = "[Create Events]";

Number of devices to create
	public static final int NUM_SITES = 1;

Number of device groups to create
	public static final int NUM_DEVICE_GROUPS = 3;

Number of devices/assignments to create
	public static final int ASSIGNMENTS_PER_SITE = 40;

Number of events per assignment
	public static final int EVENTS_PER_ASSIGNMENT = 75;

Number of events per assignment
	public static final int LOCATIONS_PER_ASSIGNMENT = 40;

Minimum engine temp
	public static final double MIN_TEMP = 80;

Maximum engine temp
	public static final double MAX_TEMP = 200;

Temp at which a warning alert will be generated
	public static final double WARN_TEMP = 160;

Temp at which an error alert will be generated
	public static final double ERROR_TEMP = 180;

Temp at which a critical alert will be generated
	public static final double CRITICAL_TEMP = 190;

Image URL assocaited with sites
	public static final String SITE_IMAGE_URL =
			"https://s3.amazonaws.com/sitewhere-demo/construction/construction.jpg";

Namespace for common core commands
	public static final String SITEWHERE_COMMON_NAMESPACE = "http://sitewhere/common";

Namespace for Raspberry Pi commands
	public static final String RASPBERRY_PI_NAMESPACE = "http://raspberrypi/example";

Namespace for Android commands
	public static final String ANDROID_NAMESPACE = "http://android/example";

Namespace for Arduino commands
	public static final String ARDUINO_NAMESPACE = "http://arduino/example";

Specification token openHAB virual device
	public static final String OPENHAB_SPEC_TOKEN = "5a95f3f2-96f0-47f9-b98d-f5c081d01948";

Specification token for Laipac S-911 BL
	public static final String LAIPAC_S911_SPEC_TOKEN = "fc0f3d8d-c6e6-4fd2-b7d6-6f21bcf3a910";

Specification token for MeiTrack device
	public static final String MEITRACK_SPEC_TOKEN = "82043707-9e3d-441f-bdcc-33cf0f4f7260";

Token used for site
	public static final String SITE_TOKEN = "bb105f8d-3150-41f5-b9d1-db04965668d3";

Available choices for devices/assignments that track heavy equipment
	protected static AssignmentChoice[] HEAVY_EQUIPMENT = {
			new AssignmentChoice("Equipment Tracker"."300"),
			new AssignmentChoice("Equipment Tracker"."301"),
			new AssignmentChoice("Equipment Tracker"."302"),
			new AssignmentChoice("Equipment Tracker"."303"),
			new AssignmentChoice("Equipment Tracker"."304") };

Available choices for devices/assignments that track people
	protected static AssignmentChoice[] PERSONNEL = {
			new AssignmentChoice("Personnel Tracker"."1"),
			new AssignmentChoice("Personnel Tracker"."2"),
			new AssignmentChoice("Personnel Tracker"."3") };

Available choices for devices/assignments that track tools
	protected static AssignmentChoice[] TOOLS = {
			new AssignmentChoice("Tool Tracker"."2") };

Information for available device specifications
	public static final SpecificationDetails[] SPECIFICATION_INFO =
			{
					new SpecificationDetails("173""Android Tablet""d2604433-e4eb-419b-97c7-88efe9b2cd41",
					new SpecificationDetails("181""Arduino High Memory",
							"417b36a8-21ef-4196-a8fe-cc756f994d0b"),
					new SpecificationDetails("174""Raspberry Pi""7dfd6d63-5e8d-4380-be04-fc5c73801dfb",
					new SpecificationDetails("175""MeiTrack GPS"),
					new SpecificationDetails("176""Gateway Default",
							"75126a52-0607-4cca-b995-df40e73a707b"),
					new SpecificationDetails("190""openHAB"),
					new SpecificationDetails("300""Laipac Health Bracelet",
Available device specifications
Map of commands for each specification token
Locations that determine zone edges
Device management implementation
Indiates whether model should be initialized if no console is available for input
	private boolean initializeIfNoConsole = false;
	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.sitewhere.spi.server.device.IDeviceModelInitializer#initialize(com.sitewhere
	 * .spi.device.IDeviceManagement)
	 */
	public void initialize(IDeviceManagement deviceManagementthrows SiteWhereException {
		this. = deviceManagement;
		// Use the system account for logging "created by" on created elements.
		SecurityContextHolder.getContext().setAuthentication(SiteWhereServer.getSystemAuthentication());
		// Coordinates for edges of zone.
		.add(new Location(34.10260138703638, -84.24412965774536));
		.add(new Location(34.101837372446774, -84.24243450164795));
		.add(new Location(34.101517550337825, -84.24091100692749));
		.add(new Location(34.10154953265732, -84.23856675624847));
		.add(new Location(34.10153176473365, -84.23575580120087));
		.add(new Location(34.10409030732968, -84.23689305782318));
		.add(new Location(34.104996439280704, -84.23700034618376));
		.add(new Location(34.10606246444614, -84.23700034618376));
		.add(new Location(34.107691680235604, -84.23690915107727));
		// Create device specifications.
		for (int i = 0; i < .i++) {
		}
		List<ISitesites = createSites();
		for (ISite site : sites) {
			List<DeviceAssignmentassignments = createAssignments(sitespecMap);
			for (DeviceAssignment assignment : assignments) {
				request.setElementId(assignment.getDeviceHardwareId());
				request.setRoles(new ArrayList<String>());
				SpecificationDetails info = specMap.get(assignment.getDevice().getSpecificationToken());
					heavyRequests.add(request);
else if (info.getAssignmentChoices() == ) {
					personnelRequests.add(request);
else if (info.getAssignmentChoices() == ) {
					toolsRequests.add(request);
				}
			}
			getDeviceManagement().addDeviceGroupElements(personnel.getToken(), personnelRequests);
		}
		SecurityContextHolder.getContext().setAuthentication(null);
	}

Test API calls for listing and removing group elements.

Parameters:
group
Throws:
com.sitewhere.spi.SiteWhereException
		.info("Matched " + groupElements.getResults().size() + " group elements.");
		for (IDeviceGroupElement current : groupElements.getResults()) {
			delElm.setType(current.getType());
			delElm.setElementId(current.getElementId());
			delete.add(delElm);
		}
		.info("Deleted " + deleted.size() + " group elements.");
		groupElements =
		.info("Remaining was " + groupElements.getResults().size() + " group elements.");
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see com.sitewhere.spi.server.IModelInitializer#isInitializeIfNoConsole()
	 */
	public boolean isInitializeIfNoConsole() {
	}
	public void setInitializeIfNoConsole(boolean initializeIfNoConsole) {
		this. = initializeIfNoConsole;
	}

Create device specifications.

		int index = 0;
			request.setAssetId(details.getAssetId());
			request.setName(details.getName());
			request.setToken(details.getUuid());
			// Add fields for gateway.
			if (details.getUuid().equals("75126a52-0607-4cca-b995-df40e73a707b")) {
				request.setDeviceElementSchema(schema);
else if (details.getUuid().equals()) {
				request.setDeviceElementSchema(schema);
else {
			}
			results[index] = spec;
			index++;
		}
		return results;
	}

Create a sample schema for a composite device.

Returns:
		// Create main default bus.
		DeviceUnit db1 = new DeviceUnit();
		db1.setName("Default Bus");
		db1.setPath("default");
		schema.getDeviceUnits().add(db1);
		// PCI Bus.
		DeviceUnit pci = new DeviceUnit();
		pci.setName("PCI Bus");
		pci.setPath("pci");
		DeviceSlot pci1 = new DeviceSlot();
		pci1.setName("PCI Device 1");
		pci1.setPath("pci1");
		DeviceSlot pci2 = new DeviceSlot();
		pci2.setName("PCI Device 2");
		pci2.setPath("pci2");
		pci.getDeviceSlots().add(pci1);
		pci.getDeviceSlots().add(pci2);
		db1.getDeviceUnits().add(pci);
		// Serial ports
		DeviceUnit serial = new DeviceUnit();
		serial.setName("Serial Ports");
		serial.setPath("serial");
		DeviceSlot ser1 = new DeviceSlot();
		ser1.setName("COM Port 1");
		ser1.setPath("com1");
		DeviceSlot ser2 = new DeviceSlot();
		ser2.setName("COM Port 2");
		ser2.setPath("com2");
		serial.getDeviceSlots().add(ser1);
		serial.getDeviceSlots().add(ser2);
		db1.getDeviceUnits().add(serial);
		// Create a bus with two slots.
		DeviceUnit bus1 = new DeviceUnit();
		bus1.setName("High Voltage Bus 1");
		bus1.setPath("hv1");
		DeviceSlot slot1 = new DeviceSlot();
		slot1.setName("HV Slot 1");
		slot1.setPath("slot1");
		bus1.getDeviceSlots().add(slot1);
		DeviceSlot slot2 = new DeviceSlot();
		slot2.setName("HV Slot 2");
		slot2.setPath("slot2");
		bus1.getDeviceSlots().add(slot2);
		schema.getDeviceUnits().add(bus1);
		// Create a top-level slot.
		DeviceSlot s1 = new DeviceSlot();
		s1.setName("Gateway Port 1");
		s1.setPath("gw1");
		schema.getDeviceSlots().add(s1);
		return schema;
	}

Create device commands that may be added to specifications.

		// Commands should not be available for openHAB.
			cmdPing.setName("ping");
			cmdPing.setDescription("Send a 'ping' request to the device to verify it can be reached.");
			commands.add(getDeviceManagement().createDeviceCommand(speccmdPing));
			testEvents.setName("testEvents");
			testEvents.setDescription("Send a request that results in sample events being returned.");
			commands.add(getDeviceManagement().createDeviceCommand(spectestEvents));
else {
			onOff.setName("sendOnOffCommand");
			onOff.setDescription("Send on/off command to an openHAB item.");
			onOff.getParameters().add(new CommandParameter("itemName".true));
			onOff.getParameters().add(new CommandParameter("command".true));
			commands.add(getDeviceManagement().createDeviceCommand(speconOff));
			openClose.setName("sendOpenCloseCommand");
			openClose.setDescription("Send open/close command to an openHAB item.");
			openClose.getParameters().add(new CommandParameter("itemName".true));
			openClose.getParameters().add(new CommandParameter("command".true));
			commands.add(getDeviceManagement().createDeviceCommand(specopenClose));
		}
		if (spec.getToken().equals("d2604433-e4eb-419b-97c7-88efe9b2cd41")) {
			changebg.setName("changeBackground");
			changebg.setDescription("Change background color of application.");
			changebg.getParameters().add(new CommandParameter("color".true));
			commands.add(getDeviceManagement().createDeviceCommand(specchangebg));
		}
		if (spec.getToken().equals("417b36a8-21ef-4196-a8fe-cc756f994d0b")) {
			serprtln.setName("serialPrintln");
			serprtln.setDescription("Print a messgae to the serial output.");
			serprtln.getParameters().add(new CommandParameter("message".true));
			commands.add(getDeviceManagement().createDeviceCommand(specserprtln));
		}
		if (spec.getToken().equals("7dfd6d63-5e8d-4380-be04-fc5c73801dfb")) {
			hello.setName("helloWorld");
			hello.setDescription("Request a 'hello world' response from device.");
			hello.getParameters().add(new CommandParameter("greeting".true));
			hello.getParameters().add(new CommandParameter("loud".true));
			commands.add(getDeviceManagement().createDeviceCommand(spechello));
		}
		.put(spec.getToken(), commands);
	}

Get a random device specification from the list.

Returns:
		int index = (int) Math.floor(Math.random() * .);
		return [index];
	}

Get the MeiTrack device specification.

Returns:
		for (int i = 0; i < .i++) {
			}
		}
		return null;
	}

Create example sites.

	public List<ISitecreateSites() throws SiteWhereException {
		List<ISiteresults = new ArrayList<ISite>();
		for (int x = 0; x < x++) {
			if (x == 0) {
			}
			request.setName("Construction Site " + (x + 1));
			request.setDescription("A construction site with many high-value assets that should "
"not be taken offsite. The system provides location tracking for the assets and notifies "
"administrators if any of the assets move outside of the general site area or "
"into areas where they are not allowed.");
			request.getMap().setType("mapquest");
			ISite site = getDeviceManagement().createSite(request);
			results.add(site);
			.info( + " " + request.getName());
			// Create a zone for the site.
		}
		return results;
	}

Create the construction zone.

Parameters:
site
Returns:
Throws:
com.sitewhere.spi.SiteWhereException
	public IZone createZone(ISite sitethrows SiteWhereException {
		request.setName("Construction Site");
		request.setBorderColor("#017112");
		request.setFillColor("#1db32e");
		request.setOpacity(0.4);
		IZone zone = getDeviceManagement().createZone(siterequest);
		.info( + " " + zone.getToken());
		return zone;
	}
		request.setToken(UUID.randomUUID().toString());
		request.setName("Heavy Equipment Tracking");
		request.setDescription("Device group that contains devices for tracking location of heavy equipment.");
		request.setRoles(new ArrayList<String>());
		request.getRoles().add("heavy-equipment-tracking");
		request.getRoles().add("tracking");
	}
		request.setToken(UUID.randomUUID().toString());
		request.setName("Personnel Tracking");
		request.setDescription("Device group that contains devices for tracking location of people.");
		request.setRoles(new ArrayList<String>());
		request.getRoles().add("personnel-tracking");
		request.getRoles().add("tracking");
	}
		request.setToken(UUID.randomUUID().toString());
		request.setName("Tool Tracking");
		request.setDescription("Device group that contains devices for tracking location of tools.");
		request.setRoles(new ArrayList<String>());
		request.getRoles().add("tool-tracking");
		request.getRoles().add("tracking");
	}

Create devices for a site and assign them.

Parameters:
site
Returns:
Throws:
com.sitewhere.spi.SiteWhereException
		Date before = new Date(System.currentTimeMillis() - (2 * 60 * 60 * 1000));
		helper.setIncludeDevice(true);
		for (int x = 0; x < x++) {
			// Make sure most of the entries are heavy equipment.
			if (Math.random() > 0.7) {
				specification = getMeitrackSpecification();
			}
			SpecificationDetails info = specMap.get(specification.getToken());
			// List<IDeviceCommand> commands =
			// commandsBySpecToken.get(specification.getToken());
			// Create device.
			request.setSpecificationToken(specification.getToken());
			request.setSiteToken(site.getToken());
			request.setComments(assnChoice.getDeviceDescriptionBase() + " " + (x + 1) + ".");
			// Create assignment.
			assnRequest.setAssetId(assnChoice.getAssignmentAssetId());
			assnRequest.setDeviceHardwareId(device.getHardwareId());
			Map<StringStringmetadata = new HashMap<StringString>();
			metadata.put("serialNumber", UUID.randomUUID().toString());
			assnRequest.setMetadata(metadata);
			.info( + " " + assignment.getToken());
			// Create events for assignment.
			createDeviceMeasurements(assignmentbefore);
			createDeviceLocations(assignmentbefore);
			// List<IDeviceCommandInvocation> invocations =
			// createDeviceCommandInvocations(assignment, before, commands);
			// createDeviceCommandResponses(assignment, before, invocations);
			// createDeviceStateChanges(assignment, specification, before);
			results.add(helper.convert(assignment, SiteWhere.getServer().getAssetModuleManager()));
		}
		return results;
	}

Create device measurements associated with an assignment.

Parameters:
assignment
Returns:
Throws:
com.sitewhere.spi.SiteWhereException
		long current = start.getTime();
		double temp = ;
		double fuel = 100;
		double delta = 4;
		double mult = 6;
		int measurementCount = 0;
		int alertCount = 0;
		for (int x = 0; x < x++) {
			// Simulate temperature changes.
			temp = temp + (delta + ((Math.random() * mult * 2) - mult));
			temp = Math.round(temp * 100.0) / 100.0;
			if ((temp > ) || (temp < )) {
				delta = -delta;
			}
			// Simulate fuel changes.
			fuel -= (Math.random() * 2);
			fuel = Math.round(fuel * 100.0) / 100.0;
			if (fuel < 0) {
				fuel = 0;
			}
			// Store current temperature measurement.
			mreq.addOrReplaceMeasurement("engine.temperature"temp);
			mreq.addOrReplaceMeasurement("fuel.level"fuel);
			mreq.setEventDate(new Date(current));
			results.add(getDeviceManagement().addDeviceMeasurements(assignment.getToken(), mreq));
			measurementCount++;
			// Create alerts based on current temperature.
			if (temp > ) {
				areq.setType("engine.overheat");
				areq.setEventDate(new Date(current));
				areq.setMessage("Engine temperature is at top of operating range.");
				if (temp > ) {
					areq.setMessage("Engine temperature is at a dangerous level.");
else if (temp > ) {
					areq.setMessage("Engine temperature critical. Shutting down.");
					break;
				}
				alertCount++;
			}
			current += 10000;
		}
		.info( + " " + measurementCount + " measurements. " + alertCount
" alerts.");
		return results;
	}

Create device locations in a path near the main zone.

Parameters:
assignment
start
Returns:
Throws:
com.sitewhere.spi.SiteWhereException
		long current = date.getTime();
		Point centroid = zone.getCentroid();
		// Calculate length of steps between locations based on bounding circle.
		double step = circle.getRadius() / 10;
		double cx = centroid.getX();
		double cy = centroid.getY();
		double deltaX = (Math.sqrt(Math.random()) * step * 2) - step;
		double deltaY = (Math.sqrt(Math.random()) * step * 2) - step;
		// Used to rotate deltas to turn path and stay inside polygon.
		xform.rotate(Math.toRadians(22.5));
		GeometryFactory factory = new GeometryFactory();
		for (int x = 0; x < x++) {
			boolean foundNext = false;
			// Add a little randomness to path.
			double waver = ((Math.random() * 20) - 10.0);
			waverXform.rotate(Math.toRadians(waver));
			Coordinate waverDelta = new Coordinate(deltaXdeltaY);
			waverXform.transform(waverDeltawaverDelta);
			deltaX = waverDelta.x;
			deltaY = waverDelta.y;
			while (!foundNext) {
				Coordinate start = new Coordinate(cxcy);
				Coordinate end = new Coordinate(cx + deltaXcy + deltaY);
				Coordinate[] lineCoords = { startend };
				LineString line = factory.createLineString(lineCoords);
				if (zone.contains(line)) {
					request.setLatitude(end.y);
					request.setLongitude(end.x);
					request.setElevation(0.0);
					request.setEventDate(new Date(current));
					IDeviceLocation created =
					results.add(created);
					cx = cx + deltaX;
					cy = cy + deltaY;
					foundNext = true;
else {
					// Rotate deltas and try again.
					Coordinate delta = new Coordinate(deltaXdeltaY);
					xform.transform(deltadelta);
					deltaX = delta.x;
					deltaY = delta.y;
				}
			}
			current += 30000;
		}
		.info( + " " + results.size() + " locations. ");
		return results;
	}

Create command invocations for an assignment.

Parameters:
assignment
date
commands
Returns:
Throws:
com.sitewhere.spi.SiteWhereException
			Date dateList<IDeviceCommandcommandsthrows SiteWhereException {
		long current = date.getTime();
		for (IDeviceCommand command : commands) {
			request.setCommandToken(command.getToken());
			request.setInitiatorId("system");
			request.setTargetId(assignment.getToken());
			request.setEventDate(new Date(current));
			Map<StringStringvalues = new HashMap<StringString>();
			for (ICommandParameter param : command.getParameters()) {
				values.put(param.getName(), getSampleValue(param.getType()));
			}
			request.setParameterValues(values);
			invocations.add(getDeviceManagement().addDeviceCommandInvocation(assignment.getToken(), command,
					request));
			current += 30000;
		}
		return invocations;
	}

Create command responses for each invocation.

Parameters:
assignment
date
invocations
Returns:
Throws:
com.sitewhere.spi.SiteWhereException
			Date dateList<IDeviceCommandInvocationinvocationsthrows SiteWhereException {
		long current = date.getTime();
		for (IDeviceCommandInvocation invocation : invocations) {
			request.setOriginatingEventId(invocation.getId());
			request.setResponse("ACK");
			request.setEventDate(new Date(current));
			responses.add(getDeviceManagement().addDeviceCommandResponse(assignment.getToken(), request));
			current += 30000;
		}
		return responses;
	}

Create example state change events.

Parameters:
assignment
start
Returns:
Throws:
com.sitewhere.spi.SiteWhereException
			IDeviceSpecification specificationDate startthrows SiteWhereException {
		register.setHardwareId(assignment.getDeviceHardwareId());
		register.setSpecificationToken(specification.getToken());
		register.setEventDate(start);
		stateChanges.add(getDeviceManagement().addDeviceStateChange(assignment.getToken(), register));
		return stateChanges;
	}

Get a sample value based on datatype.

Parameters:
type
Returns:
	protected String getSampleValue(ParameterType type) {
		switch (type) {
		case :
			return "true";
		case :
			return "0.0";
		case :
			return "0.0";
		case :
			return "test";
		default:
			return "0";
		}
	}

Get a random assignment from the list of allowed choices.

Parameters:
details
Returns:
		int slot = (int) Math.floor(details.getAssignmentChoices().length * Math.random());
		return details.getAssignmentChoices()[slot];
	}

Internal class for creating a device specification.

Author(s):
Derek
	private static class SpecificationDetails {
		private String assetId;
		private String name;
		private String uuid;
		public SpecificationDetails(String assetIdString nameString uuid,
				AssignmentChoice[] assignmentChoices) {
			this. = assetId;
			this. = name;
			this. = uuid;
			this. = assignmentChoices;
		}
		public String getAssetId() {
			return ;
		}
		public String getName() {
			return ;
		}
		public String getUuid() {
			return ;
		}
		}
	}

Internal class for choosing device/asset assignments that make sense.

Author(s):
Derek
	private static class AssignmentChoice {
		public AssignmentChoice(String devDescBaseString assnAssetModuleIdString assnAssetId) {
			this. = devDescBase;
			this. = assnAssetModuleId;
			this. = assnAssetId;
		}
			return ;
		}
		}
			return ;
		}
	}
	}
	protected void setDeviceManagement(IDeviceManagement deviceManagement) {
		this. = deviceManagement;
	}