cropwise-api-client 0.1.6__tar.gz → 0.1.7__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: cropwise-api-client
3
- Version: 0.1.6
3
+ Version: 0.1.7
4
4
  Summary: A Python client library for the Cropwise Operations API v3 with spatial GIS capabilities.
5
5
  Project-URL: Homepage, https://github.com/CzendaZdenda/cropwise-api-client
6
6
  Project-URL: Bug-Tracker, https://github.com/CzendaZdenda/cropwise-api-client
@@ -128,6 +128,50 @@ df_telemetry = client.get_logger_event_data(
128
128
  print(df_telemetry.head())
129
129
  ```
130
130
 
131
+ ### 4. Update Additional Objects Map Display (Line Width and Color)
132
+
133
+ Change line width and color of specific Additonal objects:
134
+
135
+ ```python
136
+ from cropwise import CropwiseClient
137
+
138
+ client = CropwiseClient(token="your_token")
139
+
140
+ # Get additional objects with type = "channels"
141
+ objects_df = client.get_additional_objects(object_type="channels").set_index('id')
142
+
143
+ data = {
144
+ "line_width": 4,
145
+ "line_color": "#00aeff",
146
+ }
147
+
148
+ # Update objects
149
+ for i in objects_df.index.to_list():
150
+ print(objects_df.loc[i]['name'])
151
+ client.update_object(endpoint='additional_objects', object_id=i, data=data)
152
+ ```
153
+
154
+ ### 5. Delete Additional Objects (Temporary Roads)
155
+
156
+ Remove specific additional objects from the server by their type:
157
+
158
+ ```python
159
+ from cropwise import CropwiseClient
160
+
161
+ client = CropwiseClient(token="your_token")
162
+
163
+ # Get additional objects with type = "temporary_roads"
164
+ objects_df = client.get_additional_objects(object_type="temporary_roads").set_index('id')
165
+
166
+ # Delete objects from the server
167
+ for object_id in objects_df.index.to_list():
168
+ object_name = objects_df.loc[object_id]['name']
169
+ print(f"Deleting object: {object_name} (ID: {object_id})")
170
+
171
+ # Remove the object using the DELETE method
172
+ client.delete_object(endpoint='additional_objects', object_id=object_id)
173
+ ```
174
+
131
175
  ## 📄 License
132
176
 
133
177
  This library is distributed under the MIT License. See [LICENSE](LICENSE) for more details.
@@ -102,6 +102,50 @@ df_telemetry = client.get_logger_event_data(
102
102
  print(df_telemetry.head())
103
103
  ```
104
104
 
105
+ ### 4. Update Additional Objects Map Display (Line Width and Color)
106
+
107
+ Change line width and color of specific Additonal objects:
108
+
109
+ ```python
110
+ from cropwise import CropwiseClient
111
+
112
+ client = CropwiseClient(token="your_token")
113
+
114
+ # Get additional objects with type = "channels"
115
+ objects_df = client.get_additional_objects(object_type="channels").set_index('id')
116
+
117
+ data = {
118
+ "line_width": 4,
119
+ "line_color": "#00aeff",
120
+ }
121
+
122
+ # Update objects
123
+ for i in objects_df.index.to_list():
124
+ print(objects_df.loc[i]['name'])
125
+ client.update_object(endpoint='additional_objects', object_id=i, data=data)
126
+ ```
127
+
128
+ ### 5. Delete Additional Objects (Temporary Roads)
129
+
130
+ Remove specific additional objects from the server by their type:
131
+
132
+ ```python
133
+ from cropwise import CropwiseClient
134
+
135
+ client = CropwiseClient(token="your_token")
136
+
137
+ # Get additional objects with type = "temporary_roads"
138
+ objects_df = client.get_additional_objects(object_type="temporary_roads").set_index('id')
139
+
140
+ # Delete objects from the server
141
+ for object_id in objects_df.index.to_list():
142
+ object_name = objects_df.loc[object_id]['name']
143
+ print(f"Deleting object: {object_name} (ID: {object_id})")
144
+
145
+ # Remove the object using the DELETE method
146
+ client.delete_object(endpoint='additional_objects', object_id=object_id)
147
+ ```
148
+
105
149
  ## 📄 License
106
150
 
107
151
  This library is distributed under the MIT License. See [LICENSE](LICENSE) for more details.
@@ -103,6 +103,50 @@ df_telemetry = client.get_logger_event_data(
103
103
  print(df_telemetry.head())
104
104
  ```
105
105
 
106
+ ### 4. Обновление отображение на картах дополнительных объектов (ширина и цвет линий)
107
+
108
+ Изменение ширины и цвета линий для конкретных дополнительных объектов:
109
+
110
+ ```python
111
+ from cropwise import CropwiseClient
112
+
113
+ client = CropwiseClient(token="your_token")
114
+
115
+ # Получение дополнительных объектов с типом "каналы"
116
+ objects_df = client.get_additional_objects(object_type="каналы").set_index('id')
117
+
118
+ data = {
119
+ "line_width": 4,
120
+ "line_color": "#00aeff",
121
+ }
122
+
123
+ # Обновление объектов
124
+ for i in objects_df.index.to_list():
125
+ print(objects_df.loc[i]['name'])
126
+ client.update_object(endpoint='additional_objects', object_id=i, data=data)
127
+ ```
128
+
129
+ ### 5. Удаление дополнительных объектов (временные дороги)
130
+
131
+ Получение дополнительных объектов с типом "временные дороги":
132
+
133
+ ```python
134
+ from cropwise import CropwiseClient
135
+
136
+ client = CropwiseClient(token="your_token")
137
+
138
+ # Получение дополнительных объектов с типом "канвременные дорогиалы"
139
+ objects_df = client.get_additional_objects(object_type="временные дороги").set_index('id')
140
+
141
+ # Удаление объектов с сервера
142
+ for object_id in objects_df.index.to_list():
143
+ object_name = objects_df.loc[object_id]['name']
144
+ print(f"Удаление объекта: {object_name} (ID: {object_id})")
145
+
146
+ # Удаление объекта с помощью метода DELETE
147
+ client.delete_object(endpoint='additional_objects', object_id=object_id)
148
+ ```
149
+
106
150
  ## 📄 Лицензия
107
151
 
108
152
  Проект распространяется под открытой лицензией MIT. Подробности см. в файле [LICENSE](LICENSE).
@@ -1,7 +1,7 @@
1
1
  # __init__.py
2
2
 
3
3
  from .client import CropwiseClient
4
- from .exceptions import CropwiseException, CropwiseAuthException, CropwiseApiException
4
+ from .exceptions import CropwiseException, CropwiseAuthException, CropwiseApiException, CropwiseOdometerDuplicateError
5
5
 
6
6
  # Define what is accessible when a user imports via "from cropwise import *"
7
7
  __all__ = [
@@ -9,4 +9,5 @@ __all__ = [
9
9
  "CropwiseException",
10
10
  "CropwiseAuthException",
11
11
  "CropwiseApiException",
12
+ "CropwiseOdometerDuplicateError"
12
13
  ]
@@ -1,13 +1,14 @@
1
1
  # cropwise/client.py
2
2
 
3
3
  import json
4
+ from datetime import date, datetime
4
5
  import logging
5
6
  from typing import Dict, Any, List, Optional, Union
6
7
  import requests
7
8
  from requests.adapters import HTTPAdapter
8
9
  from urllib3.util import Retry
9
10
  import pandas as pd
10
- from .exceptions import CropwiseAuthException, CropwiseApiException
11
+ from .exceptions import CropwiseAuthException, CropwiseApiException, CropwiseValueError, CropwiseOdometerDuplicateError
11
12
 
12
13
  # Set up library-specific logger
13
14
  logger = logging.getLogger("cropwise")
@@ -29,7 +30,8 @@ class CropwiseClient:
29
30
  token: Optional[str] = None,
30
31
  email: Optional[str] = None,
31
32
  password: Optional[str] = None,
32
- server_url: str = 'https://operations.cropwise.com/api/v3'
33
+ server_url: str = 'https://operations.cropwise.com/api/v3',
34
+ timezone_offset: str = "+0000"
33
35
  ):
34
36
  """
35
37
  Python client wrapper for the Cropwise Operations API v3.
@@ -38,11 +40,13 @@ class CropwiseClient:
38
40
  :param email: User login email (used if token is not provided).
39
41
  :param password: User login password (used if token is not provided).
40
42
  :param server_url: Base API server URL.
43
+ :param timezone_offset: Stores company timezone offset (e.g. "+0200" for Kaliningrad).
41
44
  """
42
45
  self.server_url = server_url.rstrip('/')
43
46
  self._token = token
44
47
  self._email = email
45
48
  self._password = password
49
+ self.timezone_offset = timezone_offset
46
50
 
47
51
  # Initialize an HTTP session with built-in retry logic
48
52
  self.session = requests.Session()
@@ -190,7 +194,7 @@ class CropwiseClient:
190
194
 
191
195
  def _send_mutation(self, method: str, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
192
196
  """
193
- Internal helper to handle POST, PUT, or PATCH mutation requests to the API.
197
+ Internal helper to handle POST, PUT, PATCH or DELETE mutation requests to the API.
194
198
  """
195
199
  url = f'{self.server_url}/{endpoint}'
196
200
 
@@ -582,6 +586,22 @@ class CropwiseClient:
582
586
 
583
587
  return df
584
588
 
589
+ def get_additional_objects(self, **kwargs) -> pd.DataFrame:
590
+ """
591
+ Get additional objects with optional filters.
592
+
593
+ Exact match:
594
+ id, field_group_id, name, object_type, additional_info, description, geometry_type,
595
+ administrative_area_name, subadministrative_area_name, locality, external_id
596
+
597
+ Comparison (append _eq, _gt, _gt_eq, _lt or _lt_eq to attribute, e.g. created_at_gt):
598
+ calculated_area, created_at, updated_at
599
+
600
+ Sorting (sort_by=<attribute>_<asc|desc>, e.g. sort_by=created_at_desc):
601
+ id, created_at, updated_at
602
+ """
603
+ return self._request_and_parse('additional_objects', kwargs)
604
+
585
605
  def create_object(self, endpoint: str, data: Dict[str, Any]) -> Dict[str, Any]:
586
606
  """
587
607
  Creates a new object (e.g., machine_tasks, machine_task_field_mapping_items) on the server.
@@ -608,4 +628,95 @@ class CropwiseClient:
608
628
  payload = {"data": data}
609
629
 
610
630
  full_endpoint = f"{endpoint}/{object_id}"
611
- return self._send_mutation('PUT', full_endpoint, payload)
631
+ return self._send_mutation('PUT', full_endpoint, payload)
632
+
633
+ def delete_object(self, endpoint: str, object_id: Union[int, str]) -> Dict[str, Any]:
634
+ """
635
+ Deletes an existing object on the server using the HTTP DELETE method.
636
+
637
+ :param endpoint: The API collection name (e.g., 'additional_objects').
638
+ :param object_id: Unique identifier of the resource to be deleted.
639
+ :return: Server response as a dictionary.
640
+ """
641
+ full_endpoint = f"{endpoint}/{object_id}"
642
+ return self._send_mutation('DELETE', full_endpoint, data={})
643
+
644
+ def create_odometer_state(
645
+ self,
646
+ machine_id: int,
647
+ date_at: Union[datetime, date],
648
+ mileage: Optional[float] = None,
649
+ work_hours: Optional[float] = None
650
+ ) -> Dict[str, Any]:
651
+ """
652
+ Creates a new odometer state record (mileage and/or work hours) for a specific machine.
653
+
654
+ Date or Datetime:
655
+ -----------------
656
+ To ensure your readings appear correctly in the regional web interface without shifting
657
+ to the previous day, this method appends the client's `timezone_offset` (e.g., "+0100"
658
+ for Copenhagen, Denmark) to the formatted timestamp.
659
+
660
+ 1. Date:
661
+ Automatically converted to 'YYYY-MM-DD 00:00:00 +XXXX' using your client's timezone.
662
+
663
+ 2. Datetime:
664
+ Formatted as 'YYYY-MM-DD HH:MM:SS +XXXX' using your client's timezone.
665
+
666
+ :param machine_id: Unique identifier of the machine (Machine ID).
667
+ :param date_at: Target time or date for the entry. Supports 'datetime' and 'date'.
668
+ :param mileage: Distance counter value (manual_distance in km). Optional.
669
+ :param work_hours: Engine hours duration (manual_engine_work_duration in hours). Optional.
670
+ :return: Server response parsed as a dictionary.
671
+ :raises CropwiseValueError: If telemetry inputs or date types are invalid.
672
+ :raises CropwiseOdometerDuplicateError: If a record already exists at the given timestamp.
673
+
674
+ """
675
+ # Validate input telemetry data
676
+ if mileage is None and work_hours is None:
677
+ raise CropwiseValueError("You must provide either 'mileage' or 'work_hours' to save an odometer state.")
678
+
679
+ # Format measuring time keeping client timezone offset in mind
680
+ if isinstance(date_at, datetime):
681
+ # If the object is timezone-aware, extract its own offset, otherwise append client's global offset
682
+ if date_at.tzinfo is not None:
683
+ time_str = date_at.strftime("%Y-%m-%d %H:%M:%S %z")
684
+ else:
685
+ time_str = f"{date_at.strftime('%Y-%m-%d %H:%M:%S')} {self.timezone_offset}"
686
+
687
+ elif isinstance(date_at, date):
688
+ # For pure date objects, default to midnight in the client's local timezone
689
+ time_str = f"{date_at.strftime('%Y-%m-%d')} 00:00:00 {self.timezone_offset}"
690
+
691
+ else:
692
+ raise CropwiseValueError("The 'date_at' parameter must be a datetime or date object.")
693
+
694
+ # Structure flat data attributes as expected by Cropwise API v3 REST endpoint schema
695
+ object_attributes = {
696
+ "machine_id": str(machine_id),
697
+ "measuring_time": time_str
698
+ }
699
+
700
+ if mileage is not None:
701
+ object_attributes["manual_distance"] = str(mileage)
702
+
703
+ if work_hours is not None:
704
+ # CRITICAL STEP: Cropwise API v3 endpoint expects engine work duration strictly in SECONDS.
705
+ # We automatically convert user-provided hours (int or float) to integer seconds.
706
+ work_seconds = int(work_hours * 3600)
707
+ object_attributes["manual_engine_work_duration"] = str(work_seconds)
708
+
709
+ try:
710
+ return self.create_object(endpoint="odometer_states", data=object_attributes)
711
+
712
+ except CropwiseApiException as e:
713
+ # Check for HTTP 422 structural indicators inside the exception object
714
+ # Language-agnostic approach: look for 'measuring_time' key in server context/error string
715
+ error_str = str(e)
716
+
717
+ if "422" in error_str and "measuring_time" in error_str:
718
+ raise CropwiseOdometerDuplicateError(
719
+ f"Odometer record already exists for machine {machine_id} at {time_str}. "
720
+ f"Original server response: {error_str}"
721
+ ) from e
722
+ raise e
@@ -19,4 +19,19 @@ class CropwiseApiException(CropwiseException):
19
19
  Raised when the Cropwise server returns an API error response.
20
20
  Handles standard HTTP error statuses such as 4xx and 5xx responses.
21
21
  """
22
+ pass
23
+
24
+
25
+ class CropwiseValueError(CropwiseException):
26
+ """
27
+ Raised when user provides invalid argument values, shapes,
28
+ or unparseable date/time strings to library methods.
29
+ """
30
+ pass
31
+
32
+ class CropwiseOdometerDuplicateError(CropwiseApiException):
33
+ """
34
+ Raised when an odometer state record already exists for the specified timestamp.
35
+ Typically triggered by a language-agnostic HTTP 422 error containing 'measuring_time'.
36
+ """
22
37
  pass
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "cropwise-api-client"
7
- version = "0.1.6"
7
+ version = "0.1.7"
8
8
  description = "A Python client library for the Cropwise Operations API v3 with spatial GIS capabilities."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"