public Builder(IDeviceSpecification api) { request.setToken(api.getToken()); request.setName(api.getName()); request.setAssetModuleId(api.getAssetModuleId()); request.setAssetId(api.getAssetId()); request.setContainerPolicy(api.getContainerPolicy()); request.setDeviceElementSchema((DeviceElementSchema) api.getDeviceElementSchema()); request.setMetadata(new HashMap<String, String>()); request.getMetadata().putAll(api.getMetadata()); }
@Override public URI getDeviceSpecificationIdentifier(IDeviceSpecification specification) throws SiteWhereException { return createUri(SITEWHERE_PROTOCOL + "specification/" + specification.getToken()); }
} else { result.setSpecificationToken(source.getSpecificationToken()); HardwareAsset asset = (HardwareAsset) manager.getAssetById(spec.getAssetModuleId(), spec.getAssetId()); if (asset != null) { result.setAssetId(asset.getId());
IDeviceUnit unit = specification.getDeviceElementSchema(); if (unit == null) { return null;
/** * Get the specification identifier. * * @param command * @return */ protected static String getSpecificationIdentifier(IDeviceSpecification specification) { UUID uuid = UUID.fromString(specification.getToken()); long low = uuid.getLeastSignificantBits(); long high = uuid.getMostSignificantBits(); ByteBuffer buffer = ByteBuffer.allocate(16); buffer.putLong(low); buffer.putLong(high); return "Spec_" + Base58.encode(buffer.array()); }
+ site.getName() + "</a>"; html += " with specification <a href=\"" + relativePath + "/specifications/" + specification.getToken() + ".html\">" + specification.getName() + "</a>"; if (!StringUtils.isEmpty(criteria.getGroupToken())) { IDeviceGroup group = devices.getDeviceGroup(criteria.getGroupToken());
/** * Generate the '.proto' information. * * @param specification * @param commands * @param buffer * @throws SiteWhereException */ protected static void generateProto(IDeviceSpecification specification, List<IDeviceCommand> commands, StringBuffer buffer) throws SiteWhereException { int indent = 0; SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); String specName = ProtobufNaming.getSpecificationIdentifier(specification); println("option optimize_for = LITE_RUNTIME;", indent, buffer); newline(buffer); println("// Google Protocol Buffer for '" + specification.getName() + "'.", indent, buffer); println("// Generated on " + formatter.format(new Date()), indent, buffer); println("message " + specName + " {", indent, buffer); newline(buffer); addCommandsEnum(specification, commands, buffer, indent + 1); newline(buffer); addHeader(buffer, indent + 1); newline(buffer); int index = 2; for (IDeviceCommand command : commands) { addCommand(command, index++, buffer, indent + 1); newline(buffer); } println("}", indent, buffer); }
/** * Copy information from SPI into Mongo DBObject. * * @param source * @param target */ public static void toDocument(IDeviceSpecification source, Document target) { target.append(PROP_TOKEN, source.getToken()); target.append(PROP_NAME, source.getName()); target.append(PROP_ASSET_MODULE_ID, source.getAssetModuleId()); target.append(PROP_ASSET_ID, source.getAssetId()); target.append(PROP_CONTAINER_POLICY, source.getContainerPolicy().name()); MongoSiteWhereEntity.toDocument(source, target); MongoMetadataProvider.toDocument(source, target); // Marshal device element schema as JSON. if (source.getDeviceElementSchema() != null) { ObjectMapper mapper = new ObjectMapper(); try { byte[] schemaJson = mapper.writeValueAsBytes(source.getDeviceElementSchema()); target.append(PROP_DEVICE_ELEMENT_SCHEMA, new Binary(schemaJson)); } catch (JsonProcessingException e) { LOGGER.error("Unable to marshal device element schema for MongoDB persistence.", e); } } }
@Override public boolean appliesTo(IDeviceContext<T> criteria) { if (criteria.getDeviceSpecification().getToken().equals(getDeviceSpecificationToken())) { return true; } return false; }
@Override public byte[] encodeDeviceSpecification(IDeviceSpecification spec) throws SiteWhereException { ProtobufMarshaler.DeviceSpecification.Builder builder = ProtobufMarshaler.DeviceSpecification.newBuilder(); builder.setToken(spec.getToken()); builder.setName(spec.getName()); builder.setAssetModuleId(spec.getAssetModuleId()); builder.setAssetId(spec.getAssetId()); builder.setContainerPolicy(spec.getContainerPolicy().name()); if (spec.getDeviceElementSchema() != null) { builder.setDeviceElementSchema(encodeDeviceElementSchema(spec.getDeviceElementSchema())); } builder.setEntityData(createEntityData(spec)); try { ByteArrayOutputStream out = new ByteArrayOutputStream(); builder.build().writeTo(out); return out.toByteArray(); } catch (IOException e) { throw new SiteWhereException("Unable to marshal device specification.", e); } }
/** * Generate a '.proto' file for a specification. * * @param specification * @return * @throws SiteWhereException */ public static String getProtoForSpecification(IDeviceSpecification specification, ITenant tenant) throws SiteWhereException { StringBuffer buffer = new StringBuffer(); List<IDeviceCommand> commands = SiteWhere.getServer().getDeviceManagement(tenant) .listDeviceCommands(specification.getToken(), false); generateProto(specification, commands, buffer); return buffer.toString(); }
/** * Convert a device specification for marshaling. * * @param source * @param manager * @return * @throws SiteWhereException */ public DeviceSpecification convert(IDeviceSpecification source, IAssetModuleManager manager) throws SiteWhereException { DeviceSpecification spec = new DeviceSpecification(); MetadataProviderEntity.copy(source, spec); spec.setToken(source.getToken()); spec.setName(source.getName()); HardwareAsset asset = (HardwareAsset) manager.getAssetById(source.getAssetModuleId(), source.getAssetId()); if (asset == null) { LOGGER.warn("Device specification has reference to non-existent asset."); throw new SiteWhereSystemException(ErrorCode.InvalidAssetReferenceId, ErrorLevel.ERROR); } spec.setAssetModuleId(source.getAssetModuleId()); spec.setAssetId(asset.getId()); spec.setAssetName(asset.getName()); spec.setAssetImageUrl(asset.getImageUrl()); if (isIncludeAsset()) { spec.setAsset(asset); } spec.setContainerPolicy(source.getContainerPolicy()); spec.setDeviceElementSchema((DeviceElementSchema) source.getDeviceElementSchema()); return spec; }
/** * Get a device specification by unique token. * * @param hardwareId * @return */ @RequestMapping(value = "/{token}/spec.proto", method = RequestMethod.GET) @ResponseBody @ApiOperation(value = "Get specification GPB file by unique token") @Secured({ SiteWhereRoles.REST }) @Documented() public ResponseEntity<byte[]> getDeviceSpecificationProtoFileByToken( @ApiParam(value = "Token", required = true) @PathVariable String token, HttpServletRequest servletRequest, HttpServletResponse response) throws SiteWhereException { Tracer.start(TracerCategory.RestApiCall, "getDeviceSpecificationProtoFileByToken", LOGGER); try { IDeviceSpecification specification = assertDeviceSpecificationByToken(token, servletRequest); String proto = SpecificationProtoBuilder.getProtoForSpecification(specification, getTenant(servletRequest)); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.set("Content-Disposition", "attachment; filename=Spec_" + specification.getToken() + ".proto"); return new ResponseEntity<byte[]>(proto.getBytes(), headers, HttpStatus.OK); } finally { Tracer.stop(LOGGER); } }
@Override public IDeviceCommand createDeviceCommand(IDeviceSpecification spec, IDeviceCommandCreateRequest request) throws SiteWhereException { // Note: This allows duplicates if duplicate was marked deleted. List<IDeviceCommand> existing = listDeviceCommands(spec.getToken(), false); // Use common logic so all backend implementations work the same. String uuid = ((request.getToken() != null) ? request.getToken() : UUID.randomUUID().toString()); DeviceCommand command = SiteWherePersistence.deviceCommandCreateLogic(spec, request, uuid, existing); MongoCollection<Document> commands = getMongoClient().getDeviceCommandsCollection(getTenant()); Document created = MongoDeviceCommand.toDocument(command); MongoPersistence.insert(commands, created, ErrorCode.DeviceCommandExists); return MongoDeviceCommand.fromDocument(created); }
/** * Create a new device command for an existing device specification. * * @param context * @param spec * @param request * @return * @throws SiteWhereException */ public static IDeviceCommand createDeviceCommand(IHBaseContext context, IDeviceSpecification spec, IDeviceCommandCreateRequest request) throws SiteWhereException { Long specId = context.getDeviceIdManager().getSpecificationKeys().getValue(spec.getToken()); if (specId == null) { throw new SiteWhereSystemException(ErrorCode.InvalidDeviceSpecificationToken, ErrorLevel.ERROR); } String uuid = ((request.getToken() != null) ? request.getToken() : UUID.randomUUID().toString()); // Use common logic so all backend implementations work the same. List<IDeviceCommand> existing = listDeviceCommands(context, spec.getToken(), false); DeviceCommand command = SiteWherePersistence.deviceCommandCreateLogic(spec, request, uuid, existing); // Create unique row for new device. Long nextId = HBaseDeviceSpecification.allocateNextCommandId(context, specId); byte[] rowkey = HBaseDeviceSpecification.getDeviceCommandRowKey(specId, nextId); context.getDeviceIdManager().getCommandKeys().create(uuid, rowkey); return putDeviceCommandPayload(context, command); }
/** * Common logic for creating new device command and populating it from * request. * * @param request * @param token * @return * @throws SiteWhereException */ public static DeviceCommand deviceCommandCreateLogic(IDeviceSpecification spec, IDeviceCommandCreateRequest request, String token, List<IDeviceCommand> existing) throws SiteWhereException { DeviceCommand command = new DeviceCommand(); // Token is required. require(token); command.setToken(token); // Name is required. require(request.getName()); command.setName(request.getName()); command.setSpecificationToken(spec.getToken()); command.setNamespace(request.getNamespace()); command.setDescription(request.getDescription()); command.getParameters().addAll(request.getParameters()); checkDuplicateCommand(command, existing); MetadataProvider.copy(request.getMetadata(), command); SiteWherePersistence.initializeEntityMetadata(command); return command; }
/** * Create the message for a specification. * * @param specification * @param tenant * @return * @throws SiteWhereException */ public static DescriptorProtos.DescriptorProto createSpecificationMessage(IDeviceSpecification specification, ITenant tenant) throws SiteWhereException { List<IDeviceCommand> commands = SiteWhere.getServer().getDeviceManagement(tenant) .listDeviceCommands(specification.getToken(), false); DescriptorProtos.DescriptorProto.Builder builder = DescriptorProtos.DescriptorProto.newBuilder(); builder.setName(ProtobufNaming.getSpecificationIdentifier(specification)); builder.addEnumType(createCommandsEnum(commands)); builder.addNestedType(createUuidMessage()); builder.addNestedType(createHeaderMessage()); for (IDeviceCommand command : commands) { builder.addNestedType(createCommandMessage(command)).build(); } return builder.build(); }