Skip to content

Commit

Permalink
align exec scripts
Browse files Browse the repository at this point in the history
install service script + make it work with virtualenvs
cmd do not need to be part of config
remove piTFT exec script (obsolete + in documentation already)
  • Loading branch information
Ptosiek committed Sep 27, 2023
1 parent 931f35d commit d78b74a
Show file tree
Hide file tree
Showing 17 changed files with 97 additions and 90 deletions.
12 changes: 0 additions & 12 deletions exec-mip.sh

This file was deleted.

22 changes: 0 additions & 22 deletions exec-service.sh

This file was deleted.

9 changes: 0 additions & 9 deletions exec.sh

This file was deleted.

45 changes: 45 additions & 0 deletions install.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#!/bin/bash

current_dir=$(pwd)
script="$current_dir/pizero_bikecomputer.py"

i_service_file="$current_dir/scripts/install/etc/systemd/system/pizero_bikecomputer.service"
o_service_file="/etc/systemd/system/pizero_bikecomputer.service"

read -p "Using TFT/XWindow? [y/n] (n): " use_x

# check if venv is set, in that case default to using thi venv to run the script
#read -p "Use current virtualenv? [y/n] (y): " use_venv

if [[ -n "$VIRTUAL_ENV" ]]; then
script="$VIRTUAL_ENV/bin/python $script"
else
echo "No virtualenv used/activated. Default python will be used"
fi

if [[ "$use_x" == "y" ]]; then
# add fullscreen option
script="$script -f"
envs="Environment=\"QT_QPA_PLATFORM=xcb\"\\nEnvironment=\"DISPLAY=:0\"\\nEnvironment=\"XAUTHORITY=/home/$USER/.Xauthority\"\\n"
after="After=display-manager.service\\n"
else
envs="Environment=\"QT_QPA_PLATFORM=offscreen\"\\nEnvironment=\"PYUSB_DEBUG=critical\"\\n"
after=""
fi

if [ -f "$i_service_file" ]; then
content=$(<"$i_service_file")
content="${content/WorkingDirectory=/WorkingDirectory=$current_dir}"
content="${content/ExecStart=/ExecStart=$script}"
content="${content/User=/User=$USER}"
content="${content/Group=/Group=$USER}"

# inject environment variables
content=$(echo "$content" | sed "/\[Install\]/i $envs")

if [[ -n "$after" ]]; then
content=$(echo "$content" | sed "/\[Service\]/i $after")
fi
echo "$content" | sudo tee $o_service_file > /dev/null
sudo systemctl enable pizero_bikecomputer
fi
46 changes: 10 additions & 36 deletions modules/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import socket
import asyncio
import shutil
import subprocess
import traceback
import math

Expand All @@ -27,6 +26,7 @@
from logger import CustomRotatingFileHandler, app_logger
from modules.helper.setting import Setting
from modules.button_config import Button_Config
from modules.utils.cmd import exec_cmd, exec_cmd_return_value
from modules.utils.timer import Timer


Expand Down Expand Up @@ -984,30 +984,6 @@ def press_button(self, button_hard, press_button, index):
def change_mode(self):
self.button_config.change_mode()

@staticmethod
def exec_cmd(cmd, cmd_print=True):
if cmd_print:
app_logger.info(cmd)
try:
subprocess.run(cmd)
except Exception: # noqa
app_logger.exception(f"Failed executing {cmd}")

@staticmethod
def exec_cmd_return_value(cmd, cmd_print=True):
if cmd_print:
app_logger.info(cmd)
try:
p = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
string = p.stdout.decode("utf8").strip()
return string
except Exception: # noqa
app_logger.exception(f"Failed executing {cmd}")

async def kill_tasks(self):
tasks = asyncio.all_tasks()
current_task = asyncio.current_task()
Expand Down Expand Up @@ -1051,33 +1027,33 @@ async def quit(self):
def poweroff(self):
if self.G_IS_RASPI:
cmd = ["sudo", "systemctl", "start", "pizero_bikecomputer_shutdown.service"]
self.exec_cmd(cmd)
exec_cmd(cmd)

def reboot(self):
if self.G_IS_RASPI:
cmd = ["sudo", "reboot"]
self.exec_cmd(cmd)
exec_cmd(cmd)

def hardware_wifi_bt_on(self):
if self.G_IS_RASPI:
cmd = [os.path.join(self.G_INSTALL_PATH, "scripts/comment_out.sh")]
self.exec_cmd(cmd)
exec_cmd(cmd)

def hardware_wifi_bt_off(self):
if self.G_IS_RASPI:
cmd = [os.path.join(self.G_INSTALL_PATH, "scripts/uncomment.sh")]
self.exec_cmd(cmd)
exec_cmd(cmd)

def update_application(self):
if self.G_IS_RASPI:
cmd = ["git", "pull", "origin", "master"]
self.exec_cmd(cmd)
exec_cmd(cmd)
self.restart_application()

def restart_application(self):
if self.G_IS_RASPI:
cmd = ["sudo", "systemctl", "restart", "pizero_bikecomputer.service"]
self.exec_cmd(cmd)
exec_cmd(cmd)

def detect_network(self):
try:
Expand All @@ -1092,14 +1068,12 @@ def detect_network(self):

def get_wifi_bt_status(self):
if not self.G_IS_RASPI:
return (False, False)
return False, False

status = {"wlan": False, "bluetooth": False}
try:
# json option requires raspbian buster
raw_status = self.exec_cmd_return_value(
["rfkill", "--json"], cmd_print=False
)
raw_status = exec_cmd_return_value(["rfkill", "--json"], cmd_print=False)
json_status = json.loads(raw_status)
for l in json_status[""]:
if "type" not in l or l["type"] not in ["wlan", "bluetooth"]:
Expand Down Expand Up @@ -1127,7 +1101,7 @@ def onoff_wifi_bt(self, key=None):
}
status = {}
status["Wifi"], status["Bluetooth"] = self.get_wifi_bt_status()
self.exec_cmd(onoff_cmd[key][status[key]])
exec_cmd(onoff_cmd[key][status[key]])

async def bluetooth_tethering(self, disconnect=False):
if not self.G_IS_RASPI:
Expand Down
5 changes: 3 additions & 2 deletions modules/display/pitft_28_r.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from modules.utils.cmd import exec_cmd
from logger import app_logger

_SENSOR_DISPLAY = True
Expand Down Expand Up @@ -42,6 +43,6 @@ def quit(self):

def change_brightness(self):
if _SENSOR_DISPLAY:
self.brightness_index = not (self.brightness_index)
self.brightness_index = not self.brightness_index
cmd = self.brightness_cmd[int(self.brightness_index)]
self.config.exec_cmd(cmd)
exec_cmd(cmd)
3 changes: 2 additions & 1 deletion modules/logger/logger_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import datetime
import shutil

from modules.utils.cmd import exec_cmd
from .logger import Logger


Expand Down Expand Up @@ -56,7 +57,7 @@ def write_log(self):
+ filename
)
sqlite3_cmd = ["sh", "-c", sql_cmd]
self.config.exec_cmd(sqlite3_cmd)
exec_cmd(sqlite3_cmd)
else:
f = open(filename, "w", encoding="UTF-8")

Expand Down
3 changes: 2 additions & 1 deletion modules/logger_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import numpy as np
from crdp import rdp

from modules.utils.cmd import exec_cmd
from logger import app_logger


Expand Down Expand Up @@ -166,7 +167,7 @@ async def restore_utc_time(self):
"--set",
utctime.strftime("%Y/%m/%d %H:%M:%S"),
]
self.config.exec_cmd(datecmd)
exec_cmd(datecmd)

async def quit(self):
await self.sensor.quit()
Expand Down
7 changes: 4 additions & 3 deletions modules/sensor/sensor_gps.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import re
import numpy as np

from modules.utils.cmd import exec_cmd, exec_cmd_return_value
from logger import app_logger
from .sensor import Sensor

Expand Down Expand Up @@ -594,7 +595,7 @@ def set_timezone(self):
if np.isnan(lat) or np.isnan(lon):
return False
tzcmd = ["python3", "./scripts/set_timezone.py", str(lat), str(lon)]
self.config.G_TIMEZONE = self.config.exec_cmd_return_value(tzcmd)
self.config.G_TIMEZONE = exec_cmd_return_value(tzcmd)
return True

def get_utc_time_from_datetime(self, gps_time):
Expand Down Expand Up @@ -625,7 +626,7 @@ def set_time(self):
l_time = parser.parse(self.values["time"])
# kernel version date
kernel_date = datetime.datetime(2019, 1, 1, 0, 0, 0, 0, tz.tzutc())
kernel_date_str = self.config.exec_cmd_return_value(["uname", "-v"])
kernel_date_str = exec_cmd_return_value(["uname", "-v"])
# "#1253 Thu Aug 15 11:37:30 BST 2019"
if len(kernel_date_str) >= 34:
m = re.search(r"^.+(\w{3}) (\d+).+(\d{4})$", kernel_date_str)
Expand All @@ -637,7 +638,7 @@ def set_time(self):
if l_time < kernel_date:
return False
datecmd = ["sudo", "date", "-u", "--set", l_time.strftime("%Y/%m/%d %H:%M:%S")]
self.config.exec_cmd(datecmd)
exec_cmd(datecmd)
return True

def get_course_index(self):
Expand Down
27 changes: 27 additions & 0 deletions modules/utils/cmd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import subprocess

from logger import app_logger


def exec_cmd(cmd, cmd_print=True):
if cmd_print:
app_logger.info(cmd)
try:
subprocess.run(cmd)
except Exception: # noqa
app_logger.exception(f"Failed executing {cmd}")


def exec_cmd_return_value(cmd, cmd_print=True):
if cmd_print:
app_logger.info(cmd)
try:
p = subprocess.run(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
string = p.stdout.decode("utf8").strip()
return string
except Exception: # noqa
app_logger.exception(f"Failed executing {cmd}")
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@ Description=PizeroBikecomputer
#After=gpsd.service local-fs.target

[Service]
WorkingDirectory=/home/pi/pizero_bikecomputer
ExecStart=/home/pi/pizero_bikecomputer/exec-service.sh
WorkingDirectory=
ExecStart=

Restart=no
Type=simple

User=pi
Group=pi
User=
Group=

[Install]
WantedBy=multi-user.target
File renamed without changes.
File renamed without changes.

0 comments on commit d78b74a

Please sign in to comment.