diff --git a/.env.example b/.env.example index a4ba811..9992938 100644 --- a/.env.example +++ b/.env.example @@ -19,6 +19,10 @@ REDIS_PASSWORD="pass" TEMPORAL_HOST=localhost:7233 TEMPORAL_NAMESPACE=scouter +PI_WEB_API_BASE_URL="https://piwebapi.link.com/piwebapi" +PI_WEB_API_AUTH_TYPE="basic" +PI_WEB_API_AUTH_TOKEN="password" + LOG_LEVEL=INFO PROJECT_NAME=scouter diff --git a/requirements.txt b/requirements.txt index f9857c6..541df15 100644 --- a/requirements.txt +++ b/requirements.txt @@ -3,5 +3,6 @@ psycopg2-binary sqlalchemy redis pymongo -git+ssh://git@github.com/Aignosi/sientia-dataops-library.git@1.6.1 -prometheus-client \ No newline at end of file +git+ssh://git@github.com/Aignosi/sientia-dataops-library.git@1.7.1 +prometheus-client +pycurl \ No newline at end of file diff --git a/scouter/activities/activities.py b/scouter/activities/activities.py index 2f3f8f9..0cc3f50 100644 --- a/scouter/activities/activities.py +++ b/scouter/activities/activities.py @@ -9,12 +9,13 @@ with workflow.unsafe.imports_passed_through(): from sientia_do.observability.logger import Logger from sientia_do.temporal.activities.postgres import Postgres + from scouter.activities.api import API from scouter.activities.gates import Gates from scouter.activities.mongodb import MongoDB from scouter.activities.redis import Redis -class Activities(Postgres, Redis, Gates, MongoDB): +class Activities(Postgres, Redis, Gates, MongoDB, API): """ Unified activities class that combines multiple data processing services. @@ -24,6 +25,7 @@ class Activities(Postgres, Redis, Gates, MongoDB): - Redis operations for caching and temporary storage - Data quality gates and filtering - MongoDB operations for data retrieval + - PI Web API operations for external data ingestion - Notification handling and logging The class implements the multiple inheritance pattern to provide a unified @@ -35,6 +37,7 @@ class Activities(Postgres, Redis, Gates, MongoDB): postgres_config: dict[str, Any], redis_config: dict[str, Any], mongodb_config: dict[str, Any], + api_config: dict[str, Any], logger: Logger, notification_handler: NotificationHandler, ): @@ -48,6 +51,8 @@ class Activities(Postgres, Redis, Gates, MongoDB): Required fields: host, port, username, password mongodb_config (dict[str, Any]): MongoDB connection configuration. Required fields: connection_string, database_name + api_config (dict[str, Any]): PI Web API configuration. + Required fields: base_url, auth_type, auth_token logger (Logger): Logger instance for application logging notification_handler (NotificationHandler): Handler for system notifications """ @@ -100,6 +105,17 @@ class Activities(Postgres, Redis, Gates, MongoDB): metrics_controller=metrics_controller, ) + # Initialize API + API.__init__( + self, + base_url=api_config['base_url'], + auth_type=api_config['auth_type'], + auth_token=api_config['auth_token'], + logger=logger, + notification_handler=notification_handler, + metrics_controller=metrics_controller, + ) + self.pod_id = getenv('HOSTNAME', 'localhost') def shutdown(self): @@ -113,3 +129,4 @@ class Activities(Postgres, Redis, Gates, MongoDB): MongoDB.close(self) Redis.close(self) Gates.close(self) + API.close(self) diff --git a/scouter/activities/api.py b/scouter/activities/api.py new file mode 100644 index 0000000..e70f19b --- /dev/null +++ b/scouter/activities/api.py @@ -0,0 +1,139 @@ +from temporalio import activity, workflow + +with workflow.unsafe.imports_passed_through(): + import traceback + from typing import Any + + from sientia_do.notifications.handlers import NotificationHandler + from sientia_do.notifications.models import NotificationLevel + from sientia_do.observability.logger import Logger + from sientia_do.observability.metrics_controller import MetricsController + from sientia_do.observability.sientia_monitoring import SientiaMonitoring + from sientia_do.temporal.constants import DATETIME_FORMAT_WITH_TZ + + from scouter.utils.clients.pi_web_api_client import PIWebAPIClient + + +class API(SientiaMonitoring): + """ + PI Web API operations for data retrieval. + + This class provides Temporal activities for interacting with the PI Web API + to retrieve tag values and historical data. It implements: + - Tag value retrieval from PI Web API endpoints + - Data quality filtering and validation + - Error handling with notifications + - Metrics collection for monitoring + + The class wraps the PIWebAPIClient to provide Temporal-aware activity methods + that can be used in workflow orchestration. + """ + + def __init__( + self, + base_url: str, + auth_type: str, + auth_token: str, + logger: Logger, + notification_handler: NotificationHandler, + metrics_controller: MetricsController, + ) -> None: + """ + Initialize API activity with PI Web API client. + + Args: + base_url (str): Base URL of the PI Web API server + auth_type (str): Authentication type ('basic' or 'bearer') + auth_token (str): Authentication token + logger (Logger): Logger instance for operation logging + notification_handler (NotificationHandler): Handler for system notifications + metrics_controller (MetricsController): Controller for metrics collection + """ + SientiaMonitoring.__init__(self, logger, notification_handler, metrics_controller) + self.pi_web_api_client = PIWebAPIClient( + base_url=base_url, + auth_config={ + 'type': auth_type, + 'token': auth_token, + }, + logger=logger, + notification_handler=notification_handler, + metrics_controller=metrics_controller, + ) + + def close(self) -> None: + """ + Close the PI Web API client and shutdown monitoring services. + """ + self.pi_web_api_client.close() + SientiaMonitoring.shutdown(self) + + @activity.defn(name='get_tag_values') + async def get_tag_values(self, input_data: dict[str, Any]) -> list[dict]: + """ + Retrieve tag values from PI Web API for specified WebIds. + + This activity fetches historical or real-time data from the PI Web API + for a set of configured tags. It returns the data as a list of dictionaries + suitable for further processing in the workflow. + + Args: + input_data (dict[str, Any]): Activity input parameters. + Required fields: + - metadata (dict[str, Any]): Workflow execution metadata + - endpoint (str): PI Web API endpoint path + - web_ids (dict[str, str | None]): Tag names mapped to WebIds + - period (dict[str, str]): Time period with 'start_time' field + - api_timeout (int): Request timeout in seconds + - max_count (int, optional): Maximum data points per tag. Defaults to 1 + + Returns: + list[dict]: List of data records, each containing: + - timestamp: Data point timestamp + - name: Tag name + - value: Numeric value + - tag: WebId + + Raises: + PIMSRequestError: If API request fails + Exception: If data retrieval or processing fails + """ + metadata = input_data['metadata'] + endpoint = input_data['endpoint'] + web_ids = input_data['web_ids'] + period = input_data['period'] + max_count = input_data.get('max_count', 1) + api_timeout = input_data['api_timeout'] + + self.info(f'Getting tag values from {endpoint}', metadata=metadata) + self.debug(f'Web IDs: {web_ids}', metadata=metadata) + try: + latest_values = await self.pi_web_api_client.get_latest_values_df( + endpoint=endpoint, + web_ids=web_ids, + start_time=period, + max_count=max_count, + metadata=metadata, + timeout=api_timeout, + ) + + except Exception as e: + await self.send_notification_async( + metadata=metadata, + notification_id='PI_WEB_API_REQUEST_ERROR', + message=f'Error getting tag values from PI Web API: {e}', + block='get_tag_values', + level=NotificationLevel.ERROR, + attachment_content=traceback.format_exc(), + ) + raise e + + latest_values['timestamp'] = latest_values['timestamp'].dt.strftime(DATETIME_FORMAT_WITH_TZ) + + # Normalize the package timestamp + latest_values['timestamp'] = latest_values['timestamp'].max() + + self.debug(f'Latest values: {latest_values}', metadata=metadata) + self.info(f'Gathered {len(latest_values)} tag values', metadata=metadata) + + return latest_values.to_dict(orient='records') diff --git a/scouter/metrics.py b/scouter/metrics.py index b25fa46..3ef2288 100644 --- a/scouter/metrics.py +++ b/scouter/metrics.py @@ -1,4 +1,5 @@ -from prometheus_client import Counter, Gauge +from prometheus_client import Counter, Gauge, Histogram +from sientia_do.observability.metrics import CORE_LABELS as SIENTIA_CORE_LABELS # Application health and status metrics APP_UP = Gauge( @@ -23,3 +24,23 @@ TAG_CHANGES_MONITOR = Gauge( 'Current value change of each tag', [*CORE_LABELS, 'tag_name'], ) + + +# Generic REST client metrics +GENERIC_REST_CLIENT_LAG = Histogram( + 'scouter_generic_rest_client_lag', + 'Lag time for a request to a generic REST client', + SIENTIA_CORE_LABELS, +) + +GENERIC_REST_READ_COUNT = Counter( + 'scouter_generic_rest_client_read_count', + 'Number of reads from a generic REST client', + SIENTIA_CORE_LABELS, +) + +GENERIC_REST_READ_ERROR_COUNT = Counter( + 'scouter_generic_rest_client_read_error_count', + 'Number of read errors from a generic REST client', + SIENTIA_CORE_LABELS, +) diff --git a/scouter/utils/clients/pi_web_api_client.py b/scouter/utils/clients/pi_web_api_client.py new file mode 100644 index 0000000..d18528a --- /dev/null +++ b/scouter/utils/clients/pi_web_api_client.py @@ -0,0 +1,335 @@ +import io +import json +import time +import warnings +from typing import Any +from urllib.parse import urlencode + +import pandas as pd +import pycurl +from sientia_do.notifications.handlers import NotificationHandler +from sientia_do.observability.logger import Logger +from sientia_do.observability.metrics_controller import MetricsController +from sientia_do.observability.sientia_monitoring import SientiaMonitoring + +from scouter import metrics + +warnings.simplefilter('ignore') # Ignore warnings such as 'verify=False' + + +class PIMSRequestError(Exception): + """Generic error for failed requests to PI Web API using pycurl.""" + + pass + + +class PIWebAPIClient(SientiaMonitoring): + """ + Client for interacting with the PI Web API. + + This class provides a robust interface for querying historical and real-time + data from OSIsoft PI systems through the PI Web API. It implements: + - Asynchronous HTTP requests using pycurl + - Authentication support (Basic and Bearer) + - Automatic data normalization and timestamp handling + - Comprehensive error handling and monitoring + - Metrics collection for observability + + The client is designed for high-performance data retrieval with proper + connection management and error recovery mechanisms. + """ + + def __init__( + self, + base_url: str, + auth_config: dict[str, Any], + logger: Logger, + notification_handler: NotificationHandler, + metrics_controller: MetricsController, + headers_config: dict[str, Any] | None = None, + ) -> None: + """ + Initialize the PI Web API client with connection parameters. + + Args: + base_url (str): Base URL of the PI Web API server + auth_config (dict[str, Any]): Authentication configuration. + Required fields: + - type (str): Authentication type ('basic' or 'bearer') + - token (str): Authentication token + logger (Logger): Logger instance for operation logging + notification_handler (NotificationHandler): Handler for system notifications + metrics_controller (MetricsController): Controller for metrics collection + headers_config (dict[str, Any], optional): HTTP headers configuration. + Default headers include content-type, accept, and x-requested-with + max_concurrency (int, optional): Maximum number of concurrent requests. Defaults to 8 + """ + if headers_config is None: + headers_config = { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'x-requested-with': 'XMLHttpRequest', + } + SientiaMonitoring.__init__(self, logger, notification_handler, metrics_controller) + + self.base_url = base_url.rstrip('/') + + # auth_config spec: + # 'type': 'basic' or 'bearer', + # 'token': 'token', + self.auth_config = auth_config + self.auth_config['type'] = self.auth_config['type'].lower() + self.headers: dict[str, str] = headers_config + + self.authenticate() + + def close(self) -> None: + """ + Close the client and shutdown monitoring services. + """ + SientiaMonitoring.shutdown(self) + + def _to_clean_timestamp(self, series: pd.Series) -> pd.Series: + """ + Convert a Series of timestamps to datetime, UTC, and round to the nearest second. + + Args: + series (pd.Series): Series containing timestamp values + + Returns: + pd.Series: Cleaned timestamp series in UTC, floored to seconds + """ + series = pd.to_datetime(series, utc=True, errors='coerce') + return series.dt.floor('s') + + def _extract_numeric(self, value: Any) -> float | None: + """ + Normalize a value (potentially nested) to float. + + This method handles PI Web API response values that may be nested + in dictionaries or other structures, extracting the numeric value. + + Args: + value (Any): Value to extract and normalize + + Returns: + float | None: Numeric value as float, or None if conversion fails + """ + if isinstance(value, dict): + value = value.get('Value', value) + return pd.to_numeric(value, errors='coerce') + + def authenticate(self): + """ + Configure authentication headers based on auth_config. + + This method sets up the Authorization header using either Basic or Bearer + authentication based on the configured authentication type. + + Raises: + ValueError: If authentication type is not 'basic' or 'bearer' + """ + self.logger.info(f'Authenticating with {self.auth_config["type"]} authentication') + + if self.auth_config['type'] == 'basic': + self.headers['Authorization'] = f'Basic {self.auth_config["token"]}' + elif self.auth_config['type'] == 'bearer': + self.headers['Authorization'] = f'Bearer {self.auth_config["token"]}' + else: + raise ValueError(f'Invalid authentication type: {self.auth_config["type"]}') + + async def _curl_get_json( + self, + url: str, + params: list[tuple[str, str]] | None = None, + timeout: int = 30, + verify: bool = True, + metadata: dict[str, Any] | None = None, + ) -> dict[str, Any]: + """ + Perform a GET request using pycurl and return the decoded JSON response. + + This method executes an asynchronous HTTP GET request with proper error handling, + metrics collection, and timeout management. It automatically tracks request + latency and emits monitoring metrics. + + Args: + url (str): Target URL for the GET request + params (list[tuple[str, str]], optional): Query parameters as list of tuples. + Each tuple contains (parameter_name, parameter_value) + timeout (int, optional): Request timeout in seconds. Defaults to 30 + verify (bool, optional): Verify SSL certificates. Defaults to True + metadata (dict[str, Any], optional): Workflow execution metadata for tracking + + Returns: + dict[str, Any]: Parsed JSON response body + + Raises: + PIMSRequestError: If HTTP error, connection error, or JSON parsing error occurs + """ + if metadata is None: + metadata = {} + + buffer = io.BytesIO() + c = pycurl.Curl() + + core_labels = self.get_core_labels(metadata=metadata, operation_type='get_json') + + try: + if params: + query_string = urlencode(params, doseq=True) + full_url = f'{url}?{query_string}' + else: + full_url = url + + c.setopt(pycurl.URL, full_url.encode('utf-8')) + c.setopt(pycurl.WRITEDATA, buffer) + + # Configure HTTP headers + header_list = [f'{k}: {v}' for k, v in self.headers.items()] + if header_list: + c.setopt(pycurl.HTTPHEADER, header_list) + + # Set request timeout + c.setopt(pycurl.TIMEOUT, timeout) + + # Configure SSL verification + if not verify: + c.setopt(pycurl.SSL_VERIFYPEER, 0) + c.setopt(pycurl.SSL_VERIFYHOST, 0) + + start_time = time.time() + try: + c.perform() + except Exception as e: + await self.emit_metric( + metric_object=metrics.GENERIC_REST_READ_ERROR_COUNT, + tags=core_labels, + ) + raise e + await self.observe_lag( + start_time=start_time, + metric_object=metrics.GENERIC_REST_CLIENT_LAG, + tags=core_labels, + ) + + status_code = c.getinfo(pycurl.RESPONSE_CODE) + body = buffer.getvalue().decode('utf-8', errors='replace') + + if status_code >= 400: + await self.emit_metric( + metric_object=metrics.GENERIC_REST_READ_ERROR_COUNT, + tags=core_labels, + ) + raise PIMSRequestError(f"HTTP {status_code} calling '{full_url}': {body[:200]}") + + await self.emit_metric( + metric_object=metrics.GENERIC_REST_READ_COUNT, + tags=core_labels, + ) + try: + return json.loads(body) + except json.JSONDecodeError as e: + raise PIMSRequestError( + f"Error decoding JSON response from '{full_url}': {e}; body: {body[:200]}" + ) from e + + except pycurl.error as e: + raise PIMSRequestError(f"Connection error calling '{url}': {e}") from e + finally: + c.close() + + async def get_latest_values_df( + self, + web_ids: dict[str, dict[str, str]], + endpoint: str, + timeout: int = 30, + start_time: str = '*-1d', + end_time: str = '*', + max_count: int | None = 1, + metadata: dict[str, Any] | None = None, + ) -> pd.DataFrame: + """ + Retrieve historical values for multiple WebIds using PI Web API streamsets. + + This method queries the PI Web API's /streamsets/recorded endpoint to fetch + historical data for multiple tags simultaneously. It returns a normalized + DataFrame with timestamps, tag names, values, and WebIds. + + Args: + web_ids (dict[str, str | None]): Dictionary mapping tag names to their WebIds. + None values are filtered out before querying + endpoint (str): PI Web API endpoint path (e.g., '/streamsets/recorded') + timeout (int, optional): Request timeout in seconds. Defaults to 30 + start_time (str, optional): Start time in PI Web API format (e.g., "*-50d"). + Defaults to "*-1d" (1 day ago) + end_time (str, optional): End time in PI Web API format (e.g., "*"). + Defaults to "*" (current time) + max_count (int, optional): Maximum number of data points per series. + Defaults to 1. If None, maxCount parameter is not sent + metadata (dict[str, Any], optional): Workflow execution metadata for tracking + + Returns: + pd.DataFrame: DataFrame with columns: + - timestamp: Cleaned timestamp (UTC, floored to seconds) + - name: Tag name + - value: Numeric value (normalized) + - tag: WebId of the tag + Returns empty DataFrame if no data is found + + Raises: + PIMSRequestError: If API request fails or returns invalid data + """ + if metadata is None: + metadata = {} + + url = f'{self.base_url}{endpoint}' + + # Build query parameters with WebIds (filtering out None values) + params: list[tuple[str, str]] = [('webid', web_id['webid']) for web_id in web_ids.values()] + params.extend( + [ + ('startTime', start_time), + ('endtime', end_time), + ('selectedFields', 'Items.Name;Items.Items.Timestamp;Items.Items.Value'), + ] + ) + + params.append(('maxCount', str(max_count))) + + data = await self._curl_get_json( + url=url, + params=params, + timeout=timeout, + verify=False, + metadata=metadata, + ) + + raw_data = data.get('Items', []) + + records = [] + for entry in raw_data: + tag_name = entry.get('Name') + series_items = entry.get('Items', []) + for it in series_items: + if isinstance(it, dict) and 'Timestamp' in it and 'Value' in it: + ts = it.get('Timestamp') + val = it.get('Value') + web_id = web_ids[tag_name]['webid'] + if ts is not None: + records.append( + { + 'timestamp': ts, + 'name': tag_name, + 'value': self._extract_numeric(val), + 'tag': web_id, + } + ) + + if not records: + return pd.DataFrame() + + df = pd.DataFrame.from_records(records) + df['timestamp'] = self._to_clean_timestamp(df['timestamp']) + + return df diff --git a/scouter/utils/connectors_config.py b/scouter/utils/connectors_config.py index 4264aa1..da712d9 100644 --- a/scouter/utils/connectors_config.py +++ b/scouter/utils/connectors_config.py @@ -83,6 +83,23 @@ def build_mongodb_config() -> dict[str, Any]: } +def build_api_config() -> dict[str, Any]: + """ + Build API connection configuration from environment variables. + + Returns: + dict[str, Any]: API configuration dictionary with keys: + - base_url: API base URL (default: https://pi.example.com) + - auth_type: API authentication type (default: basic) + - auth_token: API authentication token (default: None) + """ + return { + 'base_url': getenv('PI_WEB_API_BASE_URL', 'https://pi.example.com'), + 'auth_type': getenv('PI_WEB_API_AUTH_TYPE', 'basic'), + 'auth_token': getenv('PI_WEB_API_AUTH_TOKEN', None), + } + + def build_druid_config() -> dict[str, Any]: """ Build Apache Druid connection configuration from environment variables. diff --git a/scouter/worker/prepare_worker.py b/scouter/worker/prepare_worker.py index 09fced1..c8b68f2 100644 --- a/scouter/worker/prepare_worker.py +++ b/scouter/worker/prepare_worker.py @@ -1,7 +1,9 @@ import os +import re from collections.abc import Sequence from typing import Any +from sientia_do.observability.logger import Logger from temporalio.client import Client from temporalio.worker import PollerBehaviorAutoscaling, Worker @@ -19,14 +21,24 @@ parameters = [ ] +def camel_to_snake(text: str) -> str: + """Convert camelCase or PascalCase to snake_case.""" + text = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', text) + text = re.sub('([a-z0-9])([A-Z])', r'\1_\2', text) + return text.lower() + + def prepare_worker( main_workflow: type, other_workflows: Sequence[type], activities: Sequence[Any], temporal_client: Client, + logger: Logger, ) -> Worker: main_workflow_name = main_workflow.__name__.upper() + queue_name = f'{camel_to_snake(main_workflow.__name__)}-queue' + local_workflow_parameters = {} for parameter in parameters: @@ -34,9 +46,11 @@ def prepare_worker( os.getenv(main_workflow_name + '_' + parameter[0], parameter[1]) ) + logger.info(f'Preparing worker for {main_workflow_name} with queue {queue_name}') + return Worker( temporal_client, - task_queue='scouter-queue', + task_queue=queue_name, workflows=[main_workflow, *other_workflows], activities=[*activities], max_concurrent_workflow_tasks=local_workflow_parameters['MAX_CONCURRENT_WORKFLOW_TASKS'], diff --git a/scouter/worker/worker.py b/scouter/worker/worker.py index cd333f4..4de701a 100644 --- a/scouter/worker/worker.py +++ b/scouter/worker/worker.py @@ -15,10 +15,12 @@ with workflow.unsafe.imports_passed_through(): from scouter import metrics from scouter.activities.activities import Activities from scouter.utils.connectors_config import ( + build_api_config, build_mongodb_config, build_postgres_config, build_redis_config, ) + from scouter.workflow.pi_web_api_scouter import PIWebAPIScouter from scouter.workflow.scouter import Scouter from scouter.workflow.sub_workflows.core_scouter import CoreScouter @@ -103,6 +105,7 @@ async def main(): postgres_config=build_postgres_config(), redis_config=build_redis_config(), mongodb_config=build_mongodb_config(), + api_config=build_api_config(), ) logger.custom_info(f'Starting SDK Metrics Server on port {SDK_METRICS_PORT}...', metadata) @@ -137,7 +140,23 @@ async def main(): activities.write_metrics, activities.store_data_package, ], - ) + logger=logger, + ), + prepare_worker( + temporal_client=temporal_client, + main_workflow=PIWebAPIScouter, + other_workflows=[CoreScouter], + activities=[ + activities.get_tag_values, + activities.data_quality_gate, + activities.aggregate_data, + activities.group_and_hold_data, + activities.export_data_to_postgres, + activities.write_metrics, + activities.store_data_package, + ], + logger=logger, + ), ] handlers = [] diff --git a/scouter/workflow/pi_web_api_scouter.py b/scouter/workflow/pi_web_api_scouter.py new file mode 100644 index 0000000..6582e4e --- /dev/null +++ b/scouter/workflow/pi_web_api_scouter.py @@ -0,0 +1,103 @@ +from temporalio import workflow + +with workflow.unsafe.imports_passed_through(): + from datetime import timedelta + from typing import Any + + from sientia_do.temporal.policies import retry_policy + + from scouter.activities.activities import Activities + + +@workflow.defn(name='pi_web_api_scouter') +class PIWebAPIScouter: + """ + PI Web API Scouter workflow that orchestrates data ingestion from PI systems. + + This workflow serves as the entry point for PI Web API data processing pipelines. + Unlike the standard Scouter that loads from MongoDB, this workflow directly queries + PI Web API endpoints to retrieve tag values and processes them for downstream use. + + The workflow implements a direct API ingestion pattern with: + - Real-time data retrieval from PI Web API + - Configurable time periods and data point limits + - Error handling and retry policies + - Child workflow orchestration for data processing + - Integration with CoreScouter for standardized processing + """ + + @workflow.run + async def run(self, input_data: dict[str, Any]) -> None: + """ + Execute the PI Web API Scouter workflow. + + This method orchestrates the complete data ingestion process from PI Web API: + 1. Retrieves tag values from PI Web API using configured WebIds + 2. Validates and normalizes the retrieved data + 3. Delegates data processing to the CoreScouter workflow + + Args: + input_data (dict[str, Any]): Configuration and parameters for the workflow execution. + Required fields: + - model_name (str): Name of the data model being processed + - model_id (str): Unique identifier for the data model + - schedule_name (str): Unique identifier for the data collection schedule + - endpoint (str): PI Web API endpoint path (e.g., '/streamsets/recorded') + - web_ids (dict[str, str | None]): Mapping of tag names to WebIds + - period (dict[str, str]): Time period configuration with 'start_time' + - api_timeout (int): Request timeout in seconds for PI Web API calls + - max_count (int, optional): Maximum data points per tag. Defaults to 1 + - trigger_laborious (bool): Flag to enable intensive data processing + - filters (dict[str, str]): Data quality filters configuration + - schema (str): Target database schema for data export + - table_name (str): Target table name for data export + - retention_time (int): Data retention period in Redis (seconds) + - model_tags (dict[str, Any]): Tag-specific configuration including: + - data_range: [min, max] values for data validation + - aggr_function: Aggregation method (avg, mdn, max, min, lts) + - frequency: Data collection frequency in milliseconds + - topics: List of Kafka topics for data routing + + Returns: + None: This workflow doesn't return data, it orchestrates data processing + + Raises: + WorkflowExecutionError: If workflow execution fails + ActivityExecutionError: If any activity fails after retry attempts + PIMSRequestError: If PI Web API request fails + """ + + input_data['workflow_name'] = 'scouter' + + metadata = { + 'metadata': { + 'model_id': input_data['model_id'], + 'model_name': input_data['model_name'], + 'schedule_name': input_data['schedule_name'], + 'workflow_name': input_data['workflow_name'], + } + } + + pi_web_api_query = input_data['pi_web_api_query'] + + data = await workflow.execute_local_activity_method( + Activities.get_tag_values, + { + **metadata, + 'endpoint': pi_web_api_query['endpoint'], + 'web_ids': input_data['model_tags'], + 'period': pi_web_api_query['period'], + 'max_count': pi_web_api_query.get('max_count', 1), + 'api_timeout': pi_web_api_query['api_timeout'], + }, + start_to_close_timeout=timedelta(seconds=60), + retry_policy=retry_policy, + ) + + if not data: + return + + input_data['data'] = data + input_data['metadata'] = metadata + + await workflow.execute_child_workflow('subworkflow.core_scouter', input_data) diff --git a/scouter/workflow/sub_workflows/core_scouter.py b/scouter/workflow/sub_workflows/core_scouter.py index 1bbc4cb..2e9b1c1 100644 --- a/scouter/workflow/sub_workflows/core_scouter.py +++ b/scouter/workflow/sub_workflows/core_scouter.py @@ -102,7 +102,7 @@ class CoreScouter: if held_data == {}: return - await workflow.execute_activity_method( + data_exported = await workflow.execute_activity_method( Activities.export_data_to_postgres, { **metadata, @@ -110,11 +110,16 @@ class CoreScouter: 'table_name': input_data['table_name'], 'data': held_data, 'timestamp_conversion': {'column': 'timestamp', 'format': DATETIME_FORMAT_WITH_TZ}, + 'on_conflict': 'ignore', + 'unique_columns': ['model_id', 'timestamp', 'variable'], }, retry_policy=retry_policy, start_to_close_timeout=timedelta(seconds=60), ) + if data_exported.get('affected_rows', 0) <= 0: + return + await workflow.execute_activity_method( Activities.write_metrics, { diff --git a/tests.ipynb b/tests.ipynb new file mode 100644 index 0000000..79f937d --- /dev/null +++ b/tests.ipynb @@ -0,0 +1,984 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 12, + "id": "9d16b24a", + "metadata": {}, + "outputs": [], + "source": [ + "from datetime import timedelta\n", + "from typing import Any\n", + "from temporalio import client\n", + "from temporalio.client import WorkflowHandle\n", + "\n", + "\n", + "async def start_workflow_advanced(\n", + " temporal_client: client.Client,\n", + " workflow_name: str,\n", + " workflow_input: dict[str, Any],\n", + " workflow_id: str,\n", + " task_queue: str,\n", + " execution_timeout: timedelta | None = None,\n", + " run_timeout: timedelta | None = None,\n", + " task_timeout: timedelta | None = None,\n", + ") -> WorkflowHandle:\n", + " handle = await temporal_client.start_workflow(\n", + " workflow=workflow_name,\n", + " arg=workflow_input,\n", + " id=workflow_id or f\"{workflow_name}-{id(workflow_input)}\",\n", + " task_queue=task_queue,\n", + " execution_timeout=execution_timeout,\n", + " run_timeout=run_timeout,\n", + " task_timeout=task_timeout,\n", + " )\n", + " \n", + " return handle" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "5e344fb0", + "metadata": {}, + "outputs": [], + "source": [ + "input_data = {\n", + " \"debug_data_package\": False,\n", + " \"execution_timeout_seconds\": 300,\n", + " \"fill_missing_tags\": False,\n", + " \"filters\": {\n", + " \"NULL_VALUES_FILTER\": {\n", + " \"policy\": \"DISCARD\"\n", + " },\n", + " \"OUT_OF_BOUNDS_FILTER\": {\n", + " \"policy\": \"DISCARD\"\n", + " }\n", + " },\n", + " \"frequency\": \"30s\",\n", + " \"max_retry_policy\": 1,\n", + " \"model_config\": {\n", + " \"predict_flavor\": \"sklearn\",\n", + " \"retention_minutes\": 0,\n", + " \"target\": \"CI-W3A05F1\",\n", + " \"transform_flavor\": \"sklearn\"\n", + " },\n", + " \"model_id\": \"10\",\n", + " \"model_name\": \"Pi Web API Test Model\",\n", + " \"model_tags\": {\n", + " \"CI-W3W03S1\": {\n", + " \"aggr_func\": \"avg\",\n", + " \"data_range\": [\n", + " -100000,\n", + " 100000\n", + " ],\n", + " \"webid\": \"F1DP-7fYgsRTtUOa7V9NIwSujATFUAAAUElIQVZDXENJLVczVzAzUzE\"\n", + " },\n", + " \"CI-W3A05F1\": {\n", + " \"aggr_func\": \"lts\",\n", + " \"data_range\": [\n", + " -100000,\n", + " 100000\n", + " ],\n", + " \"webid\": \"F1DP-7fYgsRTtUOa7V9NIwSujAkVMAAAUElIQVZDXENJLVczQTA1RjE\"\n", + " }\n", + " },\n", + " \"pi_web_api_query\": {\n", + " \"endpoint\": \"/streamsets/recorded\",\n", + " \"period\": \"*-1d\",\n", + " \"max_count\": 1,\n", + " \"api_timeout\": 5\n", + " },\n", + " \"offset\": \"0m\",\n", + " \"retention_time\": 3600,\n", + " \"schedule_name\": \"pi-web-api-scouter-test\",\n", + " \"schema\": \"sientia_data\",\n", + " \"table_name\": \"laborious_data\",\n", + " \"task_timeout_seconds\": 300,\n", + " \"trigger_laborious\": False,\n", + " \"updated_at\": \"2025-08-13 18:35:01.600000+0000\",\n", + " \"workflow_type\": \"pi_web_api_scouter\"\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "9350bff3", + "metadata": {}, + "outputs": [], + "source": [ + "from temporalio import client\n", + "\n", + "temporal_client = await client.Client.connect(\n", + " target_host=\"localhost:7233\",\n", + " namespace=\"scouter\"\n", + ")\n" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "45712d7a", + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "import datetime\n", + "\n", + "now = datetime.datetime.now()\n", + "\n", + "handle = await start_workflow_advanced(\n", + " temporal_client=temporal_client,\n", + " workflow_name='pi_web_api_scouter',\n", + " workflow_input=input_data,\n", + " workflow_id='test_workflow_id_' + now.strftime('%Y%m%d%H%M%S'),\n", + " task_queue='pi-web-api-scouter-queue',\n", + " execution_timeout=timedelta(seconds=30),\n", + " run_timeout=timedelta(seconds=30),\n", + " task_timeout=timedelta(seconds=30),\n", + ")\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "d065d0de", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "pi-web-api-scouter\n" + ] + } + ], + "source": [ + "import re\n", + "def camel_to_kebab(text: str) -> str:\n", + " \"\"\"Convert camelCase or PascalCase to kebab-case.\"\"\"\n", + " text = re.sub('(.)([A-Z][a-z]+)', r'\\1-\\2', text)\n", + " text = re.sub('([a-z0-9])([A-Z])', r'\\1-\\2', text)\n", + " return text.lower()\n", + "\n", + "print(camel_to_kebab('PiWebApiScouter'))\n" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "72af4236", + "metadata": {}, + "outputs": [ + { + "ename": "KeyError", + "evalue": "'Items'", + "output_type": "error", + "traceback": [ + "\u001b[31m---------------------------------------------------------------------------\u001b[39m", + "\u001b[31mKeyError\u001b[39m Traceback (most recent call last)", + "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[17]\u001b[39m\u001b[32m, line 42\u001b[39m\n\u001b[32m 39\u001b[39m \u001b[38;5;28;01mfor\u001b[39;00m tag \u001b[38;5;129;01min\u001b[39;00m TAG_NAMES:\n\u001b[32m 40\u001b[39m response = requests.get(url.replace(\u001b[33m'\u001b[39m\u001b[38;5;132;01m{tag}\u001b[39;00m\u001b[33m'\u001b[39m, tag), headers=headers).json()\n\u001b[32m 41\u001b[39m web_ids[tag] = {\n\u001b[32m---> \u001b[39m\u001b[32m42\u001b[39m \u001b[33m'\u001b[39m\u001b[33mwebid\u001b[39m\u001b[33m'\u001b[39m: \u001b[43mresponse\u001b[49m\u001b[43m[\u001b[49m\u001b[33;43m'\u001b[39;49m\u001b[33;43mItems\u001b[39;49m\u001b[33;43m'\u001b[39;49m\u001b[43m]\u001b[49m[\u001b[32m0\u001b[39m][\u001b[33m'\u001b[39m\u001b[33mWebId\u001b[39m\u001b[33m'\u001b[39m],\n\u001b[32m 43\u001b[39m \u001b[33m'\u001b[39m\u001b[33maggr_func\u001b[39m\u001b[33m'\u001b[39m: \u001b[33m'\u001b[39m\u001b[33mlts\u001b[39m\u001b[33m'\u001b[39m,\n\u001b[32m 44\u001b[39m \u001b[33m'\u001b[39m\u001b[33mdata_range\u001b[39m\u001b[33m'\u001b[39m: [-\u001b[32m100000\u001b[39m, \u001b[32m100000\u001b[39m],\n\u001b[32m 45\u001b[39m }\n\u001b[32m 46\u001b[39m sleep(\u001b[32m0.5\u001b[39m)\n", + "\u001b[31mKeyError\u001b[39m: 'Items'" + ] + } + ], + "source": [ + "import requests\n", + "from time import sleep\n", + "\n", + "# Obter web id das seguintes tags:\n", + "TAG_NAMES = [\n", + " \"CI-W3A05F1\",\n", + " \"CI-W3W03S1\", \"CI-W3W03I1\", \"CI-W3K01T1\", \"CI-W3W01A3\",\n", + " \"CI-W3W01A2\", \"CI-W3W01A1\", \"CI-J3P01T1A\", \"CI-W3A50T1\", \"CI-W3A55T1\",\n", + " \"CI-W3A55P1\", \"CI-W3V33P1\", \"CI-W3E01F1\", \"CI-W3A50A3\", \"CI-W3A50A2\",\n", + " \"CI-W3A50A1\", \"CI-W3A50P1\", \"CI-W3W01P1\", \"CI-W3A71P1\", \"CI-W3W01P2\",\n", + " \"CI-W3A71P2\", \"CI-W3A71P3\", \"CI-J3J01S1\", \"CI-W3P17S1\", \"CI-J3P03S1\",\n", + " \"CI-W3K01S1\", \"CI-W3K14P1\", \"CI-W3K01T4\", \"CI-W3K01T2\", \n", + "\n", + " \"CI-W3FARCI_FSC\",\n", + " \"CI-W3FARCI_MA\",\n", + " \"CI-W3FARCI_MS\",\n", + " \"CI-W3FARCI_P100\",\n", + " \"CI-W3FARCI_p170\",\n", + "\n", + " \"CI-W3CLK_C3S\",\n", + " \"CI-W3CLK_C3S_EXP\",\n", + " \"CI-W3CLK_C3S_MD_EXP\",\n", + " \"CI-W3CLK_C3S_MD_PETRO\",\n", + " \"CI-W3V04P3\", \"CI-W3V04P1\",\n", + " \"CI-W3W01G1\"\n", + "]\n", + "\n", + "url = 'https://pivision.votorantimcimentos.com/piwebapi/dataservers/F1DS-7fYgsRTtUOa7V9NIwSujAUElIQVZD/points?namefilter={tag}'\n", + "\n", + "headers = {\n", + " 'Content-Type': 'application/json',\n", + " 'Accept': 'application/json',\n", + " 'X-Requested-With': 'piwebapistreams', # Header recomendado pelo PI Web API\n", + " 'Authorization': \"\"\n", + "}\n", + "\n", + "web_ids = {}\n", + "\n", + "for tag in TAG_NAMES:\n", + " response = requests.get(url.replace('{tag}', tag), headers=headers).json()\n", + " web_ids[tag] = {\n", + " 'webid': response['Items'][0]['WebId'],\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000],\n", + " }\n", + " sleep(0.5)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "55793801", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'CI-W3A05F1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAkVMAAAUElIQVZDXENJLVczQTA1RjE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3W03S1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujATFUAAAUElIQVZDXENJLVczVzAzUzE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3W03I1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAS1UAAAUElIQVZDXENJLVczVzAzSTE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3K01T1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAklQAAAUElIQVZDXENJLVczSzAxVDE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3W01A3': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAOFUAAAUElIQVZDXENJLVczVzAxQTM',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3W01A2': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAN1UAAAUElIQVZDXENJLVczVzAxQTI',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3W01A1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujANlUAAAUElIQVZDXENJLVczVzAxQTE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-J3P01T1A': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAYUUAAAUElIQVZDXENJLUozUDAxVDFB',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3A50T1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujArFMAAAUElIQVZDXENJLVczQTUwVDE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3A55T1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAxFMAAAUElIQVZDXENJLVczQTU1VDE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3A55P1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAwVMAAAUElIQVZDXENJLVczQTU1UDE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3V33P1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAJVUAAAUElIQVZDXENJLVczVjMzUDE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3E01F1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAzY0CAAUElIQVZDXENJLVczRTAxRjE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3A50A3': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAqVMAAAUElIQVZDXENJLVczQTUwQTM',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3A50A2': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAqFMAAAUElIQVZDXENJLVczQTUwQTI',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3A50A1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAp1MAAAUElIQVZDXENJLVczQTUwQTE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3A50P1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAq1MAAAUElIQVZDXENJLVczQTUwUDE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3W01P1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAPlUAAAUElIQVZDXENJLVczVzAxUDE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3A71P1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAy1MAAAUElIQVZDXENJLVczQTcxUDE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3W01P2': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAP1UAAAUElIQVZDXENJLVczVzAxUDI',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3A71P2': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAzFMAAAUElIQVZDXENJLVczQTcxUDI',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3A71P3': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAzVMAAAUElIQVZDXENJLVczQTcxUDM',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-J3J01S1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAMUUAAAUElIQVZDXENJLUozSjAxUzE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3P17S1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujA7VQAAAUElIQVZDXENJLVczUDE3UzE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-J3P03S1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAa0UAAAUElIQVZDXENJLUozUDAzUzE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3K01S1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAkFQAAAUElIQVZDXENJLVczSzAxUzE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3K14P1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAuFQAAAUElIQVZDXENJLVczSzE0UDE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3K01T4': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAl1QAAAUElIQVZDXENJLVczSzAxVDQ',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3K01T2': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAlVQAAAUElIQVZDXENJLVczSzAxVDI',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3FARCI_FSC': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAgVQAAAUElIQVZDXENJLVczRkFSQ0lfRlND',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3FARCI_MA': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAg1QAAAUElIQVZDXENJLVczRkFSQ0lfTUE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3FARCI_MS': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAhVQAAAUElIQVZDXENJLVczRkFSQ0lfTVM',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3FARCI_P100': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAiFQAAAUElIQVZDXENJLVczRkFSQ0lfUDEwMA',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3FARCI_p170': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAiVQAAAUElIQVZDXENJLVczRkFSQ0lfUDE3MA',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3CLK_C3S': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujA4lMAAAUElIQVZDXENJLVczQ0xLX0MzUw',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3CLK_C3S_EXP': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujA41MAAAUElIQVZDXENJLVczQ0xLX0MzU19FWFA',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3CLK_C3S_MD_EXP': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujA5VMAAAUElIQVZDXENJLVczQ0xLX0MzU19NRF9FWFA',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3CLK_C3S_MD_PETRO': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujA5lMAAAUElIQVZDXENJLVczQ0xLX0MzU19NRF9QRVRSTw',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3V04P3': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAElUAAAUElIQVZDXENJLVczVjA0UDM',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3V04P1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAEFUAAAUElIQVZDXENJLVczVjA0UDE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]},\n", + " 'CI-W3W01G1': {'webid': 'F1DP-7fYgsRTtUOa7V9NIwSujAOlUAAAUElIQVZDXENJLVczVzAxRzE',\n", + " 'aggr_func': 'lts',\n", + " 'data_range': [-100000, 100000]}}" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "web_ids" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2e0e3d5a", + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'Links': {},\n", + " 'Items': [{'WebId': 'F1DP-7fYgsRTtUOa7V9NIwSujAkVMAAAUElIQVZDXENJLVczQTA1RjE',\n", + " 'Name': 'CI-W3A05F1',\n", + " 'Path': '\\\\\\\\PIHAVC\\\\CI-W3A05F1',\n", + " 'Links': {'Source': 'https://pivision.votorantimcimentos.com/piwebapi/points/F1DP-7fYgsRTtUOa7V9NIwSujAkVMAAAUElIQVZDXENJLVczQTA1RjE'},\n", + " 'Items': [{'Timestamp': '2025-12-17T18:12:49.2170104Z',\n", + " 'Value': 273.3339,\n", + " 'UnitsAbbreviation': '',\n", + " 'Good': True,\n", + " 'Questionable': False,\n", + " 'Substituted': False,\n", + " 'Annotated': False}],\n", + " 'UnitsAbbreviation': ''}]}" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "item = web_ids['CI-W3A05F1']['webid']\n", + "\n", + "requests.get(\n", + " f'https://pivision.votorantimcimentos.com/piwebapi/streamsets/recorded',\n", + " params={\n", + " 'webid': item,\n", + " 'startTime': '*-1d',\n", + " 'endtime': '*',\n", + " \"maxCount\": 1,\n", + " },\n", + " headers=headers\n", + ").json()" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "f8c425e2", + "metadata": {}, + "outputs": [ + { + "data": { + "text/html": [ + "
| variable | \n", + "CI-J3J01S1 | \n", + "CI-J3P01T1A | \n", + "CI-J3P03S1 | \n", + "CI-W3A05F1 | \n", + "CI-W3A50A1 | \n", + "CI-W3A50A2 | \n", + "CI-W3A50A3 | \n", + "CI-W3A50P1 | \n", + "CI-W3A50T1 | \n", + "CI-W3A55P1 | \n", + "... | \n", + "CI-W3V33P1 | \n", + "CI-W3W01A1 | \n", + "CI-W3W01A2 | \n", + "CI-W3W01A3 | \n", + "CI-W3W01G1 | \n", + "CI-W3W01P1 | \n", + "CI-W3W01P2 | \n", + "CI-W3W03I1 | \n", + "CI-W3W03S1 | \n", + "timestamp | \n", + "
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | \n", + "87.999020 | \n", + "238.000000 | \n", + "100.442688 | \n", + "272.869100 | \n", + "0.083338 | \n", + "2.636171 | \n", + "589.246400 | \n", + "-0.923784 | \n", + "383.722400 | \n", + "-18.167961 | \n", + "... | \n", + "259.565500 | \n", + "0.008220 | \n", + "4.190174 | \n", + "376.848267 | \n", + "600.466900 | \n", + "-3.109598 | \n", + "0.221798 | \n", + "63.605830 | \n", + "1545.50293 | \n", + "2025-12-17 22:12:42 | \n", + "
| 1 | \n", + "87.999020 | \n", + "238.000000 | \n", + "100.442688 | \n", + "272.649200 | \n", + "0.083338 | \n", + "2.267340 | \n", + "618.462100 | \n", + "-0.771080 | \n", + "381.468872 | \n", + "-17.495136 | \n", + "... | \n", + "263.099854 | \n", + "0.008220 | \n", + "2.611867 | \n", + "435.797668 | \n", + "600.466900 | \n", + "-3.030156 | \n", + "0.153527 | \n", + "65.785706 | \n", + "1545.50293 | \n", + "2025-12-17 22:41:54 | \n", + "
| 2 | \n", + "86.997925 | \n", + "228.200012 | \n", + "100.442688 | \n", + "264.225372 | \n", + "0.082358 | \n", + "3.254068 | \n", + "444.800200 | \n", + "-0.789923 | \n", + "389.007800 | \n", + "-16.590466 | \n", + "... | \n", + "223.346313 | \n", + "0.085927 | \n", + "9.447197 | \n", + "343.596000 | \n", + "600.000000 | \n", + "-2.436767 | \n", + "0.350289 | \n", + "69.886520 | \n", + "1616.15491 | \n", + "2025-12-18 19:08:08 | \n", + "
| 3 | \n", + "86.997925 | \n", + "228.200012 | \n", + "100.442688 | \n", + "266.714172 | \n", + "0.082361 | \n", + "2.444070 | \n", + "481.586060 | \n", + "-0.551620 | \n", + "390.612854 | \n", + "-16.791473 | \n", + "... | \n", + "240.661469 | \n", + "0.085927 | \n", + "9.324739 | \n", + "462.062256 | \n", + "600.000000 | \n", + "-3.030156 | \n", + "0.208616 | \n", + "64.659730 | \n", + "1628.22876 | \n", + "2025-12-18 19:23:08 | \n", + "
| 4 | \n", + "91.991210 | \n", + "139.299988 | \n", + "100.442688 | \n", + "280.392334 | \n", + "0.082361 | \n", + "1.835279 | \n", + "436.144100 | \n", + "-0.486019 | \n", + "387.727000 | \n", + "-17.495136 | \n", + "... | \n", + "249.935165 | \n", + "0.059602 | \n", + "5.359922 | \n", + "367.250300 | \n", + "600.000000 | \n", + "-3.286316 | \n", + "0.276372 | \n", + "59.949337 | \n", + "1691.23462 | \n", + "2025-12-18 19:31:54 | \n", + "
| 5 | \n", + "90.001220 | \n", + "230.000000 | \n", + "100.442688 | \n", + "268.893158 | \n", + "0.083623 | \n", + "2.572147 | \n", + "410.169100 | \n", + "-0.929219 | \n", + "395.898200 | \n", + "-16.390797 | \n", + "... | \n", + "241.309967 | \n", + "0.002000 | \n", + "4.262301 | \n", + "340.296700 | \n", + "880.778200 | \n", + "-3.671064 | \n", + "0.248075 | \n", + "65.195390 | \n", + "1609.20154 | \n", + "2025-12-18 19:34:28 | \n", + "
| 6 | \n", + "90.001220 | \n", + "230.000000 | \n", + "100.442688 | \n", + "269.359000 | \n", + "0.083623 | \n", + "2.636187 | \n", + "417.679138 | \n", + "-0.837243 | \n", + "396.060272 | \n", + "-16.390797 | \n", + "... | \n", + "239.364624 | \n", + "0.002000 | \n", + "3.964616 | \n", + "318.547300 | \n", + "935.914368 | \n", + "-3.477627 | \n", + "0.248075 | \n", + "63.284638 | \n", + "1609.20154 | \n", + "2025-12-18 19:35:19 | \n", + "
| 7 | \n", + "90.001220 | \n", + "230.000000 | \n", + "100.442688 | \n", + "268.651978 | \n", + "0.083623 | \n", + "2.483914 | \n", + "404.910522 | \n", + "-0.906091 | \n", + "396.222473 | \n", + "-16.390797 | \n", + "... | \n", + "239.364624 | \n", + "0.002000 | \n", + "4.766942 | \n", + "314.721130 | \n", + "903.813232 | \n", + "-3.797625 | \n", + "0.248075 | \n", + "64.601974 | \n", + "1645.86389 | \n", + "2025-12-18 19:39:04 | \n", + "
| 8 | \n", + "90.001220 | \n", + "230.000000 | \n", + "100.442688 | \n", + "270.836426 | \n", + "0.083623 | \n", + "2.748308 | \n", + "403.442100 | \n", + "-0.939606 | \n", + "396.222473 | \n", + "-16.390797 | \n", + "... | \n", + "239.364624 | \n", + "0.001362 | \n", + "4.637836 | \n", + "325.616100 | \n", + "909.961060 | \n", + "-3.605707 | \n", + "0.248075 | \n", + "62.869644 | \n", + "1646.51428 | \n", + "2025-12-18 19:40:58 | \n", + "
| 9 | \n", + "90.001220 | \n", + "227.700012 | \n", + "100.442688 | \n", + "270.715637 | \n", + "0.089754 | \n", + "2.644230 | \n", + "425.803000 | \n", + "-1.007370 | \n", + "396.384521 | \n", + "-16.725641 | \n", + "... | \n", + "239.040222 | \n", + "0.001361 | \n", + "5.083293 | \n", + "349.286682 | \n", + "949.923500 | \n", + "-3.702983 | \n", + "0.208413 | \n", + "65.850296 | \n", + "1647.25537 | \n", + "2025-12-18 20:12:23 | \n", + "
| 10 | \n", + "90.001220 | \n", + "227.700012 | \n", + "100.442688 | \n", + "270.661438 | \n", + "0.078859 | \n", + "2.628080 | \n", + "435.462860 | \n", + "-0.962243 | \n", + "396.384521 | \n", + "-17.031452 | \n", + "... | \n", + "239.364441 | \n", + "0.108690 | \n", + "5.151842 | \n", + "353.761353 | \n", + "949.961060 | \n", + "-3.733788 | \n", + "0.207413 | \n", + "64.788740 | \n", + "1644.68042 | \n", + "2025-12-19 03:26:44 | \n", + "
| 11 | \n", + "90.001220 | \n", + "227.700012 | \n", + "100.442688 | \n", + "270.725159 | \n", + "0.078859 | \n", + "2.628080 | \n", + "424.227722 | \n", + "-0.827545 | \n", + "396.384521 | \n", + "-17.031452 | \n", + "... | \n", + "239.364441 | \n", + "0.108690 | \n", + "4.830516 | \n", + "353.761353 | \n", + "893.074000 | \n", + "-3.733788 | \n", + "0.207413 | \n", + "64.788740 | \n", + "1644.68042 | \n", + "2025-12-19 03:32:37 | \n", + "
| 12 | \n", + "90.001220 | \n", + "227.700012 | \n", + "100.442688 | \n", + "269.977020 | \n", + "0.078859 | \n", + "3.799854 | \n", + "350.998047 | \n", + "-0.901527 | \n", + "395.614441 | \n", + "-18.777557 | \n", + "... | \n", + "226.556274 | \n", + "0.108690 | \n", + "5.567447 | \n", + "312.856700 | \n", + "887.664734 | \n", + "-3.445201 | \n", + "0.188967 | \n", + "65.376144 | \n", + "1644.68042 | \n", + "2025-12-19 03:59:20 | \n", + "
| 13 | \n", + "90.001220 | \n", + "227.700012 | \n", + "100.442688 | \n", + "269.098000 | \n", + "0.078859 | \n", + "3.325234 | \n", + "401.663940 | \n", + "-0.960138 | \n", + "392.380127 | \n", + "-16.966602 | \n", + "... | \n", + "235.862518 | \n", + "0.025195 | \n", + "2.443661 | \n", + "305.058400 | \n", + "963.424100 | \n", + "-3.654345 | \n", + "0.188967 | \n", + "64.824660 | \n", + "1392.28394 | \n", + "2025-12-19 04:07:07 | \n", + "
| 14 | \n", + "89.000120 | \n", + "133.000000 | \n", + "100.442688 | \n", + "280.595900 | \n", + "0.078859 | \n", + "2.347593 | \n", + "453.182526 | \n", + "-0.409587 | \n", + "389.169952 | \n", + "-15.958172 | \n", + "... | \n", + "238.099854 | \n", + "0.025195 | \n", + "5.168004 | \n", + "417.250244 | \n", + "852.529200 | \n", + "-3.702983 | \n", + "0.268095 | \n", + "62.195198 | \n", + "1645.46326 | \n", + "2025-12-19 04:27:35 | \n", + "
| 15 | \n", + "91.002320 | \n", + "130.000000 | \n", + "100.442688 | \n", + "283.037842 | \n", + "0.109597 | \n", + "2.547736 | \n", + "364.069400 | \n", + "-0.737562 | \n", + "394.961900 | \n", + "-18.296043 | \n", + "... | \n", + "226.230900 | \n", + "0.073010 | \n", + "4.334429 | \n", + "338.391663 | \n", + "793.501953 | \n", + "-4.727626 | \n", + "0.003959 | \n", + "72.804596 | \n", + "1718.75586 | \n", + "2025-12-21 14:12:47 | \n", + "
16 rows × 33 columns
\n", + "