-
-
Notifications
You must be signed in to change notification settings - Fork 150
Expand file tree
/
Copy pathoctopus.py
More file actions
3291 lines (2929 loc) · 164 KB
/
Copy pathoctopus.py
File metadata and controls
3291 lines (2929 loc) · 164 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -----------------------------------------------------------------------------
# Predbat Home Battery System
# Copyright Trefor Southwell 2026 - All Rights Reserved
# This application maybe used for personal use only and not for commercial use
# -----------------------------------------------------------------------------
"""Octopus Energy API integration.
Provides both REST and GraphQL API access to Octopus Energy for fetching
tariff rates, intelligent dispatch schedules, saving sessions, and account
data. Delegates caching to the StorageComponent with stale-while-revalidate
semantics for multi-pod deployments.
"""
import asyncio
import requests
import re
from datetime import datetime, timedelta, timezone
from predbat_metrics import record_api_call
from const import TIME_FORMAT, TIME_FORMAT_OCTOPUS
from utils import str2time, minutes_to_time, dp1, dp2, dp4, minute_data
from component_base import ComponentBase
from mock_base import MockBase as SharedMockBase
import aiohttp
import hashlib
import json
import os
import pytz
from ha import run_async
user_agent_value = "predbat-octopus-energy"
integration_context_header = "Ha-Integration-Context"
DATE_STR_FORMAT = "%Y-%m-%d"
DATE_TIME_STR_FORMAT = "%Y-%m-%dT%H:%M:%S%z"
# Sentinel distinguishing "attribute not present on the entity" from a genuinely empty list,
# since both would otherwise look the same (falsy) to callers.
_ATTRIBUTE_UNSET = object()
# Night-rate window definitions: start time, end time, whether the window crosses midnight.
# Keys: "eco7" (Economy 7), "go" (Octopus GO / generic day-night), "iog" (Intelligent GO TOU).
OCTOPUS_NIGHT_RATE_WINDOWS = {
"eco7": {"start": (0, 30), "end": (7, 30), "cross_midnight": False},
"go": {"start": (0, 30), "end": (5, 30), "cross_midnight": False},
"iog": {"start": (23, 30), "end": (5, 30), "cross_midnight": True},
}
OCTOPUS_MAX_RETRIES = 5
# The EV/charge-point catalogue is static reference data, so it is refreshed daily
CATALOGUE_FRESH_MINUTES = 24 * 60
CATALOGUE_STALE_MINUTES = 25 * 60
OCTOPUS_SLOT_MAX_DEFAULT = 48 # 24 hours with 30-minute slots
BASE_TIME = datetime.strptime("00:00", "%H:%M")
OPTIONS_TIME = [((BASE_TIME + timedelta(seconds=minute * 60)).strftime("%H:%M")) for minute in range(4 * 60, 11 * 60, 30)]
def is_active(now_utc, activeFrom, activeTo):
if not activeFrom:
return False
if now_utc < activeFrom:
return False
if not activeTo:
return True
if now_utc > activeTo:
return False
return True
def parse_date(dt_str):
"""Convert a date string to a date object."""
try:
return datetime.strptime(dt_str, DATE_STR_FORMAT)
except (ValueError, TypeError):
return None
def parse_date_time(dt_str):
"""Convert a date string to a date object."""
try:
return datetime.strptime(dt_str, DATE_TIME_STR_FORMAT)
except (ValueError, TypeError):
return None
CDN_BLOCK_MARKERS = ("cloudfront", "request blocked", "the request could not be satisfied")
HTML_DOCUMENT_PREFIXES = ("<!doctype", "<html")
# A generic "403 Forbidden" page is indistinguishable from a WAF page, so after this many
# consecutive edge blocks fall back to refreshing the token in case the credential really
# was revoked. Without this the component could never recover from a misclassification.
EDGE_BLOCK_REFRESH_AFTER = 5
def is_edge_block_body(text):
"""Return True if a 403 body is positively identifiable as a CDN/WAF error page.
Kraken reports authentication problems as a JSON GraphQL error body (normally with
HTTP 200) or as a 401. A 403 carrying an HTML error page - e.g. CloudFront's
"Request blocked" - is edge rate limiting, not a credential problem, so the cached
token must be kept rather than discarded and immediately re-minted.
Two conditions must both hold: the body must not parse as JSON (anything the API
itself produces is JSON), and it must look like an HTML document or name a known CDN.
Matching on wording alone would misclassify a genuine JSON error that happens to say
something like "access denied", which would keep an invalid token forever - the same
permanent lockout this check exists to prevent, arrived at from the other direction.
Detection is deliberately conservative: a 403 we cannot identify as a CDN page keeps
the existing "refresh the token and retry" behaviour, which recovers genuinely revoked
tokens without needing a restart.
Args:
text: The raw response body.
Returns:
bool: True if the body carries a known CDN/WAF block signature.
"""
if not isinstance(text, str) or not text:
return False
try:
json.loads(text)
except (ValueError, TypeError):
pass
else:
# A parseable JSON body came from the API, not from an edge appliance
return False
stripped = text.lstrip().lower()
return stripped.startswith(HTML_DOCUMENT_PREFIXES) or any(marker in stripped for marker in CDN_BLOCK_MARKERS)
api_token_query = """mutation {{
obtainKrakenToken(input: {{ APIKey: "{api_key}" }}) {{
token
}}
}}"""
account_query = """query {{
account(accountNumber: "{account_id}") {{
electricityAgreements(active: true) {{
meterPoint {{
mpan
meters(includeInactive: false) {{
activeFrom
activeTo
makeAndType
serialNumber
makeAndType
meterType
smartExportElectricityMeter {{
deviceId
manufacturer
model
firmwareVersion
}}
smartImportElectricityMeter {{
deviceId
manufacturer
model
firmwareVersion
}}
}}
agreements(includeInactive: true) {{
validFrom
validTo
tariff {{
... on TariffType {{
productCode
tariffCode
}}
}}
}}
}}
}}
gasAgreements(active: true) {{
meterPoint {{
mprn
meters(includeInactive: false) {{
activeFrom
activeTo
serialNumber
consumptionUnits
modelName
mechanism
smartGasMeter {{
deviceId
manufacturer
model
firmwareVersion
}}
}}
agreements(includeInactive: true) {{
validFrom
validTo
tariff {{
tariffCode
productCode
}}
}}
}}
}}
}}
}}"""
# The vehicle/charge-point catalogue is global reference data - identical for every
# account and effectively static - so it is queried separately from the per-account
# device list and cached, rather than being re-downloaded on every device poll.
intelligent_catalogue_query = """query {
electricVehicles {
make
models {
model
batterySize
}
}
chargePointVariants {
make
models {
model
powerInKw
}
}
}"""
intelligent_device_query = """query {{
devices(accountNumber: "{account_id}") {{
id
provider
deviceType
status {{
current
}}
__typename
... on SmartFlexVehicle {{
make
model
}}
... on SmartFlexChargePoint {{
make
model
}}
}}
}}"""
intelligent_dispatches_query = """query {{
devices(accountNumber: "{account_id}", deviceId: "{device_id}") {{
id
status {{
currentState
}}
}}
flexPlannedDispatches(deviceId:"{device_id}") {{
start
end
type
energyAddedKwh
}}
completedDispatches(accountNumber: "{account_id}") {{
start
end
delta
meta {{
source
location
}}
}}
}}"""
intelligent_settings_query = """query {{
devices(accountNumber: "{account_id}", deviceId: "{device_id}") {{
id
status {{
isSuspended
}}
... on SmartFlexVehicle {{
chargingPreferences {{
weekdayTargetTime
weekdayTargetSoc
weekendTargetTime
weekendTargetSoc
minimumSoc
maximumSoc
}}
}}
... on SmartFlexChargePoint {{
chargingPreferences {{
weekdayTargetTime
weekdayTargetSoc
weekendTargetTime
weekendTargetSoc
minimumSoc
maximumSoc
}}
}}
}}
}}"""
octoplus_saving_session_query = """query {{
savingSessions {{
events(includeDev: false) {{
id
code
rewardPerKwhInOctoPoints
startAt
endAt
devEvent
targetRegion {{
regionId
}}
}}
account(accountNumber: "{account_id}") {{
hasJoinedCampaign
joinedEvents {{
eventId
startAt
endAt
rewardGivenInOctoPoints
}}
signedUpMeterPoint {{
regionId
}}
}}
}}
}}"""
octoplus_saving_session_join_mutation = """mutation {{
joinSavingSessionsEvent(input: {{
accountNumber: "{account_id}"
eventCode: "{event_code}"
}}) {{
joinedEventCodes
}}
}}
"""
flexibility_campaign_query = """query {{
customerFlexibilityCampaignEvents(
accountNumber: "{account_id}"
supplyPointIdentifier: "{mpan}"
campaignSlug: "{campaign_slug}"
last: 50
) {{
edges {{
node {{
code
startAt
endAt
}}
}}
totalCount
pageInfo {{
hasNextPage
endCursor
}}
}}
}}"""
intelligent_settings_mutation = """mutation {{
setDevicePreferences(input: {{
deviceId: "{device_id}"
mode: CHARGE
unit: PERCENTAGE
schedules: [{schedules}]
}}) {{
id
}}
}}"""
intelligent_settings_mutation_schedule = """{{
dayOfWeek: {day_of_week}
time: "{target_time}"
max: {target_percentage}
}}"""
class OctopusEnergyApiClient:
"""Low-level async HTTP client for Octopus Energy REST and GraphQL APIs.
Handles authentication, session management, rate fetching, intelligent
dispatch queries, and saving session management.
"""
def __init__(self, api_key, log, timeout_in_seconds=20):
if api_key is None:
raise Exception("OctopusAPI: API KEY is not set")
self.api_key = api_key
self.log = log
self.base_url = "https://api.octopus.energy"
self.backend_url = "https://api.backend.octopus.energy"
self.default_headers = {"user-agent": f"{user_agent_value}/1.0"}
self.timeout = aiohttp.ClientTimeout(total=None, sock_connect=timeout_in_seconds, sock_read=timeout_in_seconds)
self.session = None
self.saving_sessions_to_join = []
async def async_close(self):
if self.session is not None:
await self.session.close()
async def async_create_client_session(self):
if self.session is not None:
return self.session
self.session = aiohttp.ClientSession(headers=self.default_headers, skip_auto_headers=["User-Agent"])
return self.session
class OctopusAPI(ComponentBase):
"""Octopus Energy integration component.
Manages tariff discovery, rate caching, intelligent device tracking,
saving sessions, and account data via both REST and GraphQL APIs.
Publishes rate sensors and handles Octopus-specific features.
"""
def initialize(self, key, account_id, automatic):
"""Initialise the Octopus API component"""
self.api_key = key
self.api = OctopusEnergyApiClient(key, self.log)
self.account_id = account_id
self.graphql_token = None
self.graphql_expiration = None
self.consecutive_edge_blocks = 0
self.account_data = {}
self.tariffs = {}
self.saving_sessions = {}
self.saving_sessions_to_join = []
self.intelligent_devices = {}
self.tariff_fetched_at = None
self.device_fetched_at = None
self.sensor_updated_at = None
self.automatic = automatic
self.commands = []
self.mpan = None
self.free_electricity_events = []
# API request metrics for monitoring
self.requests_total = 0
self.failures_total = 0
# In-memory cache for product info (keyed by product_code) to avoid repeated API calls
self._product_info_cache = {}
self.log("OctopusAPI: Initialised with account ID {}".format(self.account_id))
async def select_event(self, entity_id, value):
suffix = self.get_entity_suffix(entity_id)
device_id = self.suffix_to_device_id(suffix)
if entity_id == self.get_entity_name("select", "intelligent_target_time", index=suffix) and device_id:
self.commands.append({"command": "set_intelligent_target_time", "value": value, "device_id": device_id})
elif entity_id == self.get_entity_name("select", "saving_session_join"):
self.commands.append({"command": "join_saving_session_event", "event_code": value})
def get_entity_suffix(self, entity_id):
"""
Extract the index suffix from an entity ID
"""
if "_" in entity_id:
return entity_id.split("_")[-1]
else:
return ""
async def number_event(self, entity_id, value):
suffix = self.get_entity_suffix(entity_id)
device_id = self.suffix_to_device_id(suffix)
if entity_id == self.get_entity_name("number", "intelligent_target_soc", index=suffix) and device_id:
# Set the target soc
try:
value = int(value)
except ValueError:
self.log("Error: OctopusAPI: Invalid value for intelligent target soc: {}".format(value))
return
self.commands.append({"command": "set_intelligent_target_percentage", "value": value, "device_id": device_id})
async def switch_event(self, entity_id, service):
pass
def is_alive(self):
return self.api_started and self.account_data
def _data_age_minutes(self, fetched_at):
"""Return how many minutes ago fetched_at was, or 9999 if not set."""
if fetched_at is None:
return 9999
return (datetime.now() - fetched_at).total_seconds() / 60
async def run(self, seconds, first):
"""
Main run loop
"""
if first:
# Load cached data (restores tariff_fetched_at / device_fetched_at timestamps)
await self.load_octopus_cache()
self.log("OctopusAPI: Started")
# Process any queued commands
refresh = False
if not first and (await self.process_commands(self.account_id)):
# Commands processed - will trigger refresh on next cycle
refresh = True
# On first run, use the stored fetch timestamps to decide what is stale so that fast
# restarts skip re-fetching data that was already retrieved recently. None means the
# data was never fetched (no cache), so treat as stale. Sensor data is always pushed
# on startup so HA entities are populated immediately.
tariff_due = self._data_age_minutes(self.tariff_fetched_at) >= 30
device_due = refresh or self._data_age_minutes(self.device_fetched_at) >= 10
sensor_due = first or refresh or self._data_age_minutes(self.sensor_updated_at) >= 2
if tariff_due:
# 30-minute API refresh for account and tariff discovery
if await self.async_get_account(self.account_id):
self.tariff_fetched_at = datetime.now()
if tariff_due or first:
# Rebuild tariff structure from account_data (no API call, needed after cache load)
await self.async_find_tariffs()
if device_due:
# 10-minute API refresh for saving sessions
self.saving_sessions = await self.async_get_flexibility_events(self.account_id)
self.get_saving_session_data()
self.device_fetched_at = datetime.now()
if device_due or first:
# Download rate data into tariff structure (uses storage cache, needed after cache load)
await self.fetch_tariffs(self.tariffs)
if sensor_due:
# 2-minute refresh of intelligent dispatches and the dispatch sensor so new slots are
# picked up quickly. Stamp before fetching so the fetch/publish duration can't slip
# the cadence past the next run
self.sensor_updated_at = datetime.now()
await self.async_update_intelligent_devices(self.account_id)
await self.async_intelligent_update_sensor(self.account_id)
if tariff_due or device_due:
# Don't save cache every 2 minutes, if we lose it then we re-fresh it anyhow
await self.save_octopus_cache()
if first and self.automatic:
self.automatic_config(self.tariffs)
return True
async def final(self):
"""
Final cleanup before stopping
"""
await self.api.async_close()
async def process_commands(self, account_id):
"""
Process queued commands
"""
commands = self.commands[:]
self.commands = []
done_command = False
for command in commands:
command_name = command.get("command", "")
if command_name == "set_intelligent_target_percentage":
value = command.get("value", None)
device_id = command.get("device_id", None)
await self.async_set_intelligent_target_schedule(account_id, target_percentage=int(value), device_id=device_id)
done_command = True
elif command_name == "set_intelligent_target_time":
value = command.get("value", None)
device_id = command.get("device_id", None)
await self.async_set_intelligent_target_schedule(account_id, target_time=value, device_id=device_id)
done_command = True
elif command_name == "join_saving_session_event":
event_code = command.get("event_code", None)
await self.async_join_saving_session_events(self.account_id, event_code)
done_command = True
return done_command
def get_tariff_cache_key(self, tariff_data):
"""
Generate cache key for a tariff based on product_code and tariff_code
Returns: filename safe string like "AGILE-FLEX-22-11-25_E-1R-AGILE-FLEX-22-11-25-C"
"""
product_code = tariff_data.get("productCode", "unknown")
tariff_code = tariff_data.get("tariffCode", "unknown")
# Sanitize for filesystem safety
key = f"{product_code}_{tariff_code}".replace("/", "_").replace("\\", "_")
return key
def decode_kraken_token_expiry(self, token):
"""
Extract expiration timestamp from Kraken JWT token without verification.
Returns datetime object if successful, None otherwise.
"""
import base64
if not token:
return None
try:
parts = token.split(".")
if len(parts) != 3:
return None
# Decode payload (add padding if needed)
payload = parts[1] + "=" * (4 - len(parts[1]) % 4)
payload_decoded = json.loads(base64.urlsafe_b64decode(payload))
if "exp" in payload_decoded:
return datetime.fromtimestamp(payload_decoded["exp"])
return None
except Exception as e:
self.log(f"Warn: OctopusAPI: Failed to decode Kraken token expiry: {e}")
return None
async def load_octopus_cache(self):
"""Load the octopus user cache via the storage component, normalising missing fields."""
data = await self.storage.load("octopus_user", "account") if self.storage else None
if data:
self.account_data = data.get("account_data", {})
self.saving_sessions = data.get("saving_sessions", {})
self.intelligent_devices = data.get("intelligent_devices", {})
self.graphql_token = data.get("kraken_token")
self.tariff_fetched_at = data.get("tariff_fetched_at")
self.device_fetched_at = data.get("device_fetched_at")
self.update_success_timestamp()
self.tariffs = {}
if self.account_data is None:
self.account_data = {}
if self.saving_sessions is None:
self.saving_sessions = {}
if not isinstance(self.intelligent_devices, dict):
self.intelligent_devices = {}
async def save_octopus_cache(self):
"""Save the octopus user cache (account data, tokens, sessions, devices) via the storage component."""
octopus_cache = {
"account_data": self.account_data,
"saving_sessions": self.saving_sessions,
"intelligent_devices": self.intelligent_devices,
"kraken_token": self.graphql_token,
"tariff_fetched_at": self.tariff_fetched_at,
"device_fetched_at": self.device_fetched_at,
}
if self.storage:
await self.storage.save("octopus_user", "account", octopus_cache, format="yaml", expiry=datetime.now(timezone.utc) + timedelta(days=7))
def get_tariff(self, tariff_type):
if tariff_type in self.tariffs:
return self.tariffs[tariff_type]
return None
async def async_find_tariffs(self):
"""
Find the tariffs for the account
"""
self.log("OctopusAPI: Find tariffs account data {}".format(self.account_data))
if not self.account_data:
return self.tariffs
now = datetime.now()
old_tariff_keys = set(self.tariffs.keys())
tariffs = {}
gas = self.account_data.get("account", {}).get("gasAgreements", [])
electric = self.account_data.get("account", {}).get("electricityAgreements", [])
for agreement in electric + gas:
meterpoint = agreement.get("meterPoint", {})
meters = meterpoint.get("meters", [])
agreements = meterpoint.get("agreements", [])
isActiveMeter = False
isImport = False
isExport = False
isGas = False
deviceID_import = None
deviceID_export = None
deviceID_gas = None
for meter in meters:
activeFrom = parse_date(meter.get("activeFrom", None))
activeTo = parse_date(meter.get("activeTo", None))
isActiveMeter = is_active(now, activeFrom, activeTo)
if isActiveMeter:
if meter.get("smartImportElectricityMeter", None):
isImport = True
deviceID_import = meter.get("smartImportElectricityMeter", {}).get("deviceId", None)
self.log("OctopusAPI: Found active import meter with device ID {}".format(deviceID_import))
if not self.mpan:
self.mpan = meterpoint.get("mpan")
if self.mpan:
self.log("OctopusAPI: Found MPAN {}".format(self.mpan[:4] + "..." + self.mpan[-4:] if len(self.mpan) > 8 else self.mpan))
if meter.get("smartExportElectricityMeter", None):
isExport = True
deviceID_export = meter.get("smartExportElectricityMeter", {}).get("deviceId", None)
self.log("OctopusAPI: Found active export meter with device ID {}".format(deviceID_export))
if meter.get("smartGasMeter", None):
isGas = True
deviceID_gas = meter.get("smartGasMeter", {}).get("deviceId", None)
self.log("OctopusAPI: Found active gas meter with device ID {}".format(deviceID_gas))
break
isActiveAgreement = False
tariffCode = None
productCode = None
for this_agreement in agreements:
tariff = this_agreement.get("tariff", {})
validFrom = parse_date_time(this_agreement.get("validFrom", None))
validTo = parse_date_time(this_agreement.get("validTo", None))
isActiveAgreement = is_active(self.now_utc_exact, validFrom, validTo)
if isActiveAgreement:
tariffCode = tariff.get("tariffCode", None)
productCode = tariff.get("productCode", None)
break
if isActiveMeter and isActiveAgreement:
if not isImport and not isExport and not isGas:
if tariffCode and ("OUTGOING" in tariffCode or "EXPORT" in tariffCode):
isExport = True
deviceID_export = None
self.log("OctopusAPI: No export meter found but tariff code indicates export, treating as export tariff with device ID None")
if isImport:
self.log("OctopusAPI: Adding import tariff with code {} product {} device ID {}".format(tariffCode, productCode, deviceID_import))
tariffs["import"] = {"tariffCode": tariffCode, "productCode": productCode, "deviceID": deviceID_import}
tariffs["import"]["data"] = self.tariffs.get("import", {}).get("data", None)
tariffs["import"]["standing"] = self.tariffs.get("import", {}).get("standing", None)
if isExport:
self.log("OctopusAPI: Adding export tariff with code {} product {} device ID {}".format(tariffCode, productCode, deviceID_export))
tariffs["export"] = {"tariffCode": tariffCode, "productCode": productCode, "deviceID": deviceID_export}
tariffs["export"]["data"] = self.tariffs.get("export", {}).get("data", None)
tariffs["export"]["standing"] = self.tariffs.get("export", {}).get("standing", None)
if isGas:
self.log("OctopusAPI: Adding gas tariff with code {} product {} device ID {}".format(tariffCode, productCode, deviceID_gas))
tariffs["gas"] = {"tariffCode": tariffCode, "productCode": productCode, "deviceID": deviceID_gas}
tariffs["gas"]["data"] = self.tariffs.get("gas", {}).get("data", None)
tariffs["gas"]["standing"] = self.tariffs.get("gas", {}).get("standing", None)
self.tariffs = tariffs
# Re-run automatic config if tariff structure changed (e.g. export agreement became active)
new_tariff_keys = set(self.tariffs.keys())
if old_tariff_keys and new_tariff_keys != old_tariff_keys and self.automatic:
self.log("OctopusAPI: Tariff structure changed from {} to {}, reconfiguring".format(old_tariff_keys, new_tariff_keys))
self.automatic_config(self.tariffs)
return self.tariffs
async def async_update_intelligent_devices(self, account_id):
"""
Update the intelligent device
"""
import_tariff = self.tariffs.get("import", {})
tariffCode = import_tariff.get("tariffCode", "")
if not self.is_intelligent_go_tariff(tariffCode):
return
deviceID = import_tariff.get("deviceID", None)
if deviceID:
intelligent_devices = await self.async_get_intelligent_devices(account_id, deviceID)
if intelligent_devices:
# Update existing intelligent devices with new dispatch data.
# Always call fetch_previous_dispatch when completed dispatches are available to merge historical data.
for device_id in intelligent_devices:
device = intelligent_devices[device_id]
if "completed_dispatches" in device:
self.intelligent_devices[device_id] = device
await self.fetch_previous_dispatch(device_id)
elif device_id not in self.intelligent_devices:
# First time seeing this device with no completed dispatches yet
self.intelligent_devices[device_id] = device
# Drop devices that Octopus no longer returns as LIVE. Without this a device that
# is deregistered/replaced (e.g. a re-paired charger leaving a stale registration
# behind - invisible in the Octopus app but still present via the API at some point
# in the past) stays cached and republished forever, permanently occupying a car
# slot and holding num_cars up even though only one real device remains.
removed = sorted(set(self.intelligent_devices) - set(intelligent_devices))
for device_id in removed:
self.log("OctopusAPI: Intelligent device {} no longer live, removing".format(device_id))
del self.intelligent_devices[device_id]
return self.intelligent_devices
def suffix_to_device_id(self, suffix):
"""
Convert an index suffix back to a device ID
E.g. "12345" -> "smart-meter-12345"
This is a best-effort approach based on the assumption that the device ID ends with the suffix after a hyphen
"""
for device_id in self.intelligent_devices:
if device_id.endswith(suffix):
return device_id
return None
def device_id_to_index_suffix(self, device_id):
"""
Convert a device ID to an index suffix for entity naming
E.g. "smart-meter-12345" -> "12345"
"""
if "-" in device_id:
return device_id.split("-")[-1]
else:
return device_id
async def fetch_previous_dispatch(self, device_id):
intelligent_device = self.intelligent_devices.get(device_id, None)
if intelligent_device is None:
return
index_suffix = self.device_id_to_index_suffix(device_id)
# Get current completed dispatches from the device data
current_completed = intelligent_device.get("completed_dispatches", [])
if not current_completed or not isinstance(current_completed, list):
current_completed = []
# Merge old dispatches with current completed dispatches, avoiding duplicates based on start time
entity_id = self.get_entity_name("binary_sensor", "intelligent_dispatch", index=index_suffix)
old_dispatches = self.get_state_wrapper(entity_id, attribute="completed_dispatches", default=[])
if old_dispatches and isinstance(old_dispatches, list):
for dispatch in old_dispatches:
if isinstance(dispatch, dict):
already_exists = False
for current in current_completed:
current_start = parse_date_time(current.get("start", None))
dispatch_start = parse_date_time(dispatch.get("start", None))
if dispatch_start == current_start:
already_exists = True
if not already_exists and dispatch.get("start", None) and dispatch.get("end", None) and dispatch.get("charge_in_kwh", None):
current_completed.append(dispatch)
# Remove any duplicates, give priority to those with a location set
unique_dispatches = {}
for dispatch in current_completed:
start = dispatch.get("start", None)
if start:
key = start
dispatch_location = dispatch.get("location") or dispatch.get("meta", {}).get("location")
existing_location = unique_dispatches[key].get("location") or unique_dispatches[key].get("meta", {}).get("location") if key in unique_dispatches else None
if key not in unique_dispatches or (dispatch_location and not existing_location):
unique_dispatches[key] = dispatch
current_completed = list(unique_dispatches.values())
current_completed = sorted([x for x in current_completed if x.get("start")], key=lambda x: parse_date_time(x.get("start")))
# Prune completed dispatches for results older than 5 days
current_completed = [x for x in current_completed if x.get("start") and parse_date_time(x.get("start")) > self.now_utc_exact - timedelta(days=5)]
intelligent_device["completed_dispatches"] = current_completed
def join_saving_session_event(self, event_code):
"""
Join a saving session event
"""
self.commands.append({"command": "join_saving_session_event", "event_code": event_code})
async def async_set_intelligent_target_schedule(self, account_id, device_id, target_percentage=None, target_time=None):
"""
Set the intelligent target schedule
"""
devices = self.get_intelligent_devices()
if not devices:
self.log("Warn: OctopusAPI: Try to set target schedule, but no intelligent device found")
return
device = devices.get(device_id, None)
if device:
daysOfWeek = ["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"]
if target_time is None:
target_time = self.get_intelligent_target_time(device_id)
if target_time and len(target_time) > 5:
target_time = target_time[:5] # HH:MM format
if target_percentage is None:
target_percentage = self.get_intelligent_target_soc(device_id)
self.log("OctopusAPI: Setting intelligent target device_id {} schedule time {} percentage {}".format(device_id, target_time, target_percentage))
schedule = ", ".join(list(map(lambda day: intelligent_settings_mutation_schedule.format(day_of_week=day, target_percentage=target_percentage, target_time=target_time), daysOfWeek)))
await self.async_graphql_query(intelligent_settings_mutation.format(device_id=device_id, schedules=schedule), "set-intelligent-target-time", returns_data=False)
# Update cached data
device["weekend_target_time"] = target_time
device["weekend_target_soc"] = target_percentage
device["weekday_target_time"] = target_time
device["weekday_target_soc"] = target_percentage
else:
self.log("Warn: OctopusAPI: Try to set target schedule, but no intelligent device ID {} found".format(device_id))
async def async_join_saving_session_events(self, account_id, event_code):
"""
Join the saving session events
"""
if event_code:
# Join the saving sessions
self.log("OctopusAPI: Joining saving session event {}".format(event_code))
await self.async_graphql_query(octoplus_saving_session_join_mutation.format(account_id=account_id, event_code=event_code), "join-saving-session-event", returns_data=False, use_backend=True)
# Re-fetch the saving sessions if we have joined any
self.saving_sessions = await self.async_get_saving_sessions(account_id)
def get_intelligent_devices(self):
"""
Get the intelligent device
"""
return self.intelligent_devices
def get_intelligent_completed_dispatches(self, device_id):
"""
Get the completed intelligent dispatches
"""
devices = self.get_intelligent_devices()
completed_dispatches = []
if devices:
device = devices.get(device_id, None)
if device:
completed_dispatches = device.get("completed_dispatches", [])
return completed_dispatches
def get_intelligent_planned_dispatches(self, device_id):
"""
Get the intelligent dispatches
"""
devices = self.get_intelligent_devices()
planned_dispatches = []
if devices:
device = devices.get(device_id, None)
if device:
planned_dispatches = device.get("planned_dispatches", [])
return planned_dispatches
def get_intelligent_vehicle(self, device_id):
"""
Get the intelligent vehicle
"""
vehicle = {}
devices = self.get_intelligent_devices()
if devices:
device = devices.get(device_id, None)
if device:
vehicle["vehicleBatterySizeInKwh"] = device.get("vehicle_battery_size_in_kwh", None)
vehicle["chargePointPowerInKw"] = device.get("charge_point_power_in_kw", None)
vehicle["weekdayTargetTime"] = device.get("weekday_target_time", None)
vehicle["weekdayTargetSoc"] = device.get("weekday_target_soc", None)
vehicle["weekendTargetTime"] = device.get("weekend_target_time", None)
vehicle["weekendTargetSoc"] = device.get("weekend_target_soc", None)
vehicle["minimumSoc"] = device.get("minimum_soc", None)
vehicle["maximumSoc"] = device.get("maximum_soc", None)
vehicle["suspended"] = device.get("suspended", None)
vehicle["model"] = device.get("model", None)
vehicle["provider"] = device.get("provider", None)
vehicle["status"] = device.get("status", None)
# Remove None's from the dictionary
vehicle = {k: v for k, v in vehicle.items() if v is not None}
return vehicle
def get_intelligent_battery_size(self, device_id):
"""
Get the intelligent battery sizes
"""
devices = self.get_intelligent_devices()
if devices:
device = devices.get(device_id, None)
if device:
return device.get("vehicle_battery_size_in_kwh", None)
return None
def get_intelligent_target_time(self, device_id):
"""
Get the intelligent target times
"""
devices = self.get_intelligent_devices()
if devices:
device = devices.get(device_id, None)
if device:
is_weekend = self.now_utc_exact.weekday() >= 5
return device.get("weekday_target_time" if not is_weekend else "weekend_target_time", None)
else:
return None
def get_intelligent_target_soc(self, device_id):
"""
Get the intelligent target socs
"""
devices = self.get_intelligent_devices()
if devices:
device = devices.get(device_id, None)
if device:
is_weekend = self.now_utc_exact.weekday() >= 5
return device.get("weekday_target_soc" if not is_weekend else "weekend_target_soc", None)
else:
return None
def get_entity_name(self, root, suffix, index=""):
"""
Get the entity name
"""
if index:
entity_name = root + "." + self.prefix + "_octopus_" + self.account_id.replace("-", "_") + "_" + suffix + "_" + index
else:
entity_name = root + "." + self.prefix + "_octopus_" + self.account_id.replace("-", "_") + "_" + suffix
entity_name = entity_name.lower()
return entity_name
def get_saving_session_data(self):
"""
Get the saving sessions data
"""
return_joined_events = []
return_available_events = []