Skip to content

Commit 844d39c

Browse files
committed
Convert Bash script to Python for manual inverter interaction
1 parent a5fa776 commit 844d39c

File tree

2 files changed

+82
-73
lines changed

2 files changed

+82
-73
lines changed

.flake8

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,6 @@ select = A,B,C,E,F,W,T4,B9
66
suppress-non-returning = true
77
kwargs-ignore-function-pattern-extend = (options|load_only)$
88
per-file-ignores =
9-
tests/*:ANN001,ANN201, ANN401
9+
inverter:E402
1010
extend-exclude =
1111
.venv/

inverter

+81-72
Original file line numberDiff line numberDiff line change
@@ -1,78 +1,87 @@
1-
#!/usr/bin/env bash
1+
#!/usr/bin/env python3.11
2+
import getpass
3+
import glob
4+
import os
5+
import sys
26

3-
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
47

5-
source "${SCRIPT_DIR}"/.venv/bin/activate
6-
cd "${SCRIPT_DIR}"/source || exit 1
8+
def setup() -> None:
9+
script_dir = os.path.dirname(os.path.realpath(__file__))
10+
venv_path = os.path.join(script_dir, ".venv")
11+
source_path = os.path.join(script_dir, "source")
12+
13+
if not os.path.exists(venv_path):
14+
print("Error: Virtual environment does not exist.")
15+
sys.exit(1)
16+
17+
possible_site_packages = glob.glob(os.path.join(venv_path, "lib", "python*", "site-packages"))
18+
if not possible_site_packages:
19+
print("Error: Could not find site-packages in the virtual environment.")
20+
sys.exit(1)
21+
22+
if not os.path.exists(source_path):
23+
print("Error: Source directory does not exist.")
24+
sys.exit(1)
25+
26+
sys.path.append(source_path)
27+
sys.path.append(possible_site_packages[0])
28+
29+
30+
def print_help_and_exit() -> None:
31+
print("This script allows you to interact with the inverter.")
32+
print("")
33+
print("You have to supply one of the following arguments:")
34+
print(" --status Get the current state of charge and operation mode of the inverter")
35+
print(" --mode {GENERAL,ECO_CHARGE} Set the operation mode of the inverter")
36+
print(" --tibber Fetches, displays the tibber rates and writes them to the database")
37+
print("")
38+
print("It uses all the variables defined in the .env file")
39+
sys.exit(1)
40+
41+
42+
if sys.argv[1] == "--mode" and (len(sys.argv) != 3 or sys.argv[2] not in ["GENERAL", "ECO_CHARGE"]):
43+
print('Unsupported mode, valid modes are "GENERAL" and "ECO_CHARGE"\n')
44+
print_help_and_exit()
45+
if len(sys.argv) < 2 or sys.argv[1] not in ["--status", "--mode", "--tibber"]:
46+
print_help_and_exit()
47+
48+
setup()
749

8-
read -r -d '' inverter_setup_code <<EOF
9-
from logger import LoggerMixin
1050
from goodwe.et import OperationMode
1151
from inverter import Inverter
12-
13-
LoggerMixin().log.info("Inverter is manually controlled by the user ${USER}")
14-
15-
inverter = Inverter(True)
16-
EOF
17-
18-
19-
if [[ ! ${1} =~ ^(--status|--mode|--tibber)$ ]]; then
20-
echo "This script allows you to interact with the inverter."
21-
echo ""
22-
echo "You have to supply one of the following arguments:"
23-
echo " --status Get the current state of charge and operation mode of the inverter"
24-
echo " --mode {GENERAL,ECO_CHARGE} Set the operation mode of the inverter"
25-
echo " --tibber Fetches, displays the tibber rates and writes them to the database"
26-
echo ""
27-
echo "It uses the all the variables defined in the .env file"
28-
exit 1
29-
fi
30-
31-
if [[ ${1} == "--status" ]]; then
32-
python3 - << EOF
33-
${inverter_setup_code}
34-
try:
35-
mode = inverter.get_operation_mode(True).name
36-
soc = inverter.get_state_of_charge(True)
37-
print(f"SoC: {soc} %\nmode: {mode}")
38-
except Exception as e:
39-
inverter.log.exception(e)
40-
exit(1)
41-
EOF
42-
exit $?
43-
fi
44-
45-
if [[ ${1} == "--mode" ]]; then
46-
if [[ ! ${2} =~ ^(GENERAL|ECO_CHARGE)$ ]]; then
47-
echo "Unsupported mode, valid modes are \"GENERAL\" and \"ECO_CHARGE\""
48-
exit 1
49-
fi
50-
51-
python3 - << EOF
52-
${inverter_setup_code}
53-
try:
54-
last_mode = inverter.get_operation_mode(True).name
55-
inverter.set_operation_mode(OperationMode.${2})
56-
print(f"last mode: {last_mode}\nnew mode: ${2}")
57-
except Exception as e:
58-
inverter.log.exception(e)
59-
exit(1)
60-
EOF
61-
exit $?
62-
fi
63-
64-
if [[ ${1} == "--tibber" ]]; then
65-
python3 - << EOF
52+
from logger import LoggerMixin
6653
from tibber_api_handler import TibberAPIHandler
67-
try:
68-
tibber_api_handler = TibberAPIHandler()
69-
api_result = tibber_api_handler._fetch_upcoming_prices_from_api()
70-
all_energy_rates = tibber_api_handler._extract_energy_rates_from_api_response(api_result)
71-
tibber_api_handler._remove_energy_rates_from_the_past(all_energy_rates)
72-
tibber_api_handler.write_energy_rates_to_database(all_energy_rates)
73-
except Exception as e:
74-
tibber_api_handler.log.exception(e)
75-
exit(1)
76-
EOF
77-
exit $?
78-
fi
54+
55+
logger = LoggerMixin()
56+
logger.log.info(f"Inverter is manually controlled by the user {getpass.getuser()}")
57+
58+
if sys.argv[1] == "--status":
59+
try:
60+
inverter = Inverter(True)
61+
soc = inverter.get_state_of_charge(True)
62+
mode = inverter.get_operation_mode(True).name
63+
print(f"SoC: {soc} %\nmode: {mode}")
64+
except Exception as e:
65+
logger.log.exception(e)
66+
sys.exit(1)
67+
68+
if sys.argv[1] == "--mode":
69+
try:
70+
inverter = Inverter(True)
71+
last_mode = inverter.get_operation_mode(True).name
72+
inverter.set_operation_mode(OperationMode[sys.argv[2]])
73+
print(f"last mode: {last_mode}\nnew mode: ${2}")
74+
except Exception as e:
75+
logger.log.exception(e)
76+
sys.exit(1)
77+
78+
if sys.argv[1] == "--tibber":
79+
try:
80+
tibber_api_handler = TibberAPIHandler()
81+
api_result = tibber_api_handler._fetch_upcoming_prices_from_api()
82+
all_energy_rates = tibber_api_handler._extract_energy_rates_from_api_response(api_result)
83+
tibber_api_handler._remove_energy_rates_from_the_past(all_energy_rates)
84+
tibber_api_handler.write_energy_rates_to_database(all_energy_rates)
85+
except Exception as e:
86+
logger.log.exception(e)
87+
exit(1)

0 commit comments

Comments
 (0)