Search in sources :

Example 31 with DataPointRT

use of com.serotonin.m2m2.rt.dataImage.DataPointRT in project ma-modules-public by infiniteautomation.

the class MBusDataSourceRT method doPoll.

@Override
protected synchronized void doPoll(long time) {
    boolean pointError = false;
    final List<UserDataResponse> udrs = new LinkedList<>();
    if (openConnection()) {
        try {
            for (DataPointRT point : dataPoints) {
                final MBusPointLocatorRT locatorRT = point.getPointLocator();
                final MBusPointLocatorVO locatorVo = locatorRT.getVo();
                UserDataResponse udr = getUdr(udrs, locatorVo);
                if (udr == null) {
                    if (locatorVo.isPrimaryAddressing()) {
                        udr = master.readResponse(locatorVo.getAddress());
                    } else {
                        udr = master.readResponseBySecondary(MBusUtils.int2Bcd(locatorVo.getIdentNumber()), locatorVo.getManufacturer(), locatorVo.getVersion(), locatorVo.getMedium());
                    }
                    if (udr == null) {
                        // insert empty UDR to prevent rurter tries in this polling round
                        locatorRT.needCheckDifAndVif = true;
                        udr = new UserDataResponse();
                        udr.setIdentNumber(locatorVo.getIdentNumber());
                        udr.setMedium(locatorVo.getMedium());
                        udr.setManufacturer(locatorVo.getManufacturer());
                        udr.setVersion(locatorVo.getVersion());
                        udrs.add(udr);
                        raiseEvent(POINT_READ_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.exception2", locatorVo.getDeviceName(), "Can't read device"));
                        pointError = true;
                    } else {
                        udrs.add(udr);
                    }
                }
                try {
                    if ((locatorVo.getDbIndex() == -1) || locatorRT.needCheckDifAndVif) {
                        int[] idx = findDataBlocks(udr, locatorVo);
                        switch(idx.length) {
                            case 0:
                                LOG.fatal("DataBlock not found: " + locatorVo.toString());
                                LOG.fatal(udr.toString());
                                raiseEvent(POINT_READ_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.exception2", locatorVo.toString() + "Can't find datablock"));
                                pointError = true;
                                return;
                            case 1:
                                if (locatorVo.getDbIndex() == idx[0]) {
                                    locatorRT.needCheckDifAndVif = false;
                                } else if (locatorVo.getDbIndex() == -1) {
                                    LOG.info("Set DB Index: " + locatorVo.toString());
                                    locatorVo.setDbIndex(idx[0]);
                                    locatorRT.needCheckDifAndVif = false;
                                } else {
                                    LOG.fatal("Index changed of datablock: " + locatorVo.toString());
                                    LOG.fatal(udr.toString());
                                    raiseEvent(POINT_READ_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.exception2", locatorVo.toString() + "Index changed of datablock Please maually correct the dbIndex"));
                                    return;
                                }
                                break;
                            default:
                                if (locatorVo.getDbIndex() == -1) {
                                    LOG.fatal("too many dataBlocks found: " + locatorVo.toString());
                                    LOG.fatal(udr.toString());
                                    raiseEvent(POINT_READ_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.exception2", locatorVo.toString() + "Found more then one datablock! Please specify dbIndex manually!"));
                                    return;
                                } else {
                                    for (int i : idx) {
                                        if (i == locatorVo.getDbIndex()) {
                                            locatorRT.needCheckDifAndVif = false;
                                            break;
                                        }
                                    }
                                    if (locatorRT.needCheckDifAndVif) {
                                        LOG.fatal("Matching dataBlock not found: " + locatorVo.toString());
                                        LOG.fatal(udr.toString());
                                        raiseEvent(POINT_READ_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.exception2", locatorVo.toString() + "Can't find matching datablock! Please specify dbIndex manually!"));
                                        pointError = true;
                                        return;
                                    }
                                }
                        }
                    }
                    final DataBlock db = udr.getDataBlock(locatorVo.getDbIndex());
                    pointError = setValue(db, pointError, time, point, locatorRT, locatorVo);
                } catch (IndexOutOfBoundsException ex) {
                    // Handle if datablock is not there...
                    raiseEvent(POINT_READ_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.exception2", point.getVO().getExtendedName(), "No Data"));
                    pointError = true;
                }
            }
            if (!pointError) {
                returnToNormal(POINT_READ_EXCEPTION_EVENT, time);
            }
            returnToNormal(DATA_SOURCE_EXCEPTION_EVENT, time);
        } catch (InterruptedException ex) {
            LOG.error("doPoll() interrupted", ex);
            raiseEvent(DATA_SOURCE_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.exception2", ex.getMessage(), "doPoll() Interrupted"));
        } catch (IOException ex) {
            LOG.error("doPoll() IO Ex", ex);
            raiseEvent(DATA_SOURCE_EXCEPTION_EVENT, System.currentTimeMillis(), true, new TranslatableMessage("event.exception2", ex.getMessage(), "doPoll() IO Ex"));
        } finally {
            closeConnection();
        }
    }
}
Also used : UserDataResponse(net.sf.mbus4j.dataframes.UserDataResponse) IOException(java.io.IOException) LinkedList(java.util.LinkedList) RealDataBlock(net.sf.mbus4j.dataframes.datablocks.RealDataBlock) StringDataBlock(net.sf.mbus4j.dataframes.datablocks.StringDataBlock) BigDecimalDataBlock(net.sf.mbus4j.dataframes.datablocks.BigDecimalDataBlock) DataBlock(net.sf.mbus4j.dataframes.datablocks.DataBlock) ByteDataBlock(net.sf.mbus4j.dataframes.datablocks.ByteDataBlock) IntegerDataBlock(net.sf.mbus4j.dataframes.datablocks.IntegerDataBlock) LongDataBlock(net.sf.mbus4j.dataframes.datablocks.LongDataBlock) ShortDataBlock(net.sf.mbus4j.dataframes.datablocks.ShortDataBlock) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 32 with DataPointRT

use of com.serotonin.m2m2.rt.dataImage.DataPointRT in project ma-modules-public by infiniteautomation.

the class PointValueRestController method getLatestPointValues.

/**
 * Get the latest point values for a point
 *
 * @param xid
 * @param limit
 * @return
 */
@ApiOperation(value = "Get Latest Point Values Directly from the Runtime Manager, this makes Cached and Intra-Interval data available.", notes = "Default limit 100, time descending order, Default to return cached data. For the most efficient use of this endpoint " + " the data point's default cache size should be the size that you will typically query the latest values of.")
@RequestMapping(method = RequestMethod.GET, value = "/{xid}/latest", produces = { "application/json", "text/csv" })
public ResponseEntity<List<RecentPointValueTimeModel>> getLatestPointValues(HttpServletRequest request, @ApiParam(value = "Point xid", required = true, allowMultiple = false) @PathVariable String xid, @ApiParam(value = "Return rendered value as String", required = false, defaultValue = "false", allowMultiple = false) @RequestParam(required = false, defaultValue = "false") boolean useRendered, @ApiParam(value = "Return converted value using displayed unit", required = false, defaultValue = "false", allowMultiple = false) @RequestParam(required = false, defaultValue = "false") boolean unitConversion, @ApiParam(value = "Limit results", allowMultiple = false, defaultValue = "100") @RequestParam(value = "limit", defaultValue = "100") int limit, @ApiParam(value = "Return cached data?", allowMultiple = false, defaultValue = "true") @RequestParam(value = "useCache", defaultValue = "true") boolean useCache) {
    RestProcessResult<List<RecentPointValueTimeModel>> result = new RestProcessResult<List<RecentPointValueTimeModel>>(HttpStatus.OK);
    User user = this.checkUser(request, result);
    if (result.isOk()) {
        DataPointVO vo = DataPointDao.instance.getByXid(xid);
        if (vo == null) {
            result.addRestMessage(getDoesNotExistMessage());
            return result.createResponseEntity();
        }
        try {
            if (Permissions.hasDataPointReadPermission(user, vo)) {
                // Check to see if we can convert (Must be a Numeric Value)
                if (unitConversion && (vo.getPointLocator().getDataTypeId() != DataTypes.NUMERIC)) {
                    result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "Can't convert non-numeric types."));
                    return result.createResponseEntity();
                }
                // If we are an image type we should build the URLS
                UriComponentsBuilder imageServletBuilder = UriComponentsBuilder.fromPath("/imageValue/hst{ts}_{id}.jpg");
                List<RecentPointValueTimeModel> models;
                if (useCache) {
                    // In an effort not to expand the PointValueCache we avoid the
                    // PointValueFacade
                    DataPointRT rt = Common.runtimeManager.getDataPoint(vo.getId());
                    if (rt != null) {
                        List<PointValueTime> cache = rt.getCacheCopy();
                        if (limit < cache.size()) {
                            List<PointValueTime> pvts = cache.subList(0, limit);
                            models = new ArrayList<>(limit);
                            for (PointValueTime pvt : pvts) models.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, true));
                        } else {
                            // We need to merge 2 lists
                            List<PointValueTime> disk = Common.databaseProxy.newPointValueDao().getLatestPointValues(vo.getId(), limit);
                            Set<RecentPointValueTimeModel> all = new HashSet<RecentPointValueTimeModel>(limit);
                            for (PointValueTime pvt : cache) all.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, true));
                            for (PointValueTime pvt : disk) {
                                if (all.size() >= limit)
                                    break;
                                else
                                    all.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, false));
                            }
                            models = new ArrayList<>(all);
                            // Override the comparison method
                            Collections.sort(models, new Comparator<RecentPointValueTimeModel>() {

                                // Compare such that data sets are returned in time
                                // descending order
                                // which turns out is opposite of compare to method for
                                // PointValueTime objects
                                @Override
                                public int compare(RecentPointValueTimeModel o1, RecentPointValueTimeModel o2) {
                                    if (o1.getTimestamp() < o2.getTimestamp())
                                        return 1;
                                    if (o1.getTimestamp() > o2.getTimestamp())
                                        return -1;
                                    return 0;
                                }
                            });
                        }
                    } else {
                        List<PointValueTime> pvts = Common.databaseProxy.newPointValueDao().getLatestPointValues(vo.getId(), limit);
                        models = new ArrayList<>(limit);
                        for (PointValueTime pvt : pvts) models.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, false));
                    }
                } else {
                    models = new ArrayList<>(limit);
                    List<PointValueTime> pvts = Common.databaseProxy.newPointValueDao().getLatestPointValues(vo.getId(), limit);
                    for (PointValueTime pvt : pvts) models.add(createRecentPointValueTimeModel(vo, pvt, imageServletBuilder, useRendered, unitConversion, false));
                }
                return result.createResponseEntity(models);
            } else {
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            }
        } catch (PermissionException e) {
            LOG.error(e.getMessage(), e);
            result.addRestMessage(getUnauthorizedMessage());
            return result.createResponseEntity();
        }
    } else {
        return result.createResponseEntity();
    }
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) User(com.serotonin.m2m2.vo.User) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) RecentPointValueTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.RecentPointValueTimeModel) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) ServletUriComponentsBuilder(org.springframework.web.servlet.support.ServletUriComponentsBuilder) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) AnnotatedPointValueTime(com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) List(java.util.List) ArrayList(java.util.ArrayList) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) HashSet(java.util.HashSet) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 33 with DataPointRT

use of com.serotonin.m2m2.rt.dataImage.DataPointRT in project ma-modules-public by infiniteautomation.

the class RuntimeManagerRestController method forceRefreshDataPoint.

@ApiOperation(value = "Force Refresh a data point", notes = "Not all data sources implement this feature", response = Void.class)
@RequestMapping(method = RequestMethod.PUT, value = "/force-refresh/{xid}")
public ResponseEntity<Void> forceRefreshDataPoint(@ApiParam(value = "Valid Data Point XID", required = true, allowMultiple = false) @PathVariable String xid, HttpServletRequest request) {
    RestProcessResult<Void> result = new RestProcessResult<Void>(HttpStatus.OK);
    try {
        User user = this.checkUser(request, result);
        if (result.isOk()) {
            if (xid == null) {
                result.addRestMessage(getDoesNotExistMessage());
                return result.createResponseEntity();
            }
            DataPointVO vo = DataPointDao.instance.getByXid(xid);
            if (vo == null) {
                result.addRestMessage(getDoesNotExistMessage());
                return result.createResponseEntity();
            }
            try {
                if (!Permissions.hasDataPointReadPermission(user, vo)) {
                    LOG.warn("User " + user.getUsername() + " attempted to refesh data point  with xid: " + vo.getXid() + " without read permission");
                    result.addRestMessage(getUnauthorizedMessage());
                    return result.createResponseEntity();
                }
            } catch (PermissionException e) {
                LOG.warn("User " + user.getUsername() + " attempted to refesh data point with xid: " + vo.getXid() + " without read permission");
                result.addRestMessage(getUnauthorizedMessage());
                return result.createResponseEntity();
            }
            DataPointRT rt = Common.runtimeManager.getDataPoint(vo.getId());
            if (rt == null) {
                result.addRestMessage(getPointNotEnabledMessage(xid));
                return result.createResponseEntity();
            }
            Common.runtimeManager.forcePointRead(vo.getId());
        }
    } catch (Exception e) {
        result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
    }
    return result.createResponseEntity();
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) User(com.serotonin.m2m2.vo.User) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) GenericRestException(com.infiniteautomation.mango.rest.v2.exception.GenericRestException) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) ApiOperation(com.wordnik.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 34 with DataPointRT

use of com.serotonin.m2m2.rt.dataImage.DataPointRT in project ma-modules-public by infiniteautomation.

the class PointLinkRT method execute.

private void execute(PointValueTime newValue) {
    // Bail out if already running a point link operation
    synchronized (ready) {
        if (!ready) {
            SystemEventType.raiseEvent(alreadyRunningEvent, newValue.getTime(), true, new TranslatableMessage("event.pointLink.duplicateRuns"));
            return;
        } else {
            // Stop anyone else from using this
            ready = false;
            SystemEventType.returnToNormal(alreadyRunningEvent, System.currentTimeMillis());
        }
    }
    // Propagate the update to the target point. Validate that the target point is available.
    DataPointRT targetPoint = Common.runtimeManager.getDataPoint(vo.getTargetPointId());
    if (targetPoint == null) {
        raiseFailureEvent(newValue.getTime(), new TranslatableMessage("event.pointLink.targetUnavailable"));
        ready = true;
        return;
    }
    if (!targetPoint.getPointLocator().isSettable()) {
        raiseFailureEvent(newValue.getTime(), new TranslatableMessage("event.pointLink.targetNotSettable"));
        ready = true;
        return;
    }
    int targetDataType = targetPoint.getVO().getPointLocator().getDataTypeId();
    if (!StringUtils.isBlank(vo.getScript())) {
        Map<String, IDataPointValueSource> context = new HashMap<String, IDataPointValueSource>();
        context.put(CONTEXT_SOURCE_VAR_NAME, Common.runtimeManager.getDataPoint(vo.getSourcePointId()));
        context.put(CONTEXT_TARGET_VAR_NAME, Common.runtimeManager.getDataPoint(vo.getTargetPointId()));
        try {
            if (!compiled) {
                compiledScript = CompiledScriptExecutor.compile(vo.getScript());
                compiled = true;
            }
            PointValueTime pvt = CompiledScriptExecutor.execute(compiledScript, context, null, newValue.getTime(), targetDataType, newValue.getTime(), vo.getScriptPermissions(), new PrintWriter(new NullWriter()), scriptLog, setCallback, importExclusions, false);
            if (pvt.getValue() == null) {
                raiseFailureEvent(newValue.getTime(), new TranslatableMessage("event.pointLink.nullResult"));
                ready = true;
                return;
            } else if (pvt.getValue() == CompiledScriptExecutor.UNCHANGED) {
                ready = true;
                return;
            }
            newValue = pvt;
        } catch (ScriptException e) {
            raiseFailureEvent(newValue.getTime(), new TranslatableMessage("pointLinks.validate.scriptError", e.getMessage()));
            ready = true;
            return;
        } catch (ScriptPermissionsException e) {
            raiseFailureEvent(newValue.getTime(), e.getTranslatableMessage());
            ready = true;
            return;
        } catch (ResultTypeException e) {
            raiseFailureEvent(newValue.getTime(), e.getTranslatableMessage());
            ready = true;
            return;
        }
    }
    if (DataTypes.getDataType(newValue.getValue()) != targetDataType) {
        raiseFailureEvent(newValue.getTime(), new TranslatableMessage("event.pointLink.convertError"));
        ready = true;
        return;
    }
    // Queue a work item to perform the update.
    Common.backgroundProcessing.addWorkItem(new PointLinkSetPointWorkItem(vo.getTargetPointId(), newValue, this));
    returnToNormal();
}
Also used : HashMap(java.util.HashMap) NullWriter(org.apache.commons.io.output.NullWriter) ScriptException(javax.script.ScriptException) ResultTypeException(com.serotonin.m2m2.rt.script.ResultTypeException) ScriptPermissionsException(com.serotonin.m2m2.rt.script.ScriptPermissionsException) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) IDataPointValueSource(com.serotonin.m2m2.rt.dataImage.IDataPointValueSource) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) PrintWriter(java.io.PrintWriter)

Example 35 with DataPointRT

use of com.serotonin.m2m2.rt.dataImage.DataPointRT in project ma-modules-public by infiniteautomation.

the class SerialDataSourceTestData method getCustomPoint.

public static DataPointRT getCustomPoint(String name, String xid, String valueRegex, int valueIndex, String pointIdentifier, DataSourceVO<?> ds) {
    DataPointVO vo = new DataPointVO();
    vo.setName(name);
    vo.setXid(xid);
    vo.setId(currentId++);
    SerialPointLocatorVO plVo = new SerialPointLocatorVO();
    plVo.setDataTypeId(DataTypes.ALPHANUMERIC);
    plVo.setValueRegex(valueRegex);
    plVo.setValueIndex(valueIndex);
    plVo.setPointIdentifier(pointIdentifier);
    vo.setPointLocator(plVo);
    return new DataPointRT(vo, plVo.createRuntime(), ds, null, null);
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) DataPointRT(com.serotonin.m2m2.rt.dataImage.DataPointRT) SerialPointLocatorVO(com.infiniteautomation.serial.vo.SerialPointLocatorVO)

Aggregations

DataPointRT (com.serotonin.m2m2.rt.dataImage.DataPointRT)47 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)28 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)23 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)19 HashMap (java.util.HashMap)12 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)11 IDataPointValueSource (com.serotonin.m2m2.rt.dataImage.IDataPointValueSource)9 IOException (java.io.IOException)8 ResultTypeException (com.serotonin.m2m2.rt.script.ResultTypeException)7 ArrayList (java.util.ArrayList)7 ScriptException (javax.script.ScriptException)7 ScriptLog (com.serotonin.m2m2.rt.script.ScriptLog)6 ScriptPermissionsException (com.serotonin.m2m2.rt.script.ScriptPermissionsException)5 SerialPortException (com.infiniteautomation.mango.io.serial.SerialPortException)4 SerialPointLocatorVO (com.infiniteautomation.serial.vo.SerialPointLocatorVO)4 AnnotatedPointValueTime (com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime)4 DataPointListener (com.serotonin.m2m2.rt.dataImage.DataPointListener)4 DataValue (com.serotonin.m2m2.rt.dataImage.types.DataValue)4 DwrPermission (com.serotonin.m2m2.web.dwr.util.DwrPermission)4 ApiOperation (com.wordnik.swagger.annotations.ApiOperation)4