Skip to content

forms

importing.forms ¤

Classes¤

Format ¤

Bases: PermissionsBase

Details of the data file format, describing how to read the file.

It combines several properties, such as the file extension, the delimiter, the date and time formats, and the column indices for the date and time columns, instructing how to read the data file and parse the dates. It is mostly used to ingest data from text files, like CSV. For Thingsboard imports, only the name, description and thingsboard fields are applicable.

Attributes:

Name Type Description
format_id AutoField

Primary key.

name CharField

Short name of the format entry.

description TextField

Description of the format.

extension ForeignKey

The extension of the data file.

delimiter ForeignKey

The delimiter between columns in the data file. Only required for text files.

first_row PositiveSmallIntegerField

Index of the first row with data, starting in 0.

footer_rows PositiveSmallIntegerField

Number of footer rows to be ignored at the end.

date ForeignKey

Format for the date column. Only required for text files.

date_column PositiveSmallIntegerField

Index of the date column, starting in 0.

time ForeignKey

Format for the time column. Only required for text files.

time_column PositiveSmallIntegerField

Index of the time column, starting in 0.

thingsboard BooleanField

Whether the data is being imported from Thingsboard.

Attributes¤
datetime_format property ¤

Obtain the datetime format string.

Functions¤
__str__() ¤

Return the string representation of the object.

Source code in formatting/models.py
272
273
274
def __str__(self) -> str:
    """Return the string representation of the object."""
    return str(self.name)
clean() ¤

Validate the model instance.

Checks that the required fields for non-Thingsboard data are provided.

Source code in formatting/models.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
def clean(self) -> None:
    """Validate the model instance.

    Checks that the required fields for non-Thingsboard data are provided.
    """
    super().clean()
    errors = {}
    if not self.thingsboard:
        required_fields = (
            "extension",
            "first_row",
            "footer_rows",
            "date_column",
            "time_column",
        )
        for field in required_fields:
            if getattr(self, field) is None:
                errors[field] = "Field is required for non-Thingsboard data."

    if errors:
        raise ValidationError(errors)
datetime_columns(delimiter) ¤

Column indices that correspond to the date and time columns in the dataset.

Parameters:

Name Type Description Default
delimiter str

The delimiter used to split the date and time codes.

required

Returns:

Type Description
list[int]

list[int]: A list of column indices.

Source code in formatting/models.py
285
286
287
288
289
290
291
292
293
294
295
296
297
298
def datetime_columns(self, delimiter: str) -> list[int]:
    """Column indices that correspond to the date and time columns in the dataset.

    Args:
        delimiter (str): The delimiter used to split the date and time codes.

    Returns:
        list[int]: A list of column indices.
    """
    date_items = self.date.code.split(delimiter)
    date_cols = list(range(self.date_column, self.date_column + len(date_items)))
    time_items = self.time.code.split(delimiter)
    time_cols = list(range(self.time_column, self.time_column + len(time_items)))
    return date_cols + time_cols
get_absolute_url() ¤

Get the absolute URL of the object.

Source code in formatting/models.py
276
277
278
def get_absolute_url(self) -> str:
    """Get the absolute URL of the object."""
    return reverse("formatting:format_detail", kwargs={"pk": self.pk})

ThingsboardDataRetrievalForm(*args, user=None, **kwargs) ¤

Bases: Form

Form to select ThingsboardImportMap and date range for data retrieval.

Source code in importing/forms.py
34
35
36
37
38
39
40
41
42
43
44
45
46
def __init__(self, *args, user=None, **kwargs):
    super().__init__(*args, **kwargs)
    if user is not None:
        self.fields["thingsboard_map"].queryset = get_objects_for_user(
            user,
            "importing.view_thingsboardimportmap",
            klass=ThingsboardImportMap,
        )
        self.fields["format"].queryset = get_objects_for_user(
            user,
            "formatting.view_format",
            klass=Format,
        ).order_by("name")

ThingsboardImportMap ¤

Bases: PermissionsBase

Model to store Thingsboard device mappings to station variables.

This model maps Thingsboard devices to specific variables at stations, allowing data from IoT devices to be imported and associated with the correct station and variable combinations.

Attributes:

Name Type Description
tb_variable CharField

Name of the variable in Thingsboard.

variable ForeignKey

The existing variable in Paricia associated with this mapping.

tb_device_name CharField

The name of the device in Thingsboard.

station ForeignKey

The name of the corresponding station in Paricia.

Functions¤
clean() ¤

Validate that the variable is valid for the station.

Source code in importing/models.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def clean(self) -> None:
    """Validate that the variable is valid for the station."""
    try:
        station = self.station
    except ThingsboardImportMap.station.RelatedObjectDoesNotExist:
        raise ValidationError({"station": "Station is required."})

    try:
        variable = self.variable
    except ThingsboardImportMap.variable.RelatedObjectDoesNotExist:
        raise ValidationError({"variable": "Variable is required."})

    # Check if the variable is valid for the station through SensorInstallation
    if not SensorInstallation.objects.filter(
        variable=variable, station=station
    ).exists():
        raise ValidationError(
            {
                "variable": f"Variable '{variable}' is not configured for"
                f" station '{station}' via a sensor installation."
            }
        )