pitstop-cli 1.0.0__py3-none-any.whl

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.
pitstop/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .version import __version__
2
+
3
+ __all__ = ["__version__"]
pitstop/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
pitstop/chargers.py ADDED
@@ -0,0 +1,281 @@
1
+ """EV charging-station discovery via OpenStreetMap's Overpass API.
2
+
3
+ Italian EV pricing isn't published openly in a usable form yet (the AFIR
4
+ National Access Point/DATEX II rollout is still maturing), so this module
5
+ focuses on **locations + capability** — operator, plug types, max kW, fee,
6
+ access — which is what most "where can I charge near X" questions need."""
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ import re
12
+ from dataclasses import dataclass, field
13
+
14
+ from . import core, cpo_tariffs, overpass
15
+ from .core import haversine_km, in_italy, now_iso
16
+
17
+ # Map OSM `socket:<key>` to a human-readable plug name.
18
+ _SOCKET_TYPES = {
19
+ "type2": "Type 2 (AC)",
20
+ "type2_combo": "CCS Type 2",
21
+ "type2_cable": "Type 2 (AC, tethered)",
22
+ "type1": "Type 1 (AC)",
23
+ "type1_combo": "CCS Type 1",
24
+ "chademo": "CHAdeMO",
25
+ "schuko": "Schuko (domestic)",
26
+ "tesla_supercharger": "Tesla Supercharger",
27
+ "tesla_destination": "Tesla Destination",
28
+ "tesla_supercharger_ccs": "Tesla Supercharger (CCS)",
29
+ "tesla_standard": "Tesla",
30
+ }
31
+
32
+ _DC_FAST_TYPES = {"type2_combo", "type1_combo", "chademo",
33
+ "tesla_supercharger", "tesla_supercharger_ccs"}
34
+
35
+
36
+ @dataclass
37
+ class Socket:
38
+ type: str # human-readable
39
+ count: int = 1
40
+ max_power_kw: float | None = None
41
+ osm_key: str = ""
42
+
43
+ def to_dict(self) -> dict:
44
+ d = {"type": self.type, "count": self.count}
45
+ if self.max_power_kw is not None:
46
+ d["max_power_kw"] = self.max_power_kw
47
+ return d
48
+
49
+
50
+ @dataclass
51
+ class EvStation:
52
+ osm_id: int
53
+ name: str
54
+ operator: str
55
+ lat: float
56
+ lon: float
57
+ capacity: int | None
58
+ sockets: list[Socket] = field(default_factory=list)
59
+ max_power_kw: float | None = None
60
+ fee: bool | None = None
61
+ access: str = ""
62
+ opening_hours: str = ""
63
+ distance_km: float | None = None
64
+ tariff_info_url: str | None = None # operator's official tariff page
65
+
66
+ def to_dict(self) -> dict:
67
+ d = {
68
+ "osm_id": self.osm_id,
69
+ "name": self.name,
70
+ "operator": self.operator,
71
+ "lat": self.lat,
72
+ "lon": self.lon,
73
+ "navigation_url": core.navigation_url(self.lat, self.lon),
74
+ "sockets": [s.to_dict() for s in self.sockets],
75
+ }
76
+ if self.capacity is not None:
77
+ d["capacity"] = self.capacity
78
+ if self.max_power_kw is not None:
79
+ d["max_power_kw"] = self.max_power_kw
80
+ if self.fee is not None:
81
+ d["fee"] = self.fee
82
+ if self.access:
83
+ d["access"] = self.access
84
+ if self.opening_hours:
85
+ d["opening_hours"] = self.opening_hours
86
+ if self.distance_km is not None:
87
+ d["distance_km"] = self.distance_km
88
+ if self.tariff_info_url:
89
+ d["tariff_info_url"] = self.tariff_info_url
90
+ return d
91
+
92
+ def to_geojson_feature(self) -> dict:
93
+ props = self.to_dict()
94
+ lat = props.pop("lat")
95
+ lon = props.pop("lon")
96
+ return {
97
+ "type": "Feature",
98
+ "geometry": {"type": "Point", "coordinates": [lon, lat]},
99
+ "properties": props,
100
+ }
101
+
102
+
103
+ def _parse_kw(raw: str | None) -> float | None:
104
+ """Pull a kW number out of OSM strings like '22 kW', '50kW', '22000 W', '22'."""
105
+ if not raw:
106
+ return None
107
+ s = str(raw).strip().lower().replace(",", ".")
108
+ m = re.search(r"(-?\d+(?:\.\d+)?)\s*(kw|w)?", s)
109
+ if not m:
110
+ return None
111
+ val = float(m.group(1))
112
+ unit = (m.group(2) or "kw").lower()
113
+ if unit == "w":
114
+ val /= 1000.0
115
+ return round(val, 1)
116
+
117
+
118
+ def _parse_yes_no(raw: str | None) -> bool | None:
119
+ if raw is None:
120
+ return None
121
+ s = str(raw).strip().lower()
122
+ if s in ("yes", "true", "1"):
123
+ return True
124
+ if s in ("no", "false", "0"):
125
+ return False
126
+ return None
127
+
128
+
129
+ def parse_element(el: dict) -> EvStation | None:
130
+ """Parse one OSM node/way element with `tags` into an EvStation."""
131
+ tags = el.get("tags") or {}
132
+ if tags.get("amenity") != "charging_station":
133
+ return None
134
+ lat = el.get("lat")
135
+ lon = el.get("lon")
136
+ # ways have center.lat/lon via Overpass `out center`
137
+ if lat is None or lon is None:
138
+ center = el.get("center") or {}
139
+ lat, lon = center.get("lat"), center.get("lon")
140
+ if lat is None or lon is None:
141
+ return None
142
+
143
+ sockets: list[Socket] = []
144
+ for k, v in tags.items():
145
+ # match keys like socket:type2 (count) — ignore the :output / :voltage variants
146
+ if not k.startswith("socket:") or k.count(":") != 1:
147
+ continue
148
+ subkey = k.split(":", 1)[1]
149
+ try:
150
+ count = int(str(v).strip())
151
+ except (TypeError, ValueError):
152
+ count = 1
153
+ power = _parse_kw(tags.get(f"{k}:output") or tags.get(f"{k}:max_power"))
154
+ sockets.append(Socket(
155
+ type=_SOCKET_TYPES.get(subkey, subkey.replace("_", " ").title()),
156
+ count=count,
157
+ max_power_kw=power,
158
+ osm_key=subkey,
159
+ ))
160
+
161
+ max_kw = max((s.max_power_kw for s in sockets if s.max_power_kw is not None), default=None)
162
+ try:
163
+ capacity = int(tags["capacity"]) if "capacity" in tags else None
164
+ except (TypeError, ValueError):
165
+ capacity = None
166
+
167
+ return EvStation(
168
+ osm_id=el.get("id", 0),
169
+ name=tags.get("name", "").strip(),
170
+ operator=tags.get("operator", "").strip(),
171
+ lat=float(lat),
172
+ lon=float(lon),
173
+ capacity=capacity,
174
+ sockets=sockets,
175
+ max_power_kw=max_kw,
176
+ fee=_parse_yes_no(tags.get("fee")),
177
+ access=tags.get("access", "").strip(),
178
+ opening_hours=tags.get("opening_hours", "").strip(),
179
+ )
180
+
181
+
182
+ def _overpass_query(lat: float, lon: float, radius_m: int) -> str:
183
+ return (
184
+ "[out:json][timeout:25];\n"
185
+ f"( node[\"amenity\"=\"charging_station\"](around:{radius_m},{lat},{lon});\n"
186
+ f" way[\"amenity\"=\"charging_station\"](around:{radius_m},{lat},{lon}); );\n"
187
+ "out body center;"
188
+ )
189
+
190
+
191
+ def find_chargers(
192
+ *,
193
+ near: tuple[float, float],
194
+ radius_km: float = 10.0,
195
+ operator: str = "",
196
+ socket: str = "",
197
+ min_power_kw: float = 0.0,
198
+ free_only: bool = False,
199
+ public_only: bool = False,
200
+ refresh: bool = False,
201
+ ) -> tuple[list[EvStation], str | None]:
202
+ """Fetch and filter EV charging stations from OSM around a point.
203
+ Returns (stations, error_msg)."""
204
+ if not in_italy(near[0], near[1]):
205
+ # Allow queries anywhere — pitstop's Italy bbox is for the fuel data; for
206
+ # OSM EV the user can query elsewhere if they want. Just don't bail.
207
+ pass
208
+ radius_m = int(max(100, radius_km * 1000))
209
+ elements, error = overpass.fetch_elements(_overpass_query(near[0], near[1], radius_m),
210
+ refresh=refresh)
211
+
212
+ out: list[EvStation] = []
213
+ op_lc = operator.strip().lower()
214
+ sock_lc = socket.strip().lower()
215
+ for el in elements:
216
+ st = parse_element(el)
217
+ if st is None:
218
+ continue
219
+ if op_lc and op_lc not in st.operator.lower():
220
+ continue
221
+ if sock_lc and not any(sock_lc in (s.type.lower() + " " + s.osm_key.lower())
222
+ for s in st.sockets):
223
+ continue
224
+ if min_power_kw > 0 and (st.max_power_kw is None or st.max_power_kw < min_power_kw):
225
+ continue
226
+ if free_only and st.fee is True:
227
+ continue
228
+ if public_only and st.access and st.access.lower() not in ("public", "yes", "permissive"):
229
+ continue
230
+ st.distance_km = round(haversine_km(near[0], near[1], st.lat, st.lon), 2)
231
+ st.tariff_info_url = cpo_tariffs.lookup(st.operator)
232
+ out.append(st)
233
+
234
+ out.sort(key=lambda s: s.distance_km if s.distance_km is not None else math.inf)
235
+ return out, error
236
+
237
+
238
+ def response_envelope(stations: list[EvStation], query: dict, error: str | None = None) -> dict:
239
+ env = {
240
+ "source": overpass.SOURCE_NAME,
241
+ "source_url": overpass.SOURCE_URL,
242
+ "generated_at": core.now_iso(),
243
+ "query": query,
244
+ "count": len(stations),
245
+ "stations": [s.to_dict() for s in stations],
246
+ "disclaimer": (
247
+ "Unofficial tool. EV-charger data from OpenStreetMap via Overpass API "
248
+ "(© OpenStreetMap contributors, ODbL). Coverage and freshness vary. "
249
+ "Power, plug types, and access fields reflect what mappers entered — "
250
+ "verify on-site or via the operator before relying on them. "
251
+ "Per-station tariffs are NOT in this dataset: as of mid-2026 they are "
252
+ "not openly available in Italy (AFIR DATEX II is upload-only; "
253
+ "commercial APIs like Chargeprice/Eco-Movement carry them). The "
254
+ "`tariff_info_url` field on each station, when present, links to the "
255
+ "operator's own official tariff page."
256
+ ),
257
+ }
258
+ if error:
259
+ env["error"] = error
260
+ return env
261
+
262
+
263
+ def geojson_envelope(stations: list[EvStation], query: dict, error: str | None = None) -> dict:
264
+ env = {
265
+ "type": "FeatureCollection",
266
+ "metadata": {
267
+ "source": overpass.SOURCE_NAME,
268
+ "generated_at": core.now_iso(),
269
+ "query": query,
270
+ "disclaimer": (
271
+ "Unofficial tool. EV-charger data from OpenStreetMap via Overpass API "
272
+ "(© OpenStreetMap contributors, ODbL). Coverage and freshness vary. "
273
+ "Power, plug types, and access fields reflect what mappers entered — "
274
+ "verify on-site or via the operator before relying on them."
275
+ ),
276
+ },
277
+ "features": [s.to_geojson_feature() for s in stations],
278
+ }
279
+ if error:
280
+ env["metadata"]["error"] = error
281
+ return env