Community Tip - Want the oppurtunity to discuss enhancements to PTC products? Join a working group! X
This code snippet shows how to add an existing Device to an existing DeviceGroup using a custom Groovy script executed by the Scripto web service. To call the script create a URL of the following form:
http://<HOST>/services/v1/rest/Scripto/execute/addDeviceToDeviceGroup?us...
NOTE: Text in angled brackets (< >) indicates a variable.
Alternatively, this script can be called by an Expression Rule using the following form:
If: Registration.first
Then: ExecuteCustomObject("addDeviceToDeviceGroup","<ASSET_ID>","<GROUP_NAME>")
It is worth noting that it is important when creating the Groovy script that the parameters be created in the order of the parameter list.
import net.sf.json.JSONObject
import com.axeda.drm.sdk.device.DeviceGroupFinder
import com.axeda.drm.sdk.device.DeviceGroup
import com.axeda.drm.sdk.Context
import com.axeda.common.sdk.id.Identifier
import com.axeda.drm.sdk.device.DeviceFinder
def response = [:], status
try {
if (parameters.assetId == null) { throw new IllegalArgumentException("parameter 'assetId' was not provided.")}
if (parameters.groupName == null) { throw new IllegalArgumentException("parameter 'groupName was not provided.")}
final def CONTEXT = Context.create(parameters.username)
def dgf = new DeviceGroupFinder(CONTEXT)
dgf.setName(parameters.groupName)
def group = dgf.find()
if (group == null) {
logger.error "could not retrieve group with name of '${parameters.groupName}'"
throw new Exception("could not retrieve group with id of '${parameters.groupName}'")
}
def df = new DeviceFinder(CONTEXT)
df.setId(new Identifier(parameters.assetId))
def device = df.find()
if (device == null) {
logger.error "could not retrieve asset with id of '${parameters.assetId}'"
throw new Exception("could not retrieve asset with id of '${parameters.assetId}'")
}
group.addDevice(device)
group.store()
// do a check to make sure the device is associated with the group.
group = dgf.find()
def devices = group.getDevices()
status = devices.contains(device) ? "success" : "failure"
// prepare the response.
response = [parameters: parameters, status: status]
} catch (def e) {
logger.error e.getMessage()
response = [faultcode: e.getCause(), faultstring: e.getMessage()]
}
return ['Content-Type': 'application/json', 'Content': JSONObject.fromObject(response).toString(2)];