Определение модели ThingWorx в Composer > Моделирование > Шаблоны вещей > Удаленные шаблоны > Присутствие вещи > Присутствие вещи: пользовательская стратегия передачи сообщений, создаваемая в Java с использованием ThingWorx Extension SDK
Присутствие вещи: пользовательская стратегия передачи сообщений, создаваемая в Java с использованием ThingWorx Extension SDK
Этот учебник не охватывает все основные принципы создания расширений ThingWorx. Он подразумевает следующее:
Вы знаете, как построить расширение ThingWorx.
У вас имеется пакет расширений SDK, v.8.4.0 или более поздней версии, который включает в себя объекты передачи сообщений.
Вы знаете, как построить расширение и импортировать его в ThingWorx Platform.
Вещь пользовательской стратегии можно создать на языке Java или на JavaScript и XML. Сначала необходимо создать шаблон вещи "Стратегия" и реализовать и переопределить метод ReportingAlgorithm. Затем можно создать вещь "Стратегия". В этом разделе объясняются шаги по созданию стратегии на Java. Сведения о создании вещи стратегии с помощью JavaScript см. в разделе Присутствие вещи: использование ThingWorx Composer для создания пользовательской версии ReportingStrategy Thing.
Создание шаблона вещи "Стратегия"
Чтобы создать пользовательскую стратегию в Java, создайте сначала шаблон вещи "Стратегия". Шаблон вещи служит базой кодов алгоритмов на основе Java. Определение класса для шаблона вещи должно быть аналогичным следующему:
@ThingworxBaseTemplateDefinition(name = "ReportingStrategy")
public class MyJavaStrategy extends ReportingStrategy {
Реализуйте и переопределите метод ReportingAlgorithm
Затем необходимо реализовать и переопределить метод ReportingAlgorithm. Этот метод содержит много аннотаций, необходимых для правильного функционирования. Простейшее решение для обеспечения правильной реализации заключается в копировании следующего кода:
@Override
@ThingworxServiceDefinition(name = ReportingConstants.REPORTING_ALGORITHM_SERVICE_NAME, isAllowOverride = true,
description = "Evaluates a Thing to determine if it is Present")
@ThingworxServiceResult(name = CommonPropertyNames.PROP_RESULT, baseType = "BOOLEAN",
description = "Whether the parameters describe a Device that is Reporting normally")
public Boolean ReportingAlgorithm(
@ThingworxServiceParameter(
name = ReportingConstants.EVENT_NAME,
description = "Name of the event",
baseType = "STRING" ) String eventName,
@ThingworxServiceParameter(
name = ReportingConstants.EVENT_TIME,
description = "Time event is triggered",
baseType = "DATETIME" ) DateTime eventTime,
@ThingworxServiceParameter(
name = ReportingConstants.SOURCE,
description = "Name of Thing that triggered event",
baseType = "STRING" ) String source,
@ThingworxServiceParameter(
name = ReportingConstants.SOURCE_PROPERTY,
description = "Soure property",
baseType = "STRING" ) String sourceProperty,
@ThingworxServiceParameter(
name = ReportingConstants.EVENT_DATA,
description = "Parameters necessary for the algorithm to determine if a Thing is reporting",
baseType = "INFOTABLE") InfoTable eventData) {
// specifically boolean primitive; this method should never return null
boolean result = false;

// TODO: Custom Strategy implementation here

return result;
}
Пример пользовательского шаблона вещи "Стратегия"
Шаблон вещи пользовательской стратегии должен быть похож на следующий пример. В этом примере в соответствии с пользовательской стратегией вещь помечается как присутствующая, если она не соединена, и как не присутствующая, если она соединена.

import org.joda.time.DateTime;
import org.slf4j.Logger;

import com.thingworx.logging.LogUtilities;
import com.thingworx.metadata.annotations.ThingworxBaseTemplateDefinition;
import com.thingworx.metadata.annotations.ThingworxServiceDefinition;
import com.thingworx.metadata.annotations.ThingworxServiceParameter;
import com.thingworx.metadata.annotations.ThingworxServiceResult;
import com.thingworx.things.connected.reportable.ReportingConstants;
import com.thingworx.things.connected.reportable.ReportingStrategy;
import com.thingworx.types.InfoTable;
import com.thingworx.types.constants.CommonPropertyNames;

@ThingworxBaseTemplateDefinition(name = "ReportingStrategy")
public class MyJavaStrategy extends ReportingStrategy {

private static final Logger logger =
LogUtilities.getInstance().getApplicationLogger(MyJavaStrategy.class);

@Override
@ThingworxServiceDefinition(name = ReportingConstants.REPORTING_ALGORITHM_SERVICE_NAME,
isAllowOverride = true,
description = "Evaluates a Thing to determine if it is Present")
@ThingworxServiceResult(name = CommonPropertyNames.PROP_RESULT, baseType = "BOOLEAN",
description = "Whether the parameters describe a Device that is Reporting normally")
public Boolean ReportingAlgorithm(
@ThingworxServiceParameter(
name = ReportingConstants.EVENT_NAME,
description = "Name of the event",
baseType = "STRING" ) String eventName,
@ThingworxServiceParameter(
name = ReportingConstants.EVENT_TIME,
description = "Time event is triggered",
baseType = "DATETIME" ) DateTime eventTime,
@ThingworxServiceParameter(
name = ReportingConstants.SOURCE,
description = "Name of Thing that triggered event",
baseType = "STRING" ) String source,
@ThingworxServiceParameter(
name = ReportingConstants.SOURCE_PROPERTY,
description = "Soure property",
baseType = "STRING" ) String sourceProperty,
@ThingworxServiceParameter(
name = ReportingConstants.EVENT_DATA,
description = "Parameters necessary for the algorithm to determine if a Thing is reporting",
baseType = "INFOTABLE") InfoTable eventData) {
// specifically boolean primitive; this method should never return null
boolean result;
try {
boolean isBound = (Boolean) eventData.getFirstRow().getValue(ReportingConstants.PROP_ISBOUND);
result = !isBound;
logger.info("Custom strategy has is bound [" + isBound + "].
Setting reporting to [" + result + "]");
} catch (Exception e) {
logger.error("Caught exception while evaluating reporting algorithm.
Marking as not reporting");
result = false;
}
return result;
}

}
Создание вещи "Стратегия"
Вещь стратегии расширяет пользовательский шаблон стратегии и позволяет задавать его в качестве алгоритма передачи сообщений в таблице конфигурации отчетности для удаленной сущности.
Чтобы создать вещь, в проекте должен существовать путь к папке сущностей следующего формата: <Корневая_папка_проекта>/Entites/Things, а для вещей должно существовать следующее правило именования: Things_ThingName.xml, где ThingName - имя пользовательской вещи.
Для этого примера будет использоваться имя: CustomStrategyJava, поэтому имя файла имеет вид: Things_CustomStrategyJava.xml, а его содержимое описано ниже. Необходимо отредактировать строки 14, 19 и 23 в зависимости от используемых вами имен ThingPackage, ThingName и ThingTemplate соответственно.
* 
После копирования приведенных ниже строк в редактор IDE или XML будут видны правильные номера строк.
<?xml version="1.0" encoding="UTF-8"?>
<Entities
<Things>
<Thing
effectiveThingPackage="MyStrategyPackage"
enabled="true"
name="CustomStrategyJava"
published="false"
thingTemplate="MyJavaStrategy"
</Thing>
</Things>
</Entities>
Выполнение стратегии
Начиная с версии ThingWorx 8.4.0 переоценка состояния isReporting удаленной вещи будет производиться при каждой привязке или отмене привязки вещи к ThingWorx Platform. Это состояние также может быть перерассчитано в любое время (например, с помощью таймера) с выполнением сервиса EvaluateReporting, доступного в удаленной вещи.
Было ли это полезно?