cropwise-api-client 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cropwise_api_client-0.1.0/.github/workflows/publish.yml +34 -0
- cropwise_api_client-0.1.0/.gitignore +27 -0
- cropwise_api_client-0.1.0/PKG-INFO +135 -0
- cropwise_api_client-0.1.0/README.md +109 -0
- cropwise_api_client-0.1.0/README.ru.md +108 -0
- cropwise_api_client-0.1.0/cropwise/__init__.py +12 -0
- cropwise_api_client-0.1.0/cropwise/client.py +611 -0
- cropwise_api_client-0.1.0/cropwise/exceptions.py +22 -0
- cropwise_api_client-0.1.0/cropwise/processing.py +73 -0
- cropwise_api_client-0.1.0/pyproject.toml +43 -0
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
name: Publish Python Distribution to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags:
|
|
6
|
+
- 'v*'
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
build-n-publish:
|
|
10
|
+
name: Build and publish Python distribution to PyPI
|
|
11
|
+
runs-on: ubuntu-latest
|
|
12
|
+
environment:
|
|
13
|
+
name: pypi
|
|
14
|
+
permissions:
|
|
15
|
+
id-token: write
|
|
16
|
+
contents: read
|
|
17
|
+
|
|
18
|
+
steps:
|
|
19
|
+
- name: Checkout source code
|
|
20
|
+
uses: actions/checkout@v4
|
|
21
|
+
|
|
22
|
+
- name: Set up Python
|
|
23
|
+
uses: actions/setup-python@v5
|
|
24
|
+
with:
|
|
25
|
+
python-version: '3.10'
|
|
26
|
+
|
|
27
|
+
- name: Install build tools
|
|
28
|
+
run: python -m pip install build
|
|
29
|
+
|
|
30
|
+
- name: Build distribution packages
|
|
31
|
+
run: python -m build
|
|
32
|
+
|
|
33
|
+
- name: Publish package to PyPI
|
|
34
|
+
uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Byte-compiled / optimized / DLL files
|
|
2
|
+
__pycache__/
|
|
3
|
+
*.py[cod]
|
|
4
|
+
*$py.class
|
|
5
|
+
|
|
6
|
+
# Data outputs & cache files
|
|
7
|
+
*.csv
|
|
8
|
+
*.gpkg
|
|
9
|
+
*.shp
|
|
10
|
+
|
|
11
|
+
# IDE configurations
|
|
12
|
+
.vscode/
|
|
13
|
+
.idea/
|
|
14
|
+
|
|
15
|
+
# Distribution / packaging files
|
|
16
|
+
build/
|
|
17
|
+
develop-eggs/
|
|
18
|
+
dist/
|
|
19
|
+
downloads/
|
|
20
|
+
eggs/
|
|
21
|
+
.eggs/
|
|
22
|
+
parts/
|
|
23
|
+
sdist/
|
|
24
|
+
var/
|
|
25
|
+
wheels/
|
|
26
|
+
share/python-wheels/
|
|
27
|
+
*.egg-info/
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: cropwise-api-client
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A Python client library for the Cropwise Operations API v3 with spatial GIS capabilities.
|
|
5
|
+
Project-URL: Homepage, https://github.com/CzendaZdenda/cropwise-api-client
|
|
6
|
+
Project-URL: Bug-Tracker, https://github.com/CzendaZdenda/cropwise-api-client
|
|
7
|
+
Author-email: CzendaZdenda <tramtara@seznam.cz>
|
|
8
|
+
License: MIT
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: Scientific/Engineering :: GIS
|
|
19
|
+
Requires-Python: >=3.8
|
|
20
|
+
Requires-Dist: pandas>=1.5.0
|
|
21
|
+
Requires-Dist: requests>=2.28.0
|
|
22
|
+
Provides-Extra: gis
|
|
23
|
+
Requires-Dist: geopandas>=0.12.0; extra == 'gis'
|
|
24
|
+
Requires-Dist: shapely>=2.0.0; extra == 'gis'
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# Cropwise API Client for Python
|
|
28
|
+
|
|
29
|
+
[Читать на русском](README.ru.md)
|
|
30
|
+
|
|
31
|
+
A Python client library wrapper for the **Cropwise Operations (Cropio) API v3** featuring automated pagination, request retries, and optional spatial GIS data processing capabilities.
|
|
32
|
+
|
|
33
|
+
> ⚠️ **Development Status: Beta**
|
|
34
|
+
> This library is currently in its **Beta stage**. It is fully functional for the implemented endpoints, but the codebase is actively growing. New Cropwise API endpoints will be added in future releases, and minor breaking changes to the interface may occur as the architecture matures.
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
## ✨ Supported API Endpoints & Features
|
|
38
|
+
|
|
39
|
+
This library provides direct access to specific Cropwise Operations API v3 endpoints, returning data structured as pandas DataFrames:
|
|
40
|
+
|
|
41
|
+
- **Core Infrastructure Directories:**
|
|
42
|
+
- `fields`
|
|
43
|
+
- `machines` & `machine_groups`
|
|
44
|
+
- `implements`
|
|
45
|
+
- `crops` & `work_types`
|
|
46
|
+
- `users`
|
|
47
|
+
- `agro_operations`
|
|
48
|
+
- `machine_tasks`
|
|
49
|
+
- `machine_task_agro_operation_mapping_items` (links between machine tasks and agrooperations)
|
|
50
|
+
- `machine_task_field_mapping_items` (links between machine tasks and fields)
|
|
51
|
+
- `gps_logger_data_items` (raw spatial GPS tracking points)
|
|
52
|
+
- `gps_logger_event_data_items` (machinery sensor telemetry logs, such as fuel levels or engine speeds)
|
|
53
|
+
- `history_items`
|
|
54
|
+
- `inventory_history_items` (audit history and version logs for core assets: Machines, Implements, Fields)
|
|
55
|
+
|
|
56
|
+
### GIS Export Extension
|
|
57
|
+
- Includes an optional `processing` module utilizing `geopandas` and `shapely` to compile multi-day or single-shift telemetry points into continuous `LineString` vector geometries saved directly into standard `GeoPackage (.gpkg)` layers.
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
## 📦 Installation
|
|
61
|
+
|
|
62
|
+
To install the core lightweight client for handling structured metadata tables only:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
pip install cropwise-api-client
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
To install the complete geospatial version containing the `processing` module:
|
|
69
|
+
*(Note: Windows users are highly recommended to run this package inside an **OSGeo4W Shell** or the integrated **QGIS Python Environment** to prevent spatial binary environment errors).*
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
pip install cropwise-api-client[gis]
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## 🚀 Quick Start
|
|
76
|
+
|
|
77
|
+
### 1. Initializing the Client (Recommended via Permanent Token)
|
|
78
|
+
|
|
79
|
+
Generate a permanent token inside your Cropwise Operations profile settings and use it for secure script initialization without exposing raw password strings in the codebase:
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from cropwise import CropwiseClient
|
|
83
|
+
|
|
84
|
+
# Initialize the client using a secure permanent user API token
|
|
85
|
+
client = CropwiseClient(token="your_token")
|
|
86
|
+
|
|
87
|
+
# Fetch all operational fields into a structured pandas DataFrame indexed by ID
|
|
88
|
+
df_fields = client.get_fields()
|
|
89
|
+
print(df_fields[['id', 'name']])
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### 2. Exporting Machinery Track to GeoPackage (.gpkg) for QGIS
|
|
93
|
+
|
|
94
|
+
Seamlessly download raw GPS tracking logs crossing multiple calendar days or overnight work shifts and compile them into a singular vector LineString layer saved straight to disk:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
from datetime import datetime
|
|
98
|
+
from pathlib import Path
|
|
99
|
+
from cropwise import CropwiseClient
|
|
100
|
+
from cropwise.processing import build_machine_track_gpkg
|
|
101
|
+
|
|
102
|
+
client = CropwiseClient(token="your_token")
|
|
103
|
+
|
|
104
|
+
# Extract telemetry points and write a vector LineString file for GIS mapping
|
|
105
|
+
build_machine_track_gpkg(
|
|
106
|
+
client=client,
|
|
107
|
+
machine_id=1299,
|
|
108
|
+
dt_from=datetime(2026, 10, 20, 20, 0, 0), # Night shift start
|
|
109
|
+
dt_to=datetime(2026, 10, 21, 8, 0, 0), # Night shift end
|
|
110
|
+
output_gpkg=Path("C:/GIS_Data/tracks/night_shift_1299.gpkg"),
|
|
111
|
+
machine_name="John Deere 8R"
|
|
112
|
+
)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### 3. Extracting Dynamic Telemetry and Sensor Logs
|
|
116
|
+
|
|
117
|
+
Extract specific telemetry sensor attributes across multiple machinery assets at once. The library will automatically flatten dynamic nested data attributes into native tabular columns:
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
from cropwise import CropwiseClient
|
|
121
|
+
|
|
122
|
+
client = CropwiseClient(token="your_token")
|
|
123
|
+
|
|
124
|
+
# Fetch precise fuel level and engine speed logs
|
|
125
|
+
df_telemetry = client.get_logger_event_data(
|
|
126
|
+
date_at="2026-10-23",
|
|
127
|
+
machine_ids=[101],
|
|
128
|
+
params=["fuel_level", "engine_speed", "pwr_ext"]
|
|
129
|
+
)
|
|
130
|
+
print(df_telemetry.head())
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## 📄 License
|
|
134
|
+
|
|
135
|
+
This library is distributed under the MIT License. See [LICENSE](LICENSE) for more details.
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# Cropwise API Client for Python
|
|
2
|
+
|
|
3
|
+
[Читать на русском](README.ru.md)
|
|
4
|
+
|
|
5
|
+
A Python client library wrapper for the **Cropwise Operations (Cropio) API v3** featuring automated pagination, request retries, and optional spatial GIS data processing capabilities.
|
|
6
|
+
|
|
7
|
+
> ⚠️ **Development Status: Beta**
|
|
8
|
+
> This library is currently in its **Beta stage**. It is fully functional for the implemented endpoints, but the codebase is actively growing. New Cropwise API endpoints will be added in future releases, and minor breaking changes to the interface may occur as the architecture matures.
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
## ✨ Supported API Endpoints & Features
|
|
12
|
+
|
|
13
|
+
This library provides direct access to specific Cropwise Operations API v3 endpoints, returning data structured as pandas DataFrames:
|
|
14
|
+
|
|
15
|
+
- **Core Infrastructure Directories:**
|
|
16
|
+
- `fields`
|
|
17
|
+
- `machines` & `machine_groups`
|
|
18
|
+
- `implements`
|
|
19
|
+
- `crops` & `work_types`
|
|
20
|
+
- `users`
|
|
21
|
+
- `agro_operations`
|
|
22
|
+
- `machine_tasks`
|
|
23
|
+
- `machine_task_agro_operation_mapping_items` (links between machine tasks and agrooperations)
|
|
24
|
+
- `machine_task_field_mapping_items` (links between machine tasks and fields)
|
|
25
|
+
- `gps_logger_data_items` (raw spatial GPS tracking points)
|
|
26
|
+
- `gps_logger_event_data_items` (machinery sensor telemetry logs, such as fuel levels or engine speeds)
|
|
27
|
+
- `history_items`
|
|
28
|
+
- `inventory_history_items` (audit history and version logs for core assets: Machines, Implements, Fields)
|
|
29
|
+
|
|
30
|
+
### GIS Export Extension
|
|
31
|
+
- Includes an optional `processing` module utilizing `geopandas` and `shapely` to compile multi-day or single-shift telemetry points into continuous `LineString` vector geometries saved directly into standard `GeoPackage (.gpkg)` layers.
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
## 📦 Installation
|
|
35
|
+
|
|
36
|
+
To install the core lightweight client for handling structured metadata tables only:
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install cropwise-api-client
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
To install the complete geospatial version containing the `processing` module:
|
|
43
|
+
*(Note: Windows users are highly recommended to run this package inside an **OSGeo4W Shell** or the integrated **QGIS Python Environment** to prevent spatial binary environment errors).*
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pip install cropwise-api-client[gis]
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## 🚀 Quick Start
|
|
50
|
+
|
|
51
|
+
### 1. Initializing the Client (Recommended via Permanent Token)
|
|
52
|
+
|
|
53
|
+
Generate a permanent token inside your Cropwise Operations profile settings and use it for secure script initialization without exposing raw password strings in the codebase:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from cropwise import CropwiseClient
|
|
57
|
+
|
|
58
|
+
# Initialize the client using a secure permanent user API token
|
|
59
|
+
client = CropwiseClient(token="your_token")
|
|
60
|
+
|
|
61
|
+
# Fetch all operational fields into a structured pandas DataFrame indexed by ID
|
|
62
|
+
df_fields = client.get_fields()
|
|
63
|
+
print(df_fields[['id', 'name']])
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### 2. Exporting Machinery Track to GeoPackage (.gpkg) for QGIS
|
|
67
|
+
|
|
68
|
+
Seamlessly download raw GPS tracking logs crossing multiple calendar days or overnight work shifts and compile them into a singular vector LineString layer saved straight to disk:
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from datetime import datetime
|
|
72
|
+
from pathlib import Path
|
|
73
|
+
from cropwise import CropwiseClient
|
|
74
|
+
from cropwise.processing import build_machine_track_gpkg
|
|
75
|
+
|
|
76
|
+
client = CropwiseClient(token="your_token")
|
|
77
|
+
|
|
78
|
+
# Extract telemetry points and write a vector LineString file for GIS mapping
|
|
79
|
+
build_machine_track_gpkg(
|
|
80
|
+
client=client,
|
|
81
|
+
machine_id=1299,
|
|
82
|
+
dt_from=datetime(2026, 10, 20, 20, 0, 0), # Night shift start
|
|
83
|
+
dt_to=datetime(2026, 10, 21, 8, 0, 0), # Night shift end
|
|
84
|
+
output_gpkg=Path("C:/GIS_Data/tracks/night_shift_1299.gpkg"),
|
|
85
|
+
machine_name="John Deere 8R"
|
|
86
|
+
)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### 3. Extracting Dynamic Telemetry and Sensor Logs
|
|
90
|
+
|
|
91
|
+
Extract specific telemetry sensor attributes across multiple machinery assets at once. The library will automatically flatten dynamic nested data attributes into native tabular columns:
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from cropwise import CropwiseClient
|
|
95
|
+
|
|
96
|
+
client = CropwiseClient(token="your_token")
|
|
97
|
+
|
|
98
|
+
# Fetch precise fuel level and engine speed logs
|
|
99
|
+
df_telemetry = client.get_logger_event_data(
|
|
100
|
+
date_at="2026-10-23",
|
|
101
|
+
machine_ids=[101],
|
|
102
|
+
params=["fuel_level", "engine_speed", "pwr_ext"]
|
|
103
|
+
)
|
|
104
|
+
print(df_telemetry.head())
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
## 📄 License
|
|
108
|
+
|
|
109
|
+
This library is distributed under the MIT License. See [LICENSE](LICENSE) for more details.
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
# Python-клиент для Cropwise API
|
|
2
|
+
|
|
3
|
+
[Read in English](README.md)
|
|
4
|
+
|
|
5
|
+
Библиотека-обертка на Python для работы с **Cropwise Operations (Cropio) API v3**, поддерживающая автоматическую пагинацию, повторные попытки запросов и опциональные возможности обработки пространственных ГИС-данных.
|
|
6
|
+
|
|
7
|
+
> ⚠️ **Статус разработки: Бета-версия**
|
|
8
|
+
> Данная библиотека находится на **стадии бета-тестирования**. Она полностью стабильна для уже реализованных эндпоинтов, но кодовая база продолжает активно развиваться. В будущих релизах будут добавлены новые эндпоинты Cropwise API, а по мере стабилизации архитектуры возможны незначительные изменения в синтаксисе методов.
|
|
9
|
+
|
|
10
|
+
## ✨ Поддерживаемые эндпоинты API и возможности
|
|
11
|
+
|
|
12
|
+
Библиотека предоставляет прямой доступ к определенным эндпоинтам Cropwise Operations API v3, возвращая структурированные данные в формате таблиц `pandas.DataFrame`:
|
|
13
|
+
|
|
14
|
+
- **Базовые справочники инфраструктуры:**
|
|
15
|
+
- `fields`
|
|
16
|
+
- `machines` и `machine_groups` (реестр техники и ее классификация)
|
|
17
|
+
- `implements` (прицепное и навесное оборудование)
|
|
18
|
+
- `crops` и `work_types` (справочники сельскохозяйственных культур и видов агроопераций)
|
|
19
|
+
- `users` (список пользователей системы внутри компании)
|
|
20
|
+
- `agro_operations`
|
|
21
|
+
- `machine_tasks`
|
|
22
|
+
- `machine_task_agro_operation_mapping_items` (связи между задачами техники и агрооперациями)
|
|
23
|
+
- `machine_task_field_mapping_items` (связи между задачами техники и конкретными полями)
|
|
24
|
+
- `gps_logger_data_items` (сырые пространственные GPS-координаты треков)
|
|
25
|
+
- `gps_logger_event_data_items` (телематические логи датчиков техники, такие как уровень топлива или обороты двигателя)
|
|
26
|
+
- `history_items`
|
|
27
|
+
- `inventory_history_items`
|
|
28
|
+
|
|
29
|
+
### Расширение для экспорта в ГИС
|
|
30
|
+
- Включает опциональный модуль `processing`, использующий возможности `geopandas` и `shapely` для компиляции многодневных треков или отдельных рабочих смен в непрерывные векторные геометрии `LineString` с их последующим сохранением в файлы стандартного формата `GeoPackage (.gpkg)` для QGIS и ArcGIS.
|
|
31
|
+
|
|
32
|
+
## 📦 Установка
|
|
33
|
+
|
|
34
|
+
По умолчанию устанавливается базовый легковесный клиент для работы исключительно со структурами данных и таблицами:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install cropwise-api-client
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Для установки полной геопространственной версии, содержащей ГИС-модуль `processing`:
|
|
41
|
+
*(Примечание: Пользователям операционной системы Windows настоятельно рекомендуется запускать этот пакет внутри **OSGeo4W Shell** или встроенного **Python-окружения QGIS**, чтобы избежать ошибок несовместимости скомпилированных бинарных ГИС-библиотек).*
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install cropwise-api-client[gis]
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## 🚀 Быстрый старт
|
|
48
|
+
|
|
49
|
+
### 1. Инициализация клиента (Рекомендуемый способ через постоянный токен)
|
|
50
|
+
|
|
51
|
+
Сгенерируйте постоянный API-токен в профиле Cropwise Operations и используйте его для безопасного подключения без раскрытия основного пароля аккаунта в коде:
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from cropwise import CropwiseClient
|
|
55
|
+
|
|
56
|
+
# Инициализация клиента с помощью постоянного токена пользователя
|
|
57
|
+
client = CropwiseClient(token="ваш_токен")
|
|
58
|
+
|
|
59
|
+
# Получение списка всех полей в виде DataFrame с индексацией по ID
|
|
60
|
+
df_fields = client.get_fields()
|
|
61
|
+
print(df_fields[['id', 'name']])
|
|
62
|
+
```
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
### 2. Экспорт трека техники в GeoPackage (.gpkg) для QGIS
|
|
66
|
+
|
|
67
|
+
Выгружайте сырые GPS-логи телеметрии, пересекающие границы календарных суток или ночные рабочие смены, с автоматической сборкой в единую векторную линию:
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
from datetime import datetime
|
|
71
|
+
from pathlib import Path
|
|
72
|
+
from cropwise import CropwiseClient
|
|
73
|
+
from cropwise.processing import build_machine_track_gpkg
|
|
74
|
+
|
|
75
|
+
client = CropwiseClient(token="ваш_токен")
|
|
76
|
+
|
|
77
|
+
# Извлечение точек телеметрии и запись слоя LineString прямо на диск
|
|
78
|
+
build_machine_track_gpkg(
|
|
79
|
+
client=client,
|
|
80
|
+
machine_id=1299,
|
|
81
|
+
dt_from=datetime(2026, 10, 20, 20, 0, 0), # Начало ночной смены
|
|
82
|
+
dt_to=datetime(2026, 10, 21, 8, 0, 0), # Конец ночной смены
|
|
83
|
+
output_gpkg=Path("C:/GIS_Data/tracks/night_shift_1299.gpkg"),
|
|
84
|
+
machine_name="John Deere 8R"
|
|
85
|
+
)
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### 3. Извлечение данных с датчиков телематики
|
|
89
|
+
|
|
90
|
+
Выгружайте показания конкретных датчиков. Библиотека автоматически развернет вложенные динамические структуры JSON в плоские классические колонки таблицы:
|
|
91
|
+
|
|
92
|
+
```python
|
|
93
|
+
from cropwise import CropwiseClient
|
|
94
|
+
|
|
95
|
+
client = CropwiseClient(token="ваш_токен")
|
|
96
|
+
|
|
97
|
+
# Получение логов уровня топлива, оборотов и внешнего питания для списка машин
|
|
98
|
+
df_telemetry = client.get_logger_event_data(
|
|
99
|
+
date_at="2026-10-23",
|
|
100
|
+
machine_ids=[101],
|
|
101
|
+
params=["fuel_level", "engine_speed", "pwr_ext"]
|
|
102
|
+
)
|
|
103
|
+
print(df_telemetry.head())
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## 📄 Лицензия
|
|
107
|
+
|
|
108
|
+
Проект распространяется под открытой лицензией MIT. Подробности см. в файле [LICENSE](LICENSE).
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# __init__.py
|
|
2
|
+
|
|
3
|
+
from .client import CropwiseClient
|
|
4
|
+
from .exceptions import CropwiseException, CropwiseAuthException, CropwiseApiException
|
|
5
|
+
|
|
6
|
+
# Define what is accessible when a user imports via "from cropwise import *"
|
|
7
|
+
__all__ = [
|
|
8
|
+
"CropwiseClient",
|
|
9
|
+
"CropwiseException",
|
|
10
|
+
"CropwiseAuthException",
|
|
11
|
+
"CropwiseApiException",
|
|
12
|
+
]
|
|
@@ -0,0 +1,611 @@
|
|
|
1
|
+
# cropwise/client.py
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
from typing import Dict, Any, List, Optional, Union
|
|
6
|
+
import requests
|
|
7
|
+
from requests.adapters import HTTPAdapter
|
|
8
|
+
from urllib3.util import Retry
|
|
9
|
+
import pandas as pd
|
|
10
|
+
from .exceptions import CropwiseAuthException, CropwiseApiException
|
|
11
|
+
|
|
12
|
+
# Set up library-specific logger
|
|
13
|
+
logger = logging.getLogger("cropwise")
|
|
14
|
+
|
|
15
|
+
# Standard Cropwise API response status mapping
|
|
16
|
+
RESPONSE_STATUS = {
|
|
17
|
+
400: ('Bad Request', 'The request could not be understood or was missing required parameters.'),
|
|
18
|
+
401: ('Unauthorized', 'Authentication failed or user doesn\'t have permissions for requested operation.'),
|
|
19
|
+
403: ('Forbidden', 'Access denied.'),
|
|
20
|
+
404: ('Not Found', 'Resource was not found.'),
|
|
21
|
+
422: ('Unprocessable Entity', 'The request was well-formed but failed due to semantic errors.'),
|
|
22
|
+
503: ('Service Unavailable', 'Service is temporarily unavailable (e.g. scheduled Platform Maintenance).')
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class CropwiseClient:
|
|
27
|
+
def __init__(
|
|
28
|
+
self,
|
|
29
|
+
token: Optional[str] = None,
|
|
30
|
+
email: Optional[str] = None,
|
|
31
|
+
password: Optional[str] = None,
|
|
32
|
+
server_url: str = 'https://operations.cropwise.com/api/v3'
|
|
33
|
+
):
|
|
34
|
+
"""
|
|
35
|
+
Python client wrapper for the Cropwise Operations API v3.
|
|
36
|
+
|
|
37
|
+
:param token: Permanent User API Token generated in the Cropwise profile (Recommended).
|
|
38
|
+
:param email: User login email (used if token is not provided).
|
|
39
|
+
:param password: User login password (used if token is not provided).
|
|
40
|
+
:param server_url: Base API server URL.
|
|
41
|
+
"""
|
|
42
|
+
self.server_url = server_url.rstrip('/')
|
|
43
|
+
self._token = token
|
|
44
|
+
self._email = email
|
|
45
|
+
self._password = password
|
|
46
|
+
|
|
47
|
+
# Initialize an HTTP session with built-in retry logic
|
|
48
|
+
self.session = requests.Session()
|
|
49
|
+
self._setup_retry_policy()
|
|
50
|
+
|
|
51
|
+
def _setup_retry_policy(self):
|
|
52
|
+
"""Configures automatic request retries for connection errors and unstable server states."""
|
|
53
|
+
retry_strategy = Retry(
|
|
54
|
+
total=5, # Maximum 5 retries before failing
|
|
55
|
+
backoff_factor=1, # Wait 1s, 2s, 4s, 8s, 16s between retries
|
|
56
|
+
status_forcelist=[500, 502, 503, 504], # Specific server error codes to retry
|
|
57
|
+
raise_on_status=False # Allow manual status check in _check_response
|
|
58
|
+
)
|
|
59
|
+
adapter = HTTPAdapter(max_retries=retry_strategy)
|
|
60
|
+
self.session.mount("http://", adapter)
|
|
61
|
+
self.session.mount("https://", adapter)
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def token(self) -> str:
|
|
65
|
+
"""Lazy loader that returns the permanent token or dynamically requests one using credentials."""
|
|
66
|
+
if not self._token:
|
|
67
|
+
if not self._email or not self._password:
|
|
68
|
+
raise CropwiseAuthException(
|
|
69
|
+
"Authentication error: You must provide either a permanent 'token' "
|
|
70
|
+
"or a valid 'email' and 'password' combination."
|
|
71
|
+
)
|
|
72
|
+
logger.info("Token not provided. Performing dynamic authentication via credentials...")
|
|
73
|
+
self._token = self._authenticate()
|
|
74
|
+
return self._token
|
|
75
|
+
|
|
76
|
+
def _authenticate(self) -> str:
|
|
77
|
+
"""Sends a POST request to obtain a temporary session token using email and password."""
|
|
78
|
+
url = f"{self.server_url}/users/sign_in"
|
|
79
|
+
|
|
80
|
+
payload = {
|
|
81
|
+
"user_login": {
|
|
82
|
+
"email": self._email,
|
|
83
|
+
"password": self._password
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
headers = {'Content-Type': 'application/json'}
|
|
87
|
+
|
|
88
|
+
try:
|
|
89
|
+
response = self.session.post(url, json=payload, headers=headers, timeout=15)
|
|
90
|
+
if response.status_code != 200:
|
|
91
|
+
raise CropwiseAuthException(f"Authentication failed with status code {response.status_code}.")
|
|
92
|
+
return response.json()['user_api_token']
|
|
93
|
+
except requests.RequestException as e:
|
|
94
|
+
raise CropwiseApiException(f"Network error during authentication process: {e}")
|
|
95
|
+
|
|
96
|
+
def _get_headers(self) -> Dict[str, str]:
|
|
97
|
+
"""Generates required HTTP headers for authorized API requests."""
|
|
98
|
+
return {
|
|
99
|
+
'Content-Type': 'application/json',
|
|
100
|
+
'X-User-Api-Token': self.token,
|
|
101
|
+
'Accept-Language': 'en'
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
def _check_response(self, response: requests.Response):
|
|
105
|
+
"""Validates HTTP response codes and throws clear exception messages if an error occurs."""
|
|
106
|
+
if response.status_code in (200, 201, 204):
|
|
107
|
+
return
|
|
108
|
+
|
|
109
|
+
status_info = RESPONSE_STATUS.get(response.status_code, ('Unknown Error', 'No further details available.'))
|
|
110
|
+
err_msg = f"HTTP {response.status_code} ({status_info[0]}): {status_info[1]}"
|
|
111
|
+
|
|
112
|
+
try:
|
|
113
|
+
server_errors = response.json().get('errors')
|
|
114
|
+
if server_errors:
|
|
115
|
+
err_msg += f" | Server context: {server_errors}"
|
|
116
|
+
except Exception:
|
|
117
|
+
pass
|
|
118
|
+
|
|
119
|
+
raise CropwiseApiException(err_msg)
|
|
120
|
+
|
|
121
|
+
def _get_page(self, endpoint: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
|
|
122
|
+
"""Performs a low-level HTTP GET request for a single data page."""
|
|
123
|
+
url = f'{self.server_url}/{endpoint}'
|
|
124
|
+
response = self.session.get(url, headers=self._get_headers(), params=params, timeout=30)
|
|
125
|
+
self._check_response(response)
|
|
126
|
+
return response.json()
|
|
127
|
+
|
|
128
|
+
def _get_all_pages(self, endpoint: str, filter_params: Optional[Dict[str, Any]] = None) -> List[Dict[str, Any]]:
|
|
129
|
+
"""Universal pagination engine that automatically iterates through all pages using from_id."""
|
|
130
|
+
all_data = []
|
|
131
|
+
last_id = 0
|
|
132
|
+
|
|
133
|
+
params = filter_params.copy() if filter_params else {}
|
|
134
|
+
|
|
135
|
+
while True:
|
|
136
|
+
params['from_id'] = last_id + 1
|
|
137
|
+
response_json = self._get_page(endpoint, params=params)
|
|
138
|
+
|
|
139
|
+
page_data = response_json.get('data')
|
|
140
|
+
meta_resp = response_json.get('meta', {}).get('response', {})
|
|
141
|
+
|
|
142
|
+
if not page_data or meta_resp.get('obtained_records', 0) == 0:
|
|
143
|
+
break
|
|
144
|
+
|
|
145
|
+
all_data.extend(page_data)
|
|
146
|
+
|
|
147
|
+
limit = meta_resp.get('limit', 0)
|
|
148
|
+
obtained_records = meta_resp.get('obtained_records', 0)
|
|
149
|
+
last_id = meta_resp.get('last_record_id', last_id)
|
|
150
|
+
|
|
151
|
+
# If the current page contains fewer items than the limit, we reached the end
|
|
152
|
+
if obtained_records < limit:
|
|
153
|
+
break
|
|
154
|
+
|
|
155
|
+
return all_data
|
|
156
|
+
|
|
157
|
+
def _prepare_filters(self, kwargs: Dict[str, Any]) -> Dict[str, str]:
|
|
158
|
+
"""Converts Python data types in kwargs to Cropwise API compatible string filters."""
|
|
159
|
+
filters = {}
|
|
160
|
+
for k, v in kwargs.items():
|
|
161
|
+
if v is not None:
|
|
162
|
+
if hasattr(v, 'strftime'):
|
|
163
|
+
filters[k] = v.strftime("%Y-%m-%dT%H:%M:%S")
|
|
164
|
+
elif isinstance(v, (list, tuple, set)):
|
|
165
|
+
filters[k] = ','.join([str(x) for x in v])
|
|
166
|
+
elif isinstance(v, bool):
|
|
167
|
+
filters[k] = str(v).lower()
|
|
168
|
+
else:
|
|
169
|
+
filters[k] = str(v)
|
|
170
|
+
return filters
|
|
171
|
+
|
|
172
|
+
def _to_dataframe(self, data: List[Dict[str, Any]], filter_params: Dict[str, Any]) -> pd.DataFrame:
|
|
173
|
+
"""Converts raw API list data into a standardized and sorted pandas DataFrame."""
|
|
174
|
+
if not data:
|
|
175
|
+
return pd.DataFrame()
|
|
176
|
+
|
|
177
|
+
df = pd.DataFrame(data)
|
|
178
|
+
|
|
179
|
+
# If the user didn't specify custom sorting, sort by 'id' (if the column exists)
|
|
180
|
+
if 'sort_by' not in filter_params and 'id' in df.columns:
|
|
181
|
+
return df.sort_values(by='id')
|
|
182
|
+
|
|
183
|
+
return df
|
|
184
|
+
|
|
185
|
+
def _request_and_parse(self, endpoint: str, kwargs: dict) -> pd.DataFrame:
|
|
186
|
+
"""Internal helper to process filters, fetch all pages, and return a DataFrame."""
|
|
187
|
+
filters = self._prepare_filters(kwargs)
|
|
188
|
+
data = self._get_all_pages(endpoint, filter_params=filters)
|
|
189
|
+
return self._to_dataframe(data, filters)
|
|
190
|
+
|
|
191
|
+
def _send_mutation(self, method: str, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
192
|
+
"""
|
|
193
|
+
Internal helper to handle POST, PUT, or PATCH mutation requests to the API.
|
|
194
|
+
"""
|
|
195
|
+
url = f'{self.server_url}/{endpoint}'
|
|
196
|
+
|
|
197
|
+
# Cropwise API expects the payload wrapped in a single singular-named root object key,
|
|
198
|
+
# but to keep the client simple and universal, we expect the user to pass the pre-formatted payload.
|
|
199
|
+
response = self.session.request(
|
|
200
|
+
method=method.upper(),
|
|
201
|
+
url=url,
|
|
202
|
+
headers=self._get_headers(),
|
|
203
|
+
json=data,
|
|
204
|
+
timeout=30
|
|
205
|
+
)
|
|
206
|
+
self._check_response(response)
|
|
207
|
+
return response.json() if response.status_code != 204 else {}
|
|
208
|
+
|
|
209
|
+
def get_fields(self, **kwargs) -> pd.DataFrame:
|
|
210
|
+
"""
|
|
211
|
+
Fetches all operational fields from the server.
|
|
212
|
+
|
|
213
|
+
Exact match:
|
|
214
|
+
id, field_group_id, name, additional_info, description, moisture_zone, idempotency_key,
|
|
215
|
+
external_id, cwp_id, field_type, parent_id, public_registry_key
|
|
216
|
+
|
|
217
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
|
|
218
|
+
created_at, updated_at
|
|
219
|
+
|
|
220
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
221
|
+
id, created_at, updated_at
|
|
222
|
+
"""
|
|
223
|
+
return self._request_and_parse('fields', kwargs)
|
|
224
|
+
|
|
225
|
+
def get_machines(self, **kwargs) -> pd.DataFrame:
|
|
226
|
+
"""
|
|
227
|
+
Fetches all registered agricultural machinery.
|
|
228
|
+
|
|
229
|
+
Exact match:
|
|
230
|
+
id, name, chassis_serial_number, engine_serial_number, inventory_number, machine_subtype,
|
|
231
|
+
machine_type, registration_number, year, machine_group_id, default_implement_id, default_driver_id,
|
|
232
|
+
machinery_model_id, external_id, phone_number, fuel_type_id, machinery_manufacturer_id
|
|
233
|
+
|
|
234
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
|
|
235
|
+
created_at, updated_at
|
|
236
|
+
|
|
237
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
238
|
+
id, name, created_at, updated_at
|
|
239
|
+
"""
|
|
240
|
+
return self._request_and_parse('machines', kwargs)
|
|
241
|
+
|
|
242
|
+
def get_crops(self, hidden: bool = False, **kwargs) -> pd.DataFrame:
|
|
243
|
+
"""
|
|
244
|
+
Fetches the agricultural crops.
|
|
245
|
+
|
|
246
|
+
Exact match:
|
|
247
|
+
id, standard_name, short_name, custom_name, additional_info, description, multi_year,
|
|
248
|
+
season_type, external_id, base_crop_id, productivity_estimate_crop_name, hidden
|
|
249
|
+
|
|
250
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
|
|
251
|
+
created_at, updated_at
|
|
252
|
+
|
|
253
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
254
|
+
id, created_at, updated_at
|
|
255
|
+
"""
|
|
256
|
+
# Mix explicit arguments with dynamic kwargs
|
|
257
|
+
kwargs['hidden'] = hidden
|
|
258
|
+
|
|
259
|
+
return self._request_and_parse('crops', kwargs)
|
|
260
|
+
|
|
261
|
+
def get_work_types(self, **kwargs) -> pd.DataFrame:
|
|
262
|
+
"""
|
|
263
|
+
Fetches work types with optional filters.
|
|
264
|
+
|
|
265
|
+
Exact match:
|
|
266
|
+
id, work_type_group_id, name, agri, application, sowing, harvesting, soil,
|
|
267
|
+
standard_name, hidden, external_id, disable_first_track_rule_coverage
|
|
268
|
+
|
|
269
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
|
|
270
|
+
created_at, updated_at
|
|
271
|
+
|
|
272
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
273
|
+
id, created_at, updated_at
|
|
274
|
+
"""
|
|
275
|
+
return self._request_and_parse('work_types', kwargs)
|
|
276
|
+
|
|
277
|
+
def get_machine_groups(self, **kwargs) -> pd.DataFrame:
|
|
278
|
+
"""
|
|
279
|
+
Fetches machinery groups with optional filters.
|
|
280
|
+
|
|
281
|
+
Exact match:
|
|
282
|
+
id, name, external_id
|
|
283
|
+
|
|
284
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
|
|
285
|
+
created_at, updated_at
|
|
286
|
+
|
|
287
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
288
|
+
id, created_at, updated_at
|
|
289
|
+
"""
|
|
290
|
+
return self._request_and_parse('machine_groups', kwargs)
|
|
291
|
+
|
|
292
|
+
def get_implements(self, **kwargs) -> pd.DataFrame:
|
|
293
|
+
"""
|
|
294
|
+
Fetches attached agricultural implements with optional filters.
|
|
295
|
+
|
|
296
|
+
Exact match:
|
|
297
|
+
id, implement_type, inventory_number, manufacturer, model, external_id, year,
|
|
298
|
+
registration_number, chassis_serial_number, virtual
|
|
299
|
+
|
|
300
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
|
|
301
|
+
created_at, updated_at
|
|
302
|
+
|
|
303
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
304
|
+
id, created_at, updated_at
|
|
305
|
+
"""
|
|
306
|
+
return self._request_and_parse('implements', kwargs)
|
|
307
|
+
|
|
308
|
+
def get_users(self, **kwargs) -> pd.DataFrame:
|
|
309
|
+
"""
|
|
310
|
+
Fetches company system users with optional filters.
|
|
311
|
+
|
|
312
|
+
Exact match:
|
|
313
|
+
id, username, email, notification_email, status, external_id, tax_identification_number,
|
|
314
|
+
individual_insurance_number, create_scout_report_outside_of_field
|
|
315
|
+
|
|
316
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
|
|
317
|
+
created_at, updated_at
|
|
318
|
+
|
|
319
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
320
|
+
id, created_at, updated_at
|
|
321
|
+
"""
|
|
322
|
+
return self._request_and_parse('users', kwargs)
|
|
323
|
+
|
|
324
|
+
def get_history_items(self, **kwargs) -> pd.DataFrame:
|
|
325
|
+
"""
|
|
326
|
+
Fetches crop rotation and historical land use records with optional filters.
|
|
327
|
+
|
|
328
|
+
Exact match:
|
|
329
|
+
id, field_id, active, crop_id, variety, till_type, productivity, sowing_date, harvesting_date,
|
|
330
|
+
description, additional_info, external_id, harvested_weight, yield_density, age_of_sugar_cane,
|
|
331
|
+
productivity_zone, grain_class, grain_humidity, grain_garbage_admixture, production_cycle_id,
|
|
332
|
+
field_shape_id, marketable_weight
|
|
333
|
+
|
|
334
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. sowing_date_gt):
|
|
335
|
+
sowing_date, harvesting_date, created_at, updated_at
|
|
336
|
+
|
|
337
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
338
|
+
id, created_at, updated_at
|
|
339
|
+
"""
|
|
340
|
+
return self._request_and_parse('history_items', kwargs)
|
|
341
|
+
|
|
342
|
+
def get_machine_tasks(self, **kwargs) -> pd.DataFrame:
|
|
343
|
+
"""
|
|
344
|
+
Fetches specific machinery field work tasks with optional filters.
|
|
345
|
+
|
|
346
|
+
Exact match (query params):
|
|
347
|
+
id, machine_id, driver_id, implement_id, season, work_type_id, status, external_id,
|
|
348
|
+
locked_to_edit, total_distance, work_distance, covered_area, work_area
|
|
349
|
+
|
|
350
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. season_gt):
|
|
351
|
+
season, total_distance, work_distance, covered_area, work_area, start_time, end_time,
|
|
352
|
+
created_at, updated_at, locked_at
|
|
353
|
+
|
|
354
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
355
|
+
id, created_at, updated_at
|
|
356
|
+
"""
|
|
357
|
+
return self._request_and_parse('machine_tasks', kwargs)
|
|
358
|
+
|
|
359
|
+
def get_agro_operations(self, **kwargs) -> pd.DataFrame:
|
|
360
|
+
"""
|
|
361
|
+
Fetches agricultural operations (agrooperations) with optional filters.
|
|
362
|
+
|
|
363
|
+
:param kwargs: Filters supported by Cropwise API (e.g., field_ids, crop_ids, date_start, date_end).
|
|
364
|
+
|
|
365
|
+
Exact match (query params):
|
|
366
|
+
id, field_id, status, season, work_type_id, field_shape_id, locked_to_edit,
|
|
367
|
+
external_id, agri_work_plan_id, calc_by, applications_type, history_item_id,
|
|
368
|
+
from_warehouse_id, covered_area_by_track, machine_work_area, planned_area,
|
|
369
|
+
completed_area, application_by_days, closure_reason_id
|
|
370
|
+
|
|
371
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. season_gt):
|
|
372
|
+
season, covered_area_by_track, machine_work_area, planned_area, completed_area,
|
|
373
|
+
planned_start_date, planned_end_date, created_at, updated_at, actual_start_datetime,
|
|
374
|
+
completed_datetime, locked_at
|
|
375
|
+
|
|
376
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
377
|
+
id, created_at, updated_at
|
|
378
|
+
"""
|
|
379
|
+
return self._request_and_parse('agro_operations', kwargs)
|
|
380
|
+
|
|
381
|
+
def get_machine_task_field_mapping_items(self, **kwargs) -> pd.DataFrame:
|
|
382
|
+
"""
|
|
383
|
+
Fetches mapping links between machinery tasks and specific fields.
|
|
384
|
+
|
|
385
|
+
Exact match (query params):
|
|
386
|
+
id, field_id, machine_task_id, history_item_id, covered_area, work_area
|
|
387
|
+
|
|
388
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
|
|
389
|
+
covered_area, work_area, created_at, updated_at
|
|
390
|
+
|
|
391
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
392
|
+
id, created_at, updated_at
|
|
393
|
+
"""
|
|
394
|
+
return self._request_and_parse('machine_task_field_mapping_items', kwargs)
|
|
395
|
+
|
|
396
|
+
def get_machine_task_agro_operation_mapping_items(self, **kwargs) -> pd.DataFrame:
|
|
397
|
+
"""
|
|
398
|
+
Fetches mapping links between machinery tasks and agrooperations.
|
|
399
|
+
|
|
400
|
+
Exact match (query params):
|
|
401
|
+
id, machine_task_id, agro_operation_id
|
|
402
|
+
|
|
403
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
|
|
404
|
+
created_at, updated_at
|
|
405
|
+
|
|
406
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
407
|
+
id, created_at, updated_at
|
|
408
|
+
"""
|
|
409
|
+
return self._request_and_parse('machine_task_agro_operation_mapping_items', kwargs)
|
|
410
|
+
|
|
411
|
+
def get_inventory_history_items(self, **kwargs) -> pd.DataFrame:
|
|
412
|
+
"""
|
|
413
|
+
Fetches the audit history and version logs for core assets (Machines, Implements, Fields).
|
|
414
|
+
|
|
415
|
+
This endpoint tracks lifecycle changes, updates, and versions of corporate inventory objects
|
|
416
|
+
to help understand which record state is currently active or what changed in the past.
|
|
417
|
+
|
|
418
|
+
Exact match (query params):
|
|
419
|
+
id, historyable_id, historyable_type, reason, description, available, hidden, external_id
|
|
420
|
+
|
|
421
|
+
Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
|
|
422
|
+
created_at, updated_at
|
|
423
|
+
|
|
424
|
+
Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
|
|
425
|
+
id, created_at, updated_at
|
|
426
|
+
"""
|
|
427
|
+
return self._request_and_parse('inventory_history_items', kwargs)
|
|
428
|
+
|
|
429
|
+
def get_logger_event_data(
|
|
430
|
+
self,
|
|
431
|
+
date_at: Optional[Any] = None,
|
|
432
|
+
from_time: Optional[Any] = None,
|
|
433
|
+
to_time: Optional[Any] = None,
|
|
434
|
+
machine_ids: Optional[Union[int, str, List[Union[int, str]]]] = None,
|
|
435
|
+
params: Optional[List[str]] = None,
|
|
436
|
+
**kwargs
|
|
437
|
+
) -> pd.DataFrame:
|
|
438
|
+
"""
|
|
439
|
+
Fetches telemetry logger event data items (sensors, fuel levels, ignition status).
|
|
440
|
+
|
|
441
|
+
You must provide EITHER 'date_at' OR BOTH 'from_time' and 'to_time'.
|
|
442
|
+
|
|
443
|
+
:param date_at: Target date (string "YYYY-MM-DD" or datetime/date object).
|
|
444
|
+
:param from_time: Start time of the interval (string ISO 8601 or datetime object).
|
|
445
|
+
:param to_time: End time of the interval (string ISO 8601 or datetime object).
|
|
446
|
+
:param machine_ids: Optional. Single ID (int/str) or a list/tuple/set of machine IDs.
|
|
447
|
+
:param params: Optional. List of specific sensor telemetry keys to extract.
|
|
448
|
+
"""
|
|
449
|
+
# Validate that either date_at or the time interval is provided
|
|
450
|
+
if not date_at and (not from_time or not to_time):
|
|
451
|
+
raise ValueError(
|
|
452
|
+
"Missing required parameters: You must provide either 'date_at' "
|
|
453
|
+
"or both 'from_time' and 'to_time' to specify the time range."
|
|
454
|
+
)
|
|
455
|
+
|
|
456
|
+
# Process and format time arguments into kwargs
|
|
457
|
+
if date_at is not None:
|
|
458
|
+
kwargs['date_at'] = date_at.strftime("%Y-%m-%d") if hasattr(date_at, 'strftime') else date_at
|
|
459
|
+
if from_time is not None:
|
|
460
|
+
kwargs['from_time'] = from_time.strftime("%Y-%m-%dT%H:%M:%S") if hasattr(from_time, 'strftime') else from_time
|
|
461
|
+
if to_time is not None:
|
|
462
|
+
kwargs['to_time'] = to_time.strftime("%Y-%m-%dT%H:%M:%S") if hasattr(to_time, 'strftime') else to_time
|
|
463
|
+
|
|
464
|
+
if machine_ids is not None:
|
|
465
|
+
kwargs['machine_ids'] = machine_ids
|
|
466
|
+
|
|
467
|
+
filters = self._prepare_filters(kwargs)
|
|
468
|
+
raw_data = self._get_all_pages('gps_logger_event_data_items', filter_params=filters)
|
|
469
|
+
|
|
470
|
+
if not raw_data:
|
|
471
|
+
return pd.DataFrame()
|
|
472
|
+
|
|
473
|
+
# Flattening dynamic telemetry sensor attributes into columns
|
|
474
|
+
flat_data = []
|
|
475
|
+
for row in raw_data:
|
|
476
|
+
item_id = row.get('id')
|
|
477
|
+
inner_data = row.get('data', {})
|
|
478
|
+
|
|
479
|
+
record = {
|
|
480
|
+
'id_e': item_id,
|
|
481
|
+
'time': pd.to_datetime(inner_data.get('time'), unit='s') if inner_data.get('time') else None
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
if params:
|
|
485
|
+
for p in params:
|
|
486
|
+
record[p] = inner_data.get(p)
|
|
487
|
+
else:
|
|
488
|
+
for k, v in inner_data.items():
|
|
489
|
+
if k != 'time':
|
|
490
|
+
record[k] = v
|
|
491
|
+
|
|
492
|
+
flat_data.append(record)
|
|
493
|
+
|
|
494
|
+
df = pd.DataFrame(flat_data)
|
|
495
|
+
if not df.empty and 'id_e' in df.columns:
|
|
496
|
+
df = df.set_index('id_e')
|
|
497
|
+
if 'time' in df.columns:
|
|
498
|
+
df = df.sort_values(by='time')
|
|
499
|
+
return df
|
|
500
|
+
|
|
501
|
+
def get_logger_track_data(
|
|
502
|
+
self,
|
|
503
|
+
date_at: Optional[Any] = None,
|
|
504
|
+
date_from: Optional[Any] = None,
|
|
505
|
+
date_to: Optional[Any] = None,
|
|
506
|
+
machine_ids: Optional[Union[int, str, List[Union[int, str]]]] = None,
|
|
507
|
+
**kwargs
|
|
508
|
+
) -> pd.DataFrame:
|
|
509
|
+
"""
|
|
510
|
+
Fetches raw spatial GPS tracking points for machinery.
|
|
511
|
+
|
|
512
|
+
You must provide EITHER 'date_at' OR BOTH 'date_from' and 'date_to'.
|
|
513
|
+
Supports precise datetime ranges (e.g., for night shifts crossing midnight).
|
|
514
|
+
|
|
515
|
+
:param date_at: Target date for a single day query (string "YYYY-MM-DD" or datetime/date object).
|
|
516
|
+
:param date_from: Start datetime for a precise range query (string ISO 8601 or datetime object).
|
|
517
|
+
:param date_to: End datetime for a precise range query (string ISO 8601 or datetime object).
|
|
518
|
+
:param machine_ids: Optional. Single ID (int/str) or a list/tuple/set of machine IDs.
|
|
519
|
+
"""
|
|
520
|
+
if not date_at and (not date_from or not date_to):
|
|
521
|
+
raise ValueError(
|
|
522
|
+
"Missing required parameters: You must provide either 'date_at' "
|
|
523
|
+
"or both 'date_from' and 'date_to' to specify the time range."
|
|
524
|
+
)
|
|
525
|
+
|
|
526
|
+
if machine_ids is not None:
|
|
527
|
+
kwargs['machine_ids'] = machine_ids
|
|
528
|
+
|
|
529
|
+
# Scenario 1: Precise datetime range query (Handles shifts like 20:00 to 08:00)
|
|
530
|
+
if date_from and date_to:
|
|
531
|
+
# Keep full datetime precision for later filtering
|
|
532
|
+
ts_from = pd.to_datetime(date_from)
|
|
533
|
+
ts_to = pd.to_datetime(date_to)
|
|
534
|
+
|
|
535
|
+
if ts_from > ts_to:
|
|
536
|
+
raise ValueError("'date_from' cannot be later than 'date_to'.")
|
|
537
|
+
|
|
538
|
+
logger.info(f"Fetching precise GPS tracks interval from {ts_from} to {ts_to}...")
|
|
539
|
+
|
|
540
|
+
all_dfs = []
|
|
541
|
+
# Generate calendar days that need to be requested from Cropwise API
|
|
542
|
+
for current_date in pd.date_range(ts_from.date(), ts_to.date()):
|
|
543
|
+
day_str = current_date.strftime("%Y-%m-%d")
|
|
544
|
+
day_kwargs = kwargs.copy()
|
|
545
|
+
day_kwargs['date_at'] = day_str
|
|
546
|
+
|
|
547
|
+
filters = self._prepare_filters(day_kwargs)
|
|
548
|
+
data = self._get_all_pages('gps_logger_data_items', filter_params=filters)
|
|
549
|
+
day_df = self._to_dataframe(data, filters)
|
|
550
|
+
|
|
551
|
+
if not day_df.empty:
|
|
552
|
+
all_dfs.append(day_df)
|
|
553
|
+
|
|
554
|
+
if not all_dfs:
|
|
555
|
+
return pd.DataFrame()
|
|
556
|
+
|
|
557
|
+
df = pd.concat(all_dfs)
|
|
558
|
+
|
|
559
|
+
# Temporary standardizations needed before filtering by time
|
|
560
|
+
if 'time' in df.columns:
|
|
561
|
+
df['local_time'] = pd.to_datetime(df['time']).dt.tz_localize(None)
|
|
562
|
+
# CRITICAL STEP: Crop precise shift boundaries inside Python
|
|
563
|
+
df = df[(df['local_time'] >= ts_from) & (df['local_time'] <= ts_to)]
|
|
564
|
+
|
|
565
|
+
# Scenario 2: Single calendar day query (Standard mode)
|
|
566
|
+
else:
|
|
567
|
+
kwargs['date_at'] = date_at.strftime("%Y-%m-%d") if hasattr(date_at, 'strftime') else date_at
|
|
568
|
+
filters = self._prepare_filters(kwargs)
|
|
569
|
+
data = self._get_all_pages('gps_logger_data_items', filter_params=filters)
|
|
570
|
+
df = self._to_dataframe(data, filters)
|
|
571
|
+
if not df.empty and 'time' in df.columns:
|
|
572
|
+
df['local_time'] = pd.to_datetime(df['time']).dt.tz_localize(None)
|
|
573
|
+
|
|
574
|
+
# Final Post-processing and GIS optimization
|
|
575
|
+
if not df.empty:
|
|
576
|
+
if 'long' in df.columns:
|
|
577
|
+
df = df.rename(columns={'long': 'lon'})
|
|
578
|
+
if 'id' in df.columns:
|
|
579
|
+
df = df.rename(columns={'id': 'id_t'}).set_index('id_t')
|
|
580
|
+
if 'time' in df.columns:
|
|
581
|
+
df = df.sort_values(by='time')
|
|
582
|
+
|
|
583
|
+
return df
|
|
584
|
+
|
|
585
|
+
def create_object(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
586
|
+
"""
|
|
587
|
+
Creates a new object (e.g., machine_tasks, machine_task_field_mapping_items) on the server.
|
|
588
|
+
|
|
589
|
+
:param endpoint: The API collection name (e.g., 'machine_tasks').
|
|
590
|
+
:param data: Dictionary containing object attributes.
|
|
591
|
+
:return: Server response as a dictionary.
|
|
592
|
+
"""
|
|
593
|
+
# As per Cropwise API v3 docs, the payload must be wrapped in a "data" root key
|
|
594
|
+
payload = {"data": data}
|
|
595
|
+
|
|
596
|
+
return self._send_mutation('POST', endpoint, payload)
|
|
597
|
+
|
|
598
|
+
def update_object(self, endpoint: str, object_id: Union[int, str], data: Dict[str, Any]) -> Dict[str, Any]:
|
|
599
|
+
"""
|
|
600
|
+
Updates an existing object using PUT semantics.
|
|
601
|
+
|
|
602
|
+
:param endpoint: The API collection name (e.g., 'machine_tasks').
|
|
603
|
+
:param object_id: Unique identifier of the resource.
|
|
604
|
+
:param data: Dictionary containing updated object attributes.
|
|
605
|
+
:return: Server response as a dictionary.
|
|
606
|
+
"""
|
|
607
|
+
# Standardizing payload structure with "data" root key for mutations
|
|
608
|
+
payload = {"data": data}
|
|
609
|
+
|
|
610
|
+
full_endpoint = f"{endpoint}/{object_id}"
|
|
611
|
+
return self._send_mutation('PUT', full_endpoint, payload)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
class CropwiseException(Exception):
|
|
2
|
+
"""
|
|
3
|
+
Base exception class for the Cropwise API client library.
|
|
4
|
+
All custom library exceptions inherit from this class.
|
|
5
|
+
"""
|
|
6
|
+
pass
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class CropwiseAuthException(CropwiseException):
|
|
10
|
+
"""
|
|
11
|
+
Raised when authentication fails.
|
|
12
|
+
Occurs due to invalid credentials, missing tokens, or insufficient permissions.
|
|
13
|
+
"""
|
|
14
|
+
pass
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CropwiseApiException(CropwiseException):
|
|
18
|
+
"""
|
|
19
|
+
Raised when the Cropwise server returns an API error response.
|
|
20
|
+
Handles standard HTTP error statuses such as 4xx and 5xx responses.
|
|
21
|
+
"""
|
|
22
|
+
pass
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
import logging
|
|
3
|
+
from typing import Optional
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import geopandas as gpd
|
|
6
|
+
from shapely.geometry import LineString
|
|
7
|
+
from .client import CropwiseClient
|
|
8
|
+
|
|
9
|
+
# Set up library-specific logger
|
|
10
|
+
logger = logging.getLogger("cropwise")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def build_machine_track_gpkg(
|
|
14
|
+
client: CropwiseClient,
|
|
15
|
+
machine_id: int,
|
|
16
|
+
dt_from: datetime,
|
|
17
|
+
dt_to: datetime,
|
|
18
|
+
output_gpkg: Path | str,
|
|
19
|
+
machine_name: Optional[str] = None
|
|
20
|
+
) -> bool:
|
|
21
|
+
"""
|
|
22
|
+
Fetches raw telemetry points from the Cropwise API across a date range and constructs
|
|
23
|
+
a continuous vector LineString layer saved directly into a GeoPackage (.gpkg) file for QGIS.
|
|
24
|
+
|
|
25
|
+
:param client: An instance of CropwiseClient.
|
|
26
|
+
:param machine_id: ID of the machinery.
|
|
27
|
+
:param dt_from: Start datetime of the track period (supports custom shifts).
|
|
28
|
+
:param dt_to: End datetime of the track period (supports custom shifts).
|
|
29
|
+
:param output_gpkg: Path destination (Path object or string) for the final GeoPackage file.
|
|
30
|
+
:param machine_name: Optional machine label metadata to store inside the layer attributes.
|
|
31
|
+
:return: True if the file was generated successfully, False otherwise.
|
|
32
|
+
"""
|
|
33
|
+
# Ensure output_gpkg is a Path object for safe manipulation
|
|
34
|
+
output_gpkg = Path(output_gpkg)
|
|
35
|
+
|
|
36
|
+
# REFACTORING ADVANTAGE:
|
|
37
|
+
# Our new client already handles multi-day range queries, token refresh,
|
|
38
|
+
# chronological sorting, and precise datetime cropping internally!
|
|
39
|
+
df_filtered = client.get_logger_track_data(
|
|
40
|
+
date_from=dt_from,
|
|
41
|
+
date_to=dt_to,
|
|
42
|
+
machine_ids=machine_id
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
# In our new client, the DataFrame index becomes 'id_t', so we check length or emptiness
|
|
46
|
+
if df_filtered.empty or len(df_filtered) < 2:
|
|
47
|
+
logger.warning(
|
|
48
|
+
f"Insufficient spatial data ({len(df_filtered)} points) found "
|
|
49
|
+
f"for machine ID {machine_id} within the specified timeframe."
|
|
50
|
+
)
|
|
51
|
+
return False
|
|
52
|
+
|
|
53
|
+
# Convert pandas DataFrame to vector GeoDataFrame (WGS 84 / EPSG:4326 standard GPS CRS)
|
|
54
|
+
gdf_points = gpd.GeoDataFrame(
|
|
55
|
+
df_filtered,
|
|
56
|
+
geometry=gpd.points_from_xy(df_filtered["lon"], df_filtered["lat"]),
|
|
57
|
+
crs="EPSG:4326"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
# Aggregate coordinates into a single LineString vector geometry
|
|
61
|
+
track_line = LineString(gdf_points["geometry"].tolist())
|
|
62
|
+
|
|
63
|
+
gdf_line = gpd.GeoDataFrame({
|
|
64
|
+
"machine_id": [machine_id],
|
|
65
|
+
"date_from": [dt_from.isoformat()],
|
|
66
|
+
"date_to": [dt_to.isoformat()],
|
|
67
|
+
"machine_name": [machine_name],
|
|
68
|
+
}, geometry=[track_line], crs="EPSG:4326")
|
|
69
|
+
|
|
70
|
+
# The name of the file acts as the default vector layer name inside QGIS
|
|
71
|
+
gdf_line.to_file(output_gpkg, driver="GPKG", layer=output_gpkg.stem)
|
|
72
|
+
logger.info(f"Spatial machinery track successfully generated and saved to: {output_gpkg}")
|
|
73
|
+
return True
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "cropwise-api-client"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A Python client library for the Cropwise Operations API v3 with spatial GIS capabilities."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.8"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "CzendaZdenda", email = "tramtara@seznam.cz" }
|
|
14
|
+
]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.8",
|
|
19
|
+
"Programming Language :: Python :: 3.9",
|
|
20
|
+
"Programming Language :: Python :: 3.10",
|
|
21
|
+
"Programming Language :: Python :: 3.11",
|
|
22
|
+
"Programming Language :: Python :: 3.12",
|
|
23
|
+
"License :: OSI Approved :: MIT License",
|
|
24
|
+
"Operating System :: OS Independent",
|
|
25
|
+
"Topic :: Scientific/Engineering :: GIS",
|
|
26
|
+
]
|
|
27
|
+
dependencies = [
|
|
28
|
+
"requests>=2.28.0",
|
|
29
|
+
"pandas>=1.5.0"
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.optional-dependencies]
|
|
33
|
+
gis = [
|
|
34
|
+
"geopandas>=0.12.0",
|
|
35
|
+
"shapely>=2.0.0"
|
|
36
|
+
]
|
|
37
|
+
|
|
38
|
+
[project.urls]
|
|
39
|
+
Homepage = "https://github.com/CzendaZdenda/cropwise-api-client"
|
|
40
|
+
Bug-Tracker = "https://github.com/CzendaZdenda/cropwise-api-client"
|
|
41
|
+
|
|
42
|
+
[tool.hatch.build.targets.wheel]
|
|
43
|
+
packages = ["cropwise"]
|