Search in sources :

Example 16 with DataValue

use of com.serotonin.m2m2.rt.dataImage.types.DataValue in project ma-core-public by infiniteautomation.

the class PointValueEmporter method importRow.

/*
     * (non-Javadoc)
     * @see com.serotonin.m2m2.vo.emport.AbstractSheetEmporter#importRow(org.apache.poi.ss.usermodel.Row)
     */
@Override
protected void importRow(Row rowData) throws SpreadsheetException {
    int cellNum = 0;
    // Data Point XID
    Cell xidCell = rowData.getCell(cellNum++);
    if (xidCell == null)
        throw new SpreadsheetException(rowData.getRowNum(), "emport.error.xidRequired");
    if ((xidCell.getStringCellValue() == null) || (xidCell.getStringCellValue().isEmpty()))
        throw new SpreadsheetException("emport.error.xidRequired");
    // First Check to see if we already have a point
    String xid = xidCell.getStringCellValue();
    DataPointVO dp = voMap.get(xid);
    DataPointRT dpRt = rtMap.get(xid);
    // We will always have the vo in the map but the RT may be null if the point isn't running
    if (dp == null) {
        dp = dataPointDao.getDataPoint(xid);
        if (dp == null)
            throw new SpreadsheetException(rowData.getRowNum(), "emport.error.missingPoint", xid);
        dpRt = Common.runtimeManager.getDataPoint(dp.getId());
        rtMap.put(xid, dpRt);
        voMap.put(xid, dp);
    }
    PointValueTime pvt;
    // Cell Device name (Not using Here)
    cellNum++;
    // Cell Point name (Not using Here)
    cellNum++;
    // Cell Time
    Date time = rowData.getCell(cellNum++).getDateCellValue();
    // delete/add column
    Cell modifyCell = rowData.getCell(7);
    boolean add = false;
    boolean delete = false;
    if (modifyCell != null) {
        String modification = (String) modifyCell.getStringCellValue();
        if (modification.equalsIgnoreCase("delete")) {
            delete = true;
        } else if (modification.equalsIgnoreCase("add")) {
            add = true;
        } else {
            throw new SpreadsheetException(rowData.getRowNum(), "emport.spreadsheet.modifyCellUnknown");
        }
    }
    // What do we do with the row
    if (delete) {
        if (time == null) {
            throw new SpreadsheetException(rowData.getRowNum(), "emport.error.deleteNew", "no timestamp, unable to delete");
        } else {
            try {
                this.rowsDeleted += Common.runtimeManager.purgeDataPointValue(dp.getId(), time.getTime());
            } catch (Exception e) {
                if (e instanceof DataIntegrityViolationException)
                    throw new SpreadsheetException(rowData.getRowNum(), "emport.error.unableToDeleteDueToConstraints");
                else
                    throw new SpreadsheetException(rowData.getRowNum(), "emport.error.unableToDelete", e.getMessage());
            }
        }
        // Done now
        return;
    } else if (add) {
        // Cell Value
        Cell cell;
        cell = rowData.getCell(cellNum++);
        // Create a data value
        DataValue dataValue;
        switch(dp.getPointLocator().getDataTypeId()) {
            case DataTypes.ALPHANUMERIC:
                dataValue = new AlphanumericValue(cell.getStringCellValue());
                break;
            case DataTypes.BINARY:
                switch(cell.getCellType()) {
                    case Cell.CELL_TYPE_BOOLEAN:
                        dataValue = new BinaryValue(new Boolean(cell.getBooleanCellValue()));
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        if (cell.getNumericCellValue() == 0)
                            dataValue = new BinaryValue(new Boolean(false));
                        else
                            dataValue = new BinaryValue(new Boolean(true));
                        break;
                    case Cell.CELL_TYPE_STRING:
                        if (cell.getStringCellValue().equalsIgnoreCase("false"))
                            dataValue = new BinaryValue(new Boolean(false));
                        else
                            dataValue = new BinaryValue(new Boolean(true));
                        break;
                    default:
                        throw new SpreadsheetException(rowData.getRowNum(), "common.default", "Invalid cell type for extracting boolean");
                }
                break;
            case DataTypes.MULTISTATE:
                dataValue = new MultistateValue((int) cell.getNumericCellValue());
                break;
            case DataTypes.NUMERIC:
                dataValue = new NumericValue(cell.getNumericCellValue());
                break;
            default:
                throw new SpreadsheetException(rowData.getRowNum(), "emport.spreadsheet.unsupportedDataType", dp.getPointLocator().getDataTypeId());
        }
        // Cell Rendered Value (Not using yet)
        cellNum++;
        // Cell Annotation
        Cell annotationRow = rowData.getCell(cellNum++);
        if (annotationRow != null) {
            String annotation = annotationRow.getStringCellValue();
            // TODO These methods here do not allow updating the Annotation. We need to be a set point source for that to work
            TranslatableMessage sourceMessage = new TranslatableMessage("common.default", annotation);
            pvt = new AnnotatedPointValueTime(dataValue, time.getTime(), sourceMessage);
        } else {
            pvt = new PointValueTime(dataValue, time.getTime());
        }
        // Save to cache if running
        if (dpRt != null)
            dpRt.savePointValueDirectToCache(pvt, null, true, true);
        else {
            if (pointValueDao instanceof EnhancedPointValueDao) {
                DataSourceVO<?> ds = getDataSource(dp.getDataSourceId());
                ((EnhancedPointValueDao) pointValueDao).savePointValueAsync(dp, ds, pvt, null);
            } else {
                pointValueDao.savePointValueAsync(dp.getId(), pvt, null);
            }
        }
        // Increment our counter
        this.rowsAdded++;
    }
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) DataSourceVO(com.serotonin.m2m2.vo.dataSource.DataSourceVO) DataValue(com.serotonin.m2m2.rt.dataImage.types.DataValue) ExportDataValue(com.serotonin.m2m2.vo.export.ExportDataValue) BinaryValue(com.serotonin.m2m2.rt.dataImage.types.BinaryValue) SpreadsheetException(com.serotonin.m2m2.vo.emport.SpreadsheetException) Date(java.util.Date) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) SpreadsheetException(com.serotonin.m2m2.vo.emport.SpreadsheetException) MultistateValue(com.serotonin.m2m2.rt.dataImage.types.MultistateValue) DataIntegrityViolationException(org.springframework.dao.DataIntegrityViolationException) AlphanumericValue(com.serotonin.m2m2.rt.dataImage.types.AlphanumericValue) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage) EnhancedPointValueDao(com.serotonin.m2m2.db.dao.EnhancedPointValueDao) NumericValue(com.serotonin.m2m2.rt.dataImage.types.NumericValue) Cell(org.apache.poi.ss.usermodel.Cell)

Example 17 with DataValue

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

the class PointValueRestController method setPointValue.

/**
 * Helper method for setting a point value
 *
 * @param xid
 * @param data
 * @param unitConversion
 * @return
 */
private RestProcessResult<PointValueTimeModel> setPointValue(User user, String xid, PointValueTimeModel model, boolean unitConversion, UriComponentsBuilder builder) {
    RestProcessResult<PointValueTimeModel> result = new RestProcessResult<PointValueTimeModel>(HttpStatus.OK);
    DataPointVO existingDp = DataPointDao.instance.getByXid(xid);
    if (existingDp == null) {
        result.addRestMessage(getDoesNotExistMessage());
        return result;
    }
    try {
        if (Permissions.hasDataPointSetPermission(user, existingDp)) {
            // Set the time to now if it is not present
            if (model.getTimestamp() == 0) {
                model.setTimestamp(Common.timer.currentTimeMillis());
            }
            // Validate the model's data type for compatibility
            if (DataTypeEnum.convertFrom(model.getType()) != existingDp.getPointLocator().getDataTypeId()) {
                result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("event.ds.dataType"));
                return result;
            }
            // Validate the timestamp for future dated
            if (model.getTimestamp() > Common.timer.currentTimeMillis() + SystemSettingsDao.getFutureDateLimit()) {
                result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "Future dated points not acceptable."));
                return result;
            }
            // Are we converting from the rendered Unit?
            if (unitConversion) {
                if ((model.getType() == DataTypeEnum.NUMERIC) && (model.getValue() instanceof Number)) {
                    double value;
                    if (model.getValue() instanceof Integer) {
                        value = (double) ((Integer) model.getValue());
                    } else {
                        value = (double) ((Double) model.getValue());
                    }
                    model.setValue(existingDp.getRenderedUnit().getConverterTo(existingDp.getUnit()).convert(value));
                } else {
                    result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Cannot perform unit conversion on Non Numeric data types."));
                    return result;
                }
            }
            // to convert it
            if ((model.getType() == DataTypeEnum.MULTISTATE) && (model.getValue() instanceof String)) {
                try {
                    DataValue value = existingDp.getTextRenderer().parseText((String) model.getValue(), existingDp.getPointLocator().getDataTypeId());
                    model.setValue(value.getObjectValue());
                } catch (Exception e) {
                    // Lots can go wrong here so let the user know
                    result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Unable to convert Multistate String representation to any known value."));
                }
            }
            final PointValueTime pvt;
            try {
                pvt = model.getData();
            } catch (Exception e) {
                result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]Invalid Format"));
                return result;
            }
            // one last check to ensure we are inserting the correct data type
            if (DataTypes.getDataType(pvt.getValue()) != existingDp.getPointLocator().getDataTypeId()) {
                result.addRestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("event.ds.dataType"));
                return result;
            }
            final int dataSourceId = existingDp.getDataSourceId();
            SetPointSource source = null;
            if (model.getAnnotation() != null) {
                source = new SetPointSource() {

                    @Override
                    public String getSetPointSourceType() {
                        return "REST";
                    }

                    @Override
                    public int getSetPointSourceId() {
                        return dataSourceId;
                    }

                    @Override
                    public TranslatableMessage getSetPointSourceMessage() {
                        return ((AnnotatedPointValueTime) pvt).getSourceMessage();
                    }

                    @Override
                    public void raiseRecursionFailureEvent() {
                        LOG.error("Recursive failure while setting point via REST");
                    }
                };
            }
            try {
                Common.runtimeManager.setDataPointValue(existingDp.getId(), pvt, source);
                // This URI may not always be accurate if the Data Source doesn't use the
                // provided time...
                URI location = builder.path("/v1/point-values/{xid}/{time}").buildAndExpand(xid, pvt.getTime()).toUri();
                result.addRestMessage(getResourceCreatedMessage(location));
                return result;
            } catch (RTException e) {
                // Ok its probably not enabled or settable
                result.addRestMessage(new RestMessage(HttpStatus.NOT_ACCEPTABLE, new TranslatableMessage("common.default", "[" + xid + "]" + e.getMessage())));
                return result;
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
                result.addRestMessage(getInternalServerErrorMessage(e.getMessage()));
                return result;
            }
        } else {
            result.addRestMessage(getUnauthorizedMessage());
            return result;
        }
    } catch (PermissionException e) {
        LOG.error(e.getMessage(), e);
        result.addRestMessage(getUnauthorizedMessage());
        return result;
    }
}
Also used : DataPointVO(com.serotonin.m2m2.vo.DataPointVO) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) XidPointValueTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.XidPointValueTimeModel) RecentPointValueTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.RecentPointValueTimeModel) PointValueTimeModel(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.PointValueTimeModel) DataValue(com.serotonin.m2m2.rt.dataImage.types.DataValue) SetPointSource(com.serotonin.m2m2.rt.dataImage.SetPointSource) URI(java.net.URI) RestValidationFailedException(com.serotonin.m2m2.web.mvc.rest.v1.exception.RestValidationFailedException) ValidationFailedRestException(com.infiniteautomation.mango.rest.v2.exception.ValidationFailedRestException) RTException(com.serotonin.m2m2.rt.RTException) NotFoundRestException(com.infiniteautomation.mango.rest.v2.exception.NotFoundRestException) PermissionException(com.serotonin.m2m2.vo.permission.PermissionException) RestProcessResult(com.serotonin.m2m2.web.mvc.rest.v1.message.RestProcessResult) RTException(com.serotonin.m2m2.rt.RTException) RestMessage(com.serotonin.m2m2.web.mvc.rest.v1.message.RestMessage) AnnotatedPointValueTime(com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime) TranslatableMessage(com.serotonin.m2m2.i18n.TranslatableMessage)

Example 18 with DataValue

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

the class AbstractPointValueRollupCalculator method createQuantizer.

/**
 * Create the proper quantizer for csv generation
 * @param vo
 * @param startValue
 * @param bc
 * @param writer
 * @return
 */
protected AbstractDataQuantizer createQuantizer(DataPointVO vo, DataValue startValue, BucketCalculator bc, CSVPojoWriter<T> writer, boolean writeXidColumn, boolean writeHeaders) {
    if (vo.getPointLocator().getDataTypeId() == DataTypes.NUMERIC) {
        return new AnalogStatisticsQuantizer(bc, startValue, new NumericPointValueStatisticsQuantizerCsvCallback(writer.getWriter(), vo, this.useRendered, this.unitConversion, this.rollup, writeXidColumn, writeHeaders, this.limit, this.dateTimeFormat, this.timezone));
    } else {
        if (!rollup.nonNumericSupport()) {
            LOG.warn("Invalid non-numeric rollup type: " + rollup);
            // Default to first
            rollup = RollupEnum.FIRST;
        }
        return new ValueChangeCounterQuantizer(bc, startValue, new NonNumericPointValueStatisticsQuantizerCsvCallback(writer.getWriter(), vo, useRendered, unitConversion, this.rollup, writeXidColumn, writeHeaders, this.limit, this.dateTimeFormat, this.timezone));
    }
}
Also used : NonNumericPointValueStatisticsQuantizerCsvCallback(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.statistics.NonNumericPointValueStatisticsQuantizerCsvCallback) NumericPointValueStatisticsQuantizerCsvCallback(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.statistics.NumericPointValueStatisticsQuantizerCsvCallback) NonNumericPointValueStatisticsQuantizerCsvCallback(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.statistics.NonNumericPointValueStatisticsQuantizerCsvCallback) ValueChangeCounterQuantizer(com.serotonin.m2m2.view.quantize2.ValueChangeCounterQuantizer) AnalogStatisticsQuantizer(com.serotonin.m2m2.view.quantize2.AnalogStatisticsQuantizer)

Example 19 with DataValue

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

the class AbstractPointValueRollupCalculator method getStartValue.

/**
 * Get the value at the start of the period or if there isn't one then return the closest value.
 * @param dataPointId
 * @return
 */
protected DataValue getStartValue(int dataPointId) {
    PointValueTime startPvt = pvd.getPointValueAt(dataPointId, from.getMillis());
    if (startPvt == null)
        startPvt = pvd.getPointValueBefore(dataPointId, from.getMillis());
    DataValue startValue = PointValueTime.getValue(startPvt);
    return startValue;
}
Also used : DataValue(com.serotonin.m2m2.rt.dataImage.types.DataValue) PointValueTime(com.serotonin.m2m2.rt.dataImage.PointValueTime)

Example 20 with DataValue

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

the class AbstractPointValueRollupCalculator method createQuantizer.

/**
 * Create the proper quantizer for json generation
 * @param startValue
 * @param bc
 * @param jgen
 * @return
 */
protected AbstractDataQuantizer createQuantizer(DataPointVO vo, DataValue startValue, BucketCalculator bc, JsonGenerator jgen) {
    if (vo.getPointLocator().getDataTypeId() == DataTypes.NUMERIC) {
        return new AnalogStatisticsQuantizer(bc, startValue, new NumericPointValueStatisticsQuantizerJsonCallback(jgen, vo, this.useRendered, this.unitConversion, this.rollup, this.limit, this.dateTimeFormat, this.timezone));
    } else {
        if (!rollup.nonNumericSupport()) {
            LOG.warn("Invalid non-numeric rollup type: " + rollup);
            // Default to first
            rollup = RollupEnum.FIRST;
        }
        return new ValueChangeCounterQuantizer(bc, startValue, new NonNumericPointValueStatisticsQuantizerJsonCallback(jgen, vo, useRendered, unitConversion, this.rollup, this.limit, this.dateTimeFormat, this.timezone));
    }
}
Also used : NumericPointValueStatisticsQuantizerJsonCallback(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.statistics.NumericPointValueStatisticsQuantizerJsonCallback) NonNumericPointValueStatisticsQuantizerJsonCallback(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.statistics.NonNumericPointValueStatisticsQuantizerJsonCallback) ValueChangeCounterQuantizer(com.serotonin.m2m2.view.quantize2.ValueChangeCounterQuantizer) NonNumericPointValueStatisticsQuantizerJsonCallback(com.serotonin.m2m2.web.mvc.rest.v1.model.pointValue.statistics.NonNumericPointValueStatisticsQuantizerJsonCallback) AnalogStatisticsQuantizer(com.serotonin.m2m2.view.quantize2.AnalogStatisticsQuantizer)

Aggregations

DataValue (com.serotonin.m2m2.rt.dataImage.types.DataValue)30 PointValueTime (com.serotonin.m2m2.rt.dataImage.PointValueTime)13 NumericValue (com.serotonin.m2m2.rt.dataImage.types.NumericValue)10 DataPointVO (com.serotonin.m2m2.vo.DataPointVO)10 AlphanumericValue (com.serotonin.m2m2.rt.dataImage.types.AlphanumericValue)8 MultistateValue (com.serotonin.m2m2.rt.dataImage.types.MultistateValue)8 TranslatableMessage (com.serotonin.m2m2.i18n.TranslatableMessage)6 AnnotatedPointValueTime (com.serotonin.m2m2.rt.dataImage.AnnotatedPointValueTime)6 BinaryValue (com.serotonin.m2m2.rt.dataImage.types.BinaryValue)6 BucketCalculator (com.serotonin.m2m2.view.quantize2.BucketCalculator)6 ShouldNeverHappenException (com.serotonin.ShouldNeverHappenException)5 HashMap (java.util.HashMap)5 PointValueDao (com.serotonin.m2m2.db.dao.PointValueDao)4 DataPointRT (com.serotonin.m2m2.rt.dataImage.DataPointRT)4 ImageValue (com.serotonin.m2m2.rt.dataImage.types.ImageValue)4 AbstractDataQuantizer (com.serotonin.m2m2.view.quantize2.AbstractDataQuantizer)4 ExportDataValue (com.serotonin.m2m2.vo.export.ExportDataValue)4 ImageSaveException (com.serotonin.m2m2.ImageSaveException)3 IDataPointValueSource (com.serotonin.m2m2.rt.dataImage.IDataPointValueSource)2 IdPointValueTime (com.serotonin.m2m2.rt.dataImage.IdPointValueTime)2