-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathscript v8.4
More file actions
1735 lines (1507 loc) Β· 69.8 KB
/
script v8.4
File metadata and controls
1735 lines (1507 loc) Β· 69.8 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
# Priority Rules Decision
# Powston Dynamic Arbitrage β v8.4 (Critical Floor Fix)
# Author: powston.com.au@bol.la
# BUILD: 2024-11-25 | Overnight/morning floor calculation fix
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# v8.4 CRITICAL FIX RELEASE
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Fixes major overnight/morning floor calculation bug.
#
# v8.3 β v8.4 Changes:
# 1. Fixed overnight recognition in compute_floor()
# - 2 AM now correctly calculates 2.8h reserve (not 12.8h)
# - Morning hours (5 AM-4 PM) now use correct reserve calculation
# - Enables overnight and morning export opportunities
#
# THE BUG:
# - Overnight (12 AM-5 AM) treated as "before peak"
# - Calculated reserve from peak_startβsunrise (12.8h)
# - Should calculate from current_timeβsunrise (2-3h)
# - Result: Floor at 84% instead of 30%
# - Blocked ALL overnight and morning export opportunities
#
# IMPACT:
# - Lost ~$2/day in overnight + morning arbitrage
# - Lost ~$730/year
# - Explains why timeline showed π°π°π° but system didn't export
#
# THE FIX:
# - Recognize overnight (hour < sunrise) as post-peak
# - Calculate correct hours_to_sunrise for each period
# - Overnight: 2-3h reserve = 30% floor β
# - Morning: Small reserve = ability to export β
# - Peak/post-peak: Unchanged β
#
# v8.3 Changes (recap):
# 1. Enhanced timeline icons: π΅ π
# 2. Better error messages
#
# v8.2 Changes (recap):
# 1. PRE_PEAK_MAX_BUY_PRICE ceiling
#
# v8.1 Changes (recap):
# 1. Best-N pattern template documentation
#
# v8.0 Changes (recap):
# 1. Time window helpers
# 2. Floor component standardization
# 3. Priority 50 battery full check
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# STRATEGY OVERVIEW
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Advanced battery arbitrage strategy with:
# - Weather-adaptive floor management (sunny/normal/rainy)
# - Forecast-based optimal charge/discharge timing
# - Best-N periods charging algorithm (v7.11)
# - Peak stepping floor with Best-N export (v7.12)
# - NEW v7.13: Two-tier spike handling ($1+ vs 35Β’+)
# - NEW v7.13: Emergency overnight charging protection
# - Overnight drain to morning target SOC
# - Dynamic sell thresholds based on available energy
# - Daytime opportunistic selling (morning + midday arbitrage)
# - Ultra-cheap opportunistic charging + sanity checks
# - Configurable battery full thresholds
# - Aggressive 100% by 3pm target (hold until peak)
# - Floor safety buffer for reliable morning SOC
# - Enhanced kiosk displays with Best-N context
#
# v7.13 Changes:
# - NEW: Two-tier spike handling (100Β’ drain-all, 35Β’ forecast-aware)
# - NEW: Emergency overnight charging (Priority 68)
# - NEW: End-of-peak urgency (last 2 periods export regardless)
# - NEW: Peak trickle export at 100W (prevent import drift)
# - NEW: Enhanced kiosk with πβ‘οΈ emojis, buy/sell verbs, Best-N context
# - NEW: Combined SOC display (average both inverters)
# - FIX: Smart charging ONLY during day (disabled overnight)
# - FIX: Overnight window extends to pv_start (not just sunrise)
# - FIX: Remove double PEAK_HOUSE_LOAD_MULTIPLIER application
# - FIX: Shorten decision strings to avoid 255-char limit
# - Static floor calculation (accurate, avoids snapshot volatility)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# STRATEGY CONFIGURATION
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CONFIG = {
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# System Configuration
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"NUM_INVERTERS": 2, # Number of inverters in system
"INVERTER_IDS": [43923, 43924], # For combined SOC averaging
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Battery Thresholds (%)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"BATTERY_FULL_SOC": 100.0, # When battery is "full"
"BATTERY_CURTAILMENT_SOC": 98.0, # Curtail solar at this SOC
"BATTERY_CHARGE_STOP_SOC": 99.0, # Stop forced charging (let solar finish)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Time Windows (hours)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"PEAK_START": 16, # Peak period starts (4pm)
"PEAK_END": 20, # Peak period last hour (8pm = 8:00-8:59pm)
"CHARGE_COMPLETE_HOUR": 15, # Must be at 100% by this hour (3pm)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Price Thresholds (c/kWh)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"MAX_AM_BUY_PRICE": 12.0, # v7.14: Increased from 10.0 for unexpected low-GTI days
"PRE_PEAK_MAX_BUY_PRICE": 12.0, # v8.2: Don't pay more than this for pre-peak charging
"BASE_MIN_SELL_PRICE": 5.0, # Minimum acceptable sell price
"ALWAYS_SELL_PRICE": 35.0, # Spike threshold (with forecast check)
"DRAIN_TO_ZERO_PRICE": 100.0, # Always drain to zero ($1/kWh+)
"SPIKE_MARGIN": 10.0, # Spike must beat overnight buy by this
"DESIRED_MARGIN": 5.0, # Target profit margin above buy price
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Ultra-Cheap Charging
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"ULTRA_CHEAP_BUY_PRICE": 2.0, # Always charge below this (c/kWh)
"OPPORTUNISTIC_DISCOUNT": 0.7, # Charge if 30% cheaper than avg
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Forecast & Uncertainty
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"FUTURE_FORECAST_HOURS": 8, # How far ahead to look
"BUY_UNCERTAINTY_DISCOUNT": 0.03, # Increase buy prices for caution (3%)
"SELL_UNCERTAINTY_DISCOUNT": 0.07, # Decrease sell prices for caution (7%)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Solar Classification (GTI WΒ·h/mΒ²)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"GTI_SUNNY_THRESHOLD": 6000.0,
"GTI_NORMAL_THRESHOLD": 3500.0,
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PV Generation Timing (hours after sunrise, by weather)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"SUNNY_PV_OFFSET": 1.0, # 1h after sunrise on sunny days
"NORMAL_PV_OFFSET": 2.0, # 2h after sunrise on normal days
"RAINY_PV_OFFSET": 3.0, # 3h after sunrise on rainy days
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# House Load (kWh per hour TOTAL SYSTEM)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"HOUSE_LOAD_KWH_PER_HOUR": 2.75, # Total system baseline
"PEAK_HOUSE_LOAD_MULTIPLIER": 1.5, # Peak usage 50% higher
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Floor Calculation
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"SUNNY_FLOOR_SOC": 7.5, # Aggressive (solar will recharge tomorrow)
"NORMAL_FLOOR_SOC": 17.5, # Balanced (moderate recharge expected)
"RAINY_FLOOR_SOC": 30.0, # Conservative (may not recharge)
"FLOOR_SAFETY_BUFFER_PERIODS": 3.0, # v7.14: Increased from 1.5 to prevent intra-period drift
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Export Budgets (kWh per inverter, by weather)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"SUNNY_EXPORT_BUDGET": 20.0,
"NORMAL_EXPORT_BUDGET": 12.5,
"RAINY_EXPORT_BUDGET": 5.0,
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Overnight Drain Strategy
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"TARGET_MORNING_SOC_MIN": 10.0,
"TARGET_MORNING_SOC_MAX": 20.0,
"OVERNIGHT_THRESHOLD_FACTOR": 0.70,
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Daytime Opportunistic Selling
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
"DAYTIME_OPPORTUNISTIC_SELL_PRICE": 5.0,
"DAYTIME_ARBITRAGE_MARGIN": 3.0,
"DAYTIME_SAFETY_MARGIN": 1.5,
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# BEST-N SELECTION PATTERN (v8.1)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Standard algorithm used across multiple decision functions.
# Template for manual inline use (POWSTON doesn't support function-to-function calls).
#
# USED IN:
# - smart_charging() β Find N cheapest buy periods
# - peak_export_best_n() β Find N best sell periods during peak
# - overnight_opportunities() β Find N best sell periods overnight
#
# ALGORITHM:
# 1. Collect candidate periods with (index, hour, price)
# 2. Sort by price:
# - Ascending for BUY (cheapest first)
# - Descending for SELL (highest first)
# 3. Take top N based on energy needs
# 4. Check if current period (index 0) is in Best-N
# 5. Calculate rank and threshold
#
# PATTERN STRUCTURE:
# ```
# # Step 1: Collect periods
# periods = []
# for i in range(len(forecast)):
# ph = (hour_val + i * 0.5) % 24
# if meets_window_criteria(ph):
# periods.append({"index": i, "hour": ph, "price": forecast[i]})
#
# # Step 2: Sort
# sorted_periods = sorted(periods, key=lambda x: x["price"], reverse=is_sell)
#
# # Step 3: Take Best-N
# n_needed = calculate_periods_needed(energy_required, max_power_per_period)
# best_n = sorted_periods[:min(n_needed, len(sorted_periods))]
#
# # Step 4: Check current period
# current_is_good = 0 in [p["index"] for p in best_n]
#
# # Step 5: Calculate rank
# current_rank = None
# for idx, p in enumerate(sorted_periods):
# if p["index"] == 0:
# current_rank = idx + 1
# break
#
# threshold = best_n[-1]["price"] if best_n else 0
# ```
#
# WHY THIS PATTERN:
# - Consistent ranking across all decision points
# - Prevents "good enough" vs "best" confusion
# - Makes debugging easier (same structure everywhere)
# - Allows tuning N without changing algorithm
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# HELPER FUNCTIONS
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def period_hour(base_hour, period_offset):
"""
Calculate hour for a future period, handling midnight wrap.
Args:
base_hour: Starting hour (float, 0-23.99)
period_offset: Number of 30-min periods forward (int)
Returns:
Hour of the target period (float, 0-23.99)
Example:
period_hour(23.5, 2) β 0.5 (23:30 + 1h = 00:30)
"""
return (base_hour + period_offset * 0.5) % 24
def in_window(hour, start, end):
"""
Check if hour is within [start, end) window, handling midnight wrap.
Args:
hour: Current hour (float, 0-23.99)
start: Window start hour (float, 0-23.99)
end: Window end hour (float, 0-23.99)
Returns:
True if hour is in window
Examples:
in_window(18, 16, 21) β True (peak period)
in_window(23, 21, 5) β True (overnight, wraps midnight)
in_window(3, 21, 5) β True (overnight, wraps midnight)
in_window(10, 21, 5) β False (daytime, not in overnight)
"""
if start < end:
# Normal case: window doesn't cross midnight
return start <= hour < end
else:
# Wrap case: window crosses midnight
return hour >= start or hour < end
def hours_between(from_hour, to_hour):
"""
Calculate hours from from_hour to to_hour, handling midnight wrap.
Args:
from_hour: Starting hour (float, 0-23.99)
to_hour: Ending hour (float, 0-23.99)
Returns:
Hours forward (always positive, float)
Examples:
hours_between(16, 21) β 5.0 (4pm to 9pm)
hours_between(23, 5) β 6.0 (11pm to 5am next day)
hours_between(5, 5) β 0.0 (same time)
"""
if from_hour <= to_hour:
return to_hour - from_hour
else:
return (24 - from_hour) + to_hour
def periods_between(from_hour, to_hour):
"""
Calculate number of 30-min periods between hours.
v8.0: Inline logic (POWSTON doesn't support function-to-function calls).
"""
# Inline hours_between logic
if from_hour <= to_hour:
hrs = to_hour - from_hour
else:
hrs = (24 - from_hour) + to_hour
return int(hrs * 2)
def format_time(hour_float):
"""Convert fractional hour to 12-hour format string (e.g., 7.5 β '7:30am')."""
h = int(hour_float)
m = int((hour_float - h) * 60)
period = "am" if h < 12 else "pm"
display_h = h if h <= 12 else h - 12
if display_h == 0:
display_h = 12
return "%d:%02d%s" % (display_h, m, period)
def apply_discount(forecast, hours, discount_rate):
"""Apply exponential discounting to price forecasts."""
if not forecast or hours <= 0:
return []
return [forecast[i] * ((1 + discount_rate) ** i) for i in range(min(hours, len(forecast)))]
def classify_solar(gti, cfg):
"""Classify solar forecast as sunny, normal, or rainy."""
if gti >= cfg["GTI_SUNNY_THRESHOLD"]:
return "sunny"
elif gti >= cfg["GTI_NORMAL_THRESHOLD"]:
return "normal"
return "rainy"
def get_combined_soc(battery_soc_input, inverters_dict, inverter_ids_list):
"""Calculate combined SOC from multiple inverters for display."""
socs = []
for inv_id in inverter_ids_list:
inv_key = 'inverter_params_' + str(inv_id)
if inv_key in inverters_dict:
inv_data = inverters_dict[inv_key]
if 'battery_soc' in inv_data:
soc_val = inv_data['battery_soc']
if isinstance(soc_val, (int, float)):
socs.append(float(soc_val))
if len(socs) > 0:
return sum(socs) / len(socs)
else:
return float(battery_soc_input) if isinstance(battery_soc_input, (int, float)) else 0.0
def compute_evening_premium(buy_fc, sell_fc, hour_val, cfg):
"""
Calculate evening premium: peak sell prices vs all future buy prices.
v8.0: Inline time logic (POWSTON doesn't support function-to-function calls).
"""
peak_start = float(cfg["PEAK_START"])
peak_end_actual = float(cfg["PEAK_END"]) + 1.0
future_buys = []
peak_sells = []
for i in range(min(len(buy_fc), len(sell_fc))):
# Inline period_hour: (hour_val + i * 0.5) % 24
ph = (hour_val + i * 0.5) % 24
# Inline in_window logic
if peak_start < peak_end_actual:
is_peak = peak_start <= ph < peak_end_actual
else:
is_peak = ph >= peak_start or ph < peak_end_actual
if is_peak:
peak_sells.append(sell_fc[i])
else:
future_buys.append(buy_fc[i])
return max(peak_sells) - min(future_buys) if future_buys and peak_sells else 0.0
def compute_peak_working_floor(hour_val, solar_class, sunrise_val, battery_wh, cfg):
"""
v7.13: Calculate working floor during peak with STATIC house load buffer.
v8.0: Inline time logic (POWSTON doesn't support function-to-function calls).
Recalculates every period - any deviation from predicted usage shows up
as more/less exportable energy naturally.
"""
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FLOOR COMPONENT: Battery Capacity
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
battery_kwh = battery_wh / 1000.0
peak_end_actual_val = float(cfg["PEAK_END"] + 1)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FLOOR COMPONENT: Base Floor Selection
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if solar_class == "sunny":
base_floor = cfg["SUNNY_FLOOR_SOC"]
elif solar_class == "rainy":
base_floor = cfg["RAINY_FLOOR_SOC"]
else:
base_floor = cfg["NORMAL_FLOOR_SOC"]
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FLOOR COMPONENT: Overnight Reserve Calculation
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# Hours from 9pm to sunrise
if peak_end_actual_val <= sunrise_val:
hours_to_sunrise = sunrise_val - peak_end_actual_val
else:
hours_to_sunrise = (24 - peak_end_actual_val) + sunrise_val
overnight_kwh = hours_to_sunrise * cfg["HOUSE_LOAD_KWH_PER_HOUR"]
overnight_reserve_soc = (overnight_kwh / battery_kwh) * 100.0
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FLOOR COMPONENT: Safety Buffer Calculation
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
safety_kwh = cfg["FLOOR_SAFETY_BUFFER_PERIODS"] * 0.5 * cfg["HOUSE_LOAD_KWH_PER_HOUR"]
safety_buffer_soc = (safety_kwh / battery_kwh) * 100.0
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FLOOR COMPONENT: Floor Composition
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
floor_at_9pm = base_floor + overnight_reserve_soc + safety_buffer_soc
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# PEAK-SPECIFIC: Stepping Buffer (decreases as we approach 9pm)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if hour_val <= peak_end_actual_val:
hrs_to_9pm = peak_end_actual_val - hour_val
else:
hrs_to_9pm = (24 - hour_val) + peak_end_actual_val
periods_until_9pm = max(0, int(hrs_to_9pm * 2))
if periods_until_9pm > 0:
house_per_period_kwh = (
cfg["HOUSE_LOAD_KWH_PER_HOUR"] # 2.75 kWh/h TOTAL system
* 0.5 # period duration
* cfg["PEAK_HOUSE_LOAD_MULTIPLIER"] # 1.5Γ
)
peak_buffer_kwh = house_per_period_kwh * periods_until_9pm
peak_buffer_soc = (peak_buffer_kwh / battery_kwh) * 100.0
else:
peak_buffer_soc = 0.0
working_floor = floor_at_9pm + peak_buffer_soc
return {
"working_floor": max(0.0, min(100.0, working_floor)),
"floor_at_9pm": floor_at_9pm,
"peak_buffer_soc": peak_buffer_soc,
"periods_until_9pm": periods_until_9pm,
"overnight_reserve_soc": overnight_reserve_soc,
"overnight_hours": hours_to_sunrise,
"safety_buffer_soc": safety_buffer_soc,
}
def peak_export_best_n(soc, sell_fc, sell_now, hour_val, working_floor, battery_wh, max_discharge_kwh, cfg):
"""
v7.13: Peak export using Best-N strategy with end-of-peak urgency.
NEW: Last 2 periods of peak, export whatever's available regardless of ranking.
"""
peak_end_actual_val = float(cfg["PEAK_END"] + 1)
battery_kwh = battery_wh / 1000.0
exportable_kwh = max(0.0, ((soc - working_floor) / 100.0) * battery_kwh)
if exportable_kwh <= 0:
return {
"should_export": False,
"priority": 60,
"reason": "At floor %.1f%%" % working_floor,
"exportable_kwh": 0,
}
periods_needed = max(1, int(exportable_kwh / max_discharge_kwh + 0.999))
periods_available = max(0, int((peak_end_actual_val - hour_val) * 2))
if periods_available <= 0:
return {"should_export": False, "priority": 60, "reason": "Past peak"}
# NEW v7.13: End-of-peak urgency
if periods_available <= 2 and exportable_kwh > 0:
return {
"should_export": True,
"priority": 60,
"reason": "End-peak urgent (%.1fkWh, %dp left)" % (exportable_kwh, periods_available),
"exportable_kwh": exportable_kwh,
}
# Best-N ranking
peak_prices = sell_fc[:periods_available]
if not peak_prices:
return {"should_export": False, "priority": 60, "reason": "No forecast"}
sorted_prices = sorted(peak_prices, reverse=True)
best_n_threshold = sorted_prices[min(periods_needed - 1, len(sorted_prices) - 1)]
if sell_now >= best_n_threshold:
rank = sum(1 for p in sorted_prices if p > sell_now) + 1
return {
"should_export": True,
"priority": 60,
"reason": "Peak Best-N @ %.2fc (rank %d/%d)" % (
sell_now, rank, periods_available
),
"exportable_kwh": exportable_kwh,
"rank": rank,
"periods_available": periods_available,
}
# Not in best-N - find when to export for kiosk
best_period_idx = peak_prices.index(max(peak_prices))
best_hour = hour_val + (best_period_idx * 0.5)
return {
"should_export": False,
"priority": 60,
"reason": "Hold for better (%.2fc < %.2fc)" % (sell_now, best_n_threshold),
"exportable_kwh": exportable_kwh,
"best_n_threshold": best_n_threshold,
"next_export_hour": best_hour,
"next_export_price": max(peak_prices),
"next_export_rank": 1,
}
def compute_floor(solar_class, evening_premium, soc, hour_val, sunrise_val, battery_wh, cfg):
"""
Compute dynamic SOC floor for POST-PEAK period (after 9pm).
v8.0: Inline time logic (POWSTON doesn't support function-to-function calls).
"""
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FLOOR COMPONENT: Battery Capacity
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
battery_kwh = battery_wh / 1000.0
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FLOOR COMPONENT: Base Floor Selection
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
if solar_class == "sunny":
base_floor = cfg["SUNNY_FLOOR_SOC"]
base_budget = cfg["SUNNY_EXPORT_BUDGET"]
elif solar_class == "rainy":
base_floor = cfg["RAINY_FLOOR_SOC"]
base_budget = cfg["RAINY_EXPORT_BUDGET"]
else:
base_floor = cfg["NORMAL_FLOOR_SOC"]
base_budget = cfg["NORMAL_EXPORT_BUDGET"]
peak_start_val = float(cfg["PEAK_START"])
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FLOOR COMPONENT: Overnight Reserve Calculation
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# v8.4 FIX: Recognize overnight (after midnight, before sunrise) as post-peak
# This prevents using peak_startβsunrise (12.8h) when we should use currentβsunrise (2-3h)
# Check if we're in overnight period (after midnight, before sunrise)
is_overnight = hour_val < sunrise_val
if is_overnight:
# OVERNIGHT (12 AM - sunrise): Calculate from current time to sunrise
# At 2 AM with 4:48 sunrise: 2.8h reserve, not 12.8h!
hours_to_sunrise = sunrise_val - hour_val
elif hour_val < peak_start_val:
# TRUE PRE-PEAK (sunrise - 4 PM): Use peak start to sunrise
# This is daytime before peak, solar is generating
if peak_start_val <= sunrise_val:
hours_to_sunrise = sunrise_val - peak_start_val
else:
hours_to_sunrise = (24 - peak_start_val) + sunrise_val
else:
# POST-PEAK (4 PM - midnight): Use current time to sunrise with wrap
if hour_val <= sunrise_val:
hours_to_sunrise = sunrise_val - hour_val
else:
hours_to_sunrise = (24 - hour_val) + sunrise_val
overnight_kwh = hours_to_sunrise * cfg["HOUSE_LOAD_KWH_PER_HOUR"]
overnight_reserve_soc = (overnight_kwh / battery_kwh) * 100.0
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FLOOR COMPONENT: Safety Buffer Calculation
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
safety_kwh = cfg["FLOOR_SAFETY_BUFFER_PERIODS"] * 0.5 * cfg["HOUSE_LOAD_KWH_PER_HOUR"]
safety_buffer_soc = (safety_kwh / battery_kwh) * 100.0
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# FLOOR COMPONENT: Floor Composition
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# v8.4: Overnight uses post-peak logic (not pre-peak)
if is_overnight or hour_val >= peak_start_val:
# OVERNIGHT or POST-PEAK: Same import and export floors
import_floor = base_floor + overnight_reserve_soc + safety_buffer_soc
export_floor = base_floor + overnight_reserve_soc + safety_buffer_soc
else:
# TRUE PRE-PEAK (daytime before peak): Full import floor, calculated export floor
import_floor = cfg["BATTERY_FULL_SOC"]
export_floor = base_floor + overnight_reserve_soc + safety_buffer_soc
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# POST-PEAK SPECIFIC: Arbitrage Budget
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
low = cfg["DESIRED_MARGIN"]
high = 2 * cfg["DESIRED_MARGIN"]
if evening_premium <= low:
budget_factor = 0.0
elif evening_premium <= high:
budget_factor = 0.5
else:
budget_factor = 1.0
budget = base_budget * budget_factor
available_kwh = max(0.0, (soc - export_floor) / 100.0 * battery_kwh)
budget = min(budget, available_kwh)
return {
"import_floor": max(0.0, import_floor),
"export_floor": max(0.0, export_floor),
"budget": budget,
"overnight_reserve_soc": overnight_reserve_soc,
"overnight_hours": hours_to_sunrise,
"safety_buffer_soc": safety_buffer_soc,
}
def smart_charging(soc, export_floor, buy_fc, sell_fc, buy_now, hour_val, battery_wh, max_charge_kwh, sunrise_hour_val, cfg):
"""
v7.13: Smart charging ONLY during DAY period (sunrise β peak).
v7.14: Added pre-dawn hard block (sunrise - 2h) to prevent early-AM triggers.
FIXED: No longer runs overnight - prevents midnight imports.
"""
peak_start_val = float(cfg["PEAK_START"])
# v7.14 Change C: Block charging more than 2h before sunrise
# This prevents 1-3am Best-N triggers regardless of price ranking
pre_dawn_cutoff = sunrise_hour_val - 2.0
# Handle midnight wrap-around
if hour_val > 12 and pre_dawn_cutoff < 0:
pre_dawn_cutoff = pre_dawn_cutoff + 24
# Block if we're in the pre-dawn window (more than 2h before sunrise)
if hour_val < 12: # Early morning hours
if hour_val < pre_dawn_cutoff:
return {"should_charge": False, "priority": 50, "reason": "Pre-dawn block"}
else: # Evening/night hours
if pre_dawn_cutoff > 12 and hour_val < pre_dawn_cutoff:
return {"should_charge": False, "priority": 50, "reason": "Pre-dawn block"}
# CRITICAL: Only run during daytime, not overnight
if hour_val >= peak_start_val:
return {"should_charge": False, "priority": 50, "reason": "auto (past charge window)"}
if not buy_fc:
return {"should_charge": False, "priority": 50, "reason": "auto (no forecast)"}
battery_kwh = battery_wh / 1000.0
target_soc = cfg["BATTERY_FULL_SOC"]
# v8.0: Don't charge if already at/above target
# This allows curtailment (Priority 42) to run during negative FiT
if soc >= target_soc:
return {"should_charge": False, "priority": 50, "reason": "Battery full"}
energy_needed = ((target_soc - soc) / 100.0) * battery_kwh
periods_needed = max(1, int(energy_needed / max_charge_kwh + 0.999))
deadline = float(cfg["CHARGE_COMPLETE_HOUR"])
periods_available = int((deadline - hour_val) * 2)
if periods_available <= 0:
return {"should_charge": False, "priority": 50, "reason": "Past deadline"}
buffer = periods_available - periods_needed
max_am_buy = float(cfg["MAX_AM_BUY_PRICE"])
# Floor protection
if soc < export_floor and buy_now > max_am_buy:
peak_idx = int((peak_start_val - hour_val) * 2)
peak_end_actual_val = float(cfg["PEAK_END"] + 1)
peak_sells = (
sell_fc[peak_idx:peak_idx + int((peak_end_actual_val - peak_start_val) * 2)]
if peak_idx < len(sell_fc)
else []
)
avg_peak_sell = sum(peak_sells) / len(peak_sells) if peak_sells else 0
energy_to_floor = max(0.0, ((export_floor - soc) / 100.0) * battery_kwh)
cost = energy_to_floor * (buy_now / 100.0)
revenue = min(energy_to_floor, 20.0) * (avg_peak_sell / 100.0)
future_buys = buy_fc[:periods_available]
min_buy = min(future_buys) if future_buys else 9999
if buy_now < min_buy:
return {
"should_charge": True,
"priority": 45,
"reason": "Floor cheapest @ %.2fc" % buy_now,
}
elif revenue > cost:
return {
"should_charge": True,
"priority": 45,
"reason": "Floor profitable",
}
elif periods_needed >= periods_available:
return {
"should_charge": True,
"priority": 48,
"reason": "Floor urgent",
}
# Urgent mode
if buffer <= 0:
if buy_now <= max_am_buy:
return {
"should_charge": True,
"priority": 50,
"reason": "Urgent @ %.2fc" % buy_now,
}
else:
return {
"should_charge": False,
"priority": 50,
"reason": "Urgent but too expensive",
}
# Best-N selection
future_prices = buy_fc[:periods_available]
if not future_prices:
return {"should_charge": False, "priority": 50, "reason": "No forecast"}
sorted_prices = sorted(future_prices)
best_n_threshold = sorted_prices[min(periods_needed - 1, len(sorted_prices) - 1)]
# v8.2: Reject if price exceeds pre-peak ceiling (even if Best-N)
# Prevents 16.5Β’ imports when almost full
pre_peak_max = float(cfg["PRE_PEAK_MAX_BUY_PRICE"])
if buy_now > pre_peak_max:
return {
"should_charge": False,
"priority": 50,
"reason": "Too expensive @ %.2fc (max %.2fc)" % (buy_now, pre_peak_max),
}
if buy_now <= best_n_threshold:
rank = sum(1 for p in sorted_prices if p < buy_now) + 1
return {
"should_charge": True,
"priority": 50,
"reason": "Best-N @ %.2fc (rank %d/%d)" % (buy_now, rank, periods_available),
}
return {
"should_charge": False,
"priority": 50,
"reason": "Wait for better (threshold %.2fc)" % best_n_threshold,
}
def overnight_opportunities(sell_fc, hour_val, sunrise_val, soc, battery_wh, max_discharge_kwh, cfg):
"""
Analyze overnight sell opportunities (from PEAK_END to sunrise).
v8.0: Inline time logic (POWSTON doesn't support function-to-function calls).
"""
if not sell_fc:
return None
target = (cfg["TARGET_MORNING_SOC_MIN"] + cfg["TARGET_MORNING_SOC_MAX"]) / 2.0
drain_kwh = max(0.0, ((soc - target) / 100.0) * (battery_wh / 1000.0))
peak_end_actual_val = float(cfg["PEAK_END"] + 1)
periods = []
for i in range(len(sell_fc)):
# v8.0: Inline period_hour logic
ph = (hour_val + i * 0.5) % 24
# v8.0: Inline in_window logic
if peak_end_actual_val < sunrise_val:
is_overnight = peak_end_actual_val <= ph < sunrise_val
else:
is_overnight = ph >= peak_end_actual_val or ph < sunrise_val
if is_overnight:
periods.append({"index": i, "hour": ph, "price": sell_fc[i]})
if not periods:
return None
periods = sorted(periods, key=lambda x: x["price"], reverse=True)
needed = max(1, int(drain_kwh / max_discharge_kwh + 0.999))
best = periods[:min(needed, len(periods))]
current_rank = None
for idx in range(len(periods)):
if periods[idx]["index"] == 0:
current_rank = idx + 1
break
return {
"has_opportunities": True,
"best_periods": best,
"current_is_good": 0 in [p["index"] for p in best],
"current_rank": current_rank,
"total_periods": len(periods),
"periods_needed": needed,
"worst_acceptable_price": best[-1]["price"] if best else 0,
}
def next_best(forecast, hour_val, end_val):
"""Find next best opportunity in forecast with formatted time."""
if not forecast:
return None
periods = [
{"index": i, "hour": hour_val + i * 0.5, "price": forecast[i]}
for i in range(1, len(forecast))
if hour_val + i * 0.5 < end_val
]
if not periods:
return None
periods = sorted(periods, key=lambda x: x["price"])
# Inline time formatting to avoid function dependency
best_hour = periods[0]["hour"]
h = int(best_hour)
m = int((best_hour - h) * 60)
period = "am" if h < 12 else "pm"
display_h = h if h <= 12 else h - 12
if display_h == 0:
display_h = 12
hour_formatted = "%d:%02d%s" % (display_h, m, period)
return {
"hour": periods[0]["hour"],
"hour_formatted": hour_formatted,
"price": round(periods[0]["price"], 2),
"periods_away": periods[0]["index"],
}
def build_forecast_timeline(buy_fc, sell_fc, hour_val, sc_info, peak_info, cfg):
"""
v7.14: Build compact forecast timeline showing next 8 periods.
v8.0: Inline time logic (POWSTON doesn't support function-to-function calls).
v8.3: Add π ultra-cheap and π΅ negative buy icons.
Returns string like: "Next 4h: π΅πβ‘β‘ββπ°π°"
"""
if not buy_fc or not sell_fc:
return ""
icons = []
max_periods = min(8, len(buy_fc), len(sell_fc))
peak_start = float(cfg["PEAK_START"])
peak_end = float(cfg["PEAK_END"]) + 1.0
ultra_cheap = float(cfg["ULTRA_CHEAP_BUY_PRICE"])
for i in range(max_periods):
# v8.0: Inline period_hour logic
ph = (hour_val + i * 0.5) % 24
buy_price = buy_fc[i]
sell_price = sell_fc[i]
# v8.0: Inline in_window logic for peak check
if peak_start < peak_end:
is_peak = peak_start <= ph < peak_end
else:
is_peak = ph >= peak_start or ph < peak_end
# Peak period logic
if is_peak:
# Check if in Best-N sell periods
best_n_thr = peak_info.get("best_n_threshold", 999) if peak_info else 999
if sell_price >= best_n_thr:
icon = "π°"
else:
icon = "β"
# v8.3: Check for negative buy price (rare but valuable)
elif buy_price < 0:
icon = "π΅"
# v8.3: Check for ultra-cheap buy
elif buy_price <= ultra_cheap:
icon = "π"
# Day period - check for charging
elif sc_info and sc_info.get("should_charge"):
# Simple heuristic: if price is below current, it's a buy candidate
if buy_price <= buy_fc[0]:
icon = "β‘"
else:
icon = "β"
# Check for sell opportunities
elif sell_price >= float(cfg["BASE_MIN_SELL_PRICE"]):
icon = "π°"
# Negative FiT
elif sell_price < 0:
icon = "π«"
else:
icon = "β"
icons.append(icon)
timeline = "".join(icons)
hours_covered = max_periods * 0.5
return "Next %.0fh: %s" % (hours_covered, timeline)
def build_kiosk_info(
time_period,
pv_kwh,
load_kwh,
surplus_deficit,
hour_val,
sunrise_hour_val,
battery_soc,
floor_soc,
battery_kwh,
sell_price_val,
next_charge_info,
next_discharge_info,
opp_analysis,
house_load_per_hour,
num_inverters,
floor_info,
peak_export_info,
forecast_timeline
):
"""
v7.13: Enhanced kiosk with πβ‘οΈ emojis, buy/sell verbs, and Best-N context.
v7.14: Added forecast timeline and improved contrast.
"""
try:
pv_kwh = float(pv_kwh) if pv_kwh is not None else 0.0
load_kwh = float(load_kwh) if load_kwh is not None else 0.0
surplus_deficit = float(surplus_deficit) if surplus_deficit is not None else 0.0
battery_soc = float(battery_soc) if battery_soc is not None else 0.0
floor_soc = float(floor_soc) if floor_soc is not None else 0.0
battery_kwh = float(battery_kwh) if battery_kwh is not None and battery_kwh > 0 else 50.0
sell_price_val = float(sell_price_val) if sell_price_val is not None else 0.0
if time_period == "Day":
# v7.14: Better contrast symbols, timeline, restored next charge info
base = "π%dkWh β‘οΈ%dkWh" % (int(pv_kwh), int(load_kwh))
# Better contrast for surplus/deficit
if surplus_deficit >= 0:
base = base + " β%dkWh" % int(surplus_deficit)
else:
base = base + " β%dkWh" % int(abs(surplus_deficit))
# Add timeline
if forecast_timeline:
base = base + " | " + forecast_timeline
# Show next charge opportunity (restored from v7.12)
if next_charge_info and next_charge_info.get("hour_formatted"):
base = base + " | β‘%s@%.1fc" % (
next_charge_info["hour_formatted"], next_charge_info["price"]
)
elif surplus_deficit < 0:
base = base + " | No cheap buys"
elif time_period == "Peak":
avail_kwh = ((battery_soc - floor_soc) / 100.0) * battery_kwh
soc_above_floor = battery_soc - floor_soc
if avail_kwh > 0:
base = "π %.0f%% (%.0f%% above floor) | %.1fkWh" % (
battery_soc, soc_above_floor, avail_kwh
)
else:
if floor_info:
overnight_kwh = floor_info.get("overnight_hours", 0) * house_load_per_hour * num_inverters