Skip to content

Commit

Permalink
Merge pull request #3 from GeekyDeaks/feature-gui
Browse files Browse the repository at this point in the history
Feature gui
  • Loading branch information
GeekyDeaks authored Apr 11, 2023
2 parents 85426cf + 2a84e01 commit 657bd06
Show file tree
Hide file tree
Showing 15 changed files with 451 additions and 101 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ shm_info
/build
/dist
*.spec
*.cfg
52 changes: 52 additions & 0 deletions ams2-cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from logging import getLogger, basicConfig, DEBUG
basicConfig(
level=DEBUG,
format="%(asctime)s.%(msecs)03d [%(levelname)s] %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
l = getLogger(__name__)

import argparse
import os
import time
from stm.sampler import RawSampler
from stm.ams2 import AMS2Sampler, AMS2Logger

def main():

parser = argparse.ArgumentParser(description="Log AMS2 samples to MoTeC i2")
parser.add_argument("--freq", type=int, default=20, help="frequency (Hz) to collect samples")
parser.add_argument("--saveraw", help="save raw samples to an sqlite3 db for later analysis", action="store_true")
parser.add_argument("--loadraw", help="load raw samples from an sqlite3 db", default="")

args = parser.parse_args()

filetemplate = os.path.join("logs", "ams2", "{venue}_{vehicle}_{driver}_{session}_{datetime}")

if args.saveraw:
rawfile = os.path.join("logs", "raw", "ams2", f"{time.time():.0f}.db" )
else:
rawfile = None

if args.loadraw:
sampler = RawSampler(rawfile=args.loadraw)
else:
sampler = AMS2Sampler(freq=args.freq)

logger = AMS2Logger(
rawfile=rawfile,
sampler=sampler,
filetemplate=filetemplate
)

try:
logger.start()
while logger.is_alive():
logger.join(0.1)
except KeyboardInterrupt:
l.warning("stopping")
logger.stop()
logger.join()

if __name__ == '__main__':
main()
159 changes: 131 additions & 28 deletions ams2.py
Original file line number Diff line number Diff line change
@@ -1,45 +1,148 @@
import PySimpleGUI as sg
import json
import os
import time

from stm.version import __version__
from stm.ams2 import AMS2Logger, AMS2Sampler
from logging import getLogger, basicConfig, DEBUG

# try and load the sate
STATE_FILE = "ams2.cfg"

try:
with open(STATE_FILE) as f:
state = json.load(f)
except Exception as e:
state = {
"FREQ": "20",
}

sg.change_look_and_feel('Default1')

BUTTON_DISABLED = (sg.theme_background_color(), sg.theme_background_color())
BUTTON_ENABLED = (sg.theme_button_color_text(), sg.theme_background_color())

labels = [
[sg.Text("Sampling Frequency")],
[sg.Text("Log File")],
[sg.Text("Vehicle")],
[sg.Text("Venue")],
[sg.Text("Sequence")],
[sg.Text("Game State")],
[sg.Text("Race State")],
[sg.Text("Session")],
[sg.Text("Lap")],
]

values = [
[sg.Input(state["FREQ"], key="FREQ", size=(5,1), enable_events=True), sg.Text("Hz", justification="l")],
[sg.Text("Not Started",key="LOGFILE" )],
[sg.Text("N/A", key="VEHICLE")],
[sg.Text("N/A", key="VENUE")],
[sg.Text("N/A", key="SEQ")],
[sg.Text("N/A", key="GAMESTATE")],
[sg.Text("N/A", key="RACESTATE")],
[sg.Text("N/A", key="SESSION")],
[sg.Text("N/A", key="LAP")],
]

# Define the window's contents
layout = [
[sg.Column(labels, element_justification='r'), sg.Column(values)],
[
sg.Button('Start', key="START"),
sg.Button("Stop", key="STOP", disabled=True, button_color=BUTTON_DISABLED),
sg.Button('Quit', key="QUIT"),
sg.Checkbox("Rawfile", key="RAWFILE")
],
[sg.HorizontalSeparator()],
[sg.Output(size=(100, 12), echo_stdout_stderr=True)]
]

# Create the window
window = sg.Window(f"AMS2 logger v{__version__}", layout, finalize=True)
# start the logger after creating the output element
basicConfig(
level=DEBUG,
format="%(asctime)s.%(msecs)03d [%(levelname)s] %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
datefmt="%H:%M:%S"
)
l = getLogger(__name__)

import argparse
import os
import time
from stm.sampler import RawSampler
from stm.ams2 import AMS2Sampler, AMS2Logger
logger = None

def main():
# Display and interact with the Window using an Event Loop
while True:
event, values = window.read(timeout=500)
# See if user wants to quit or window was closed
if event in (sg.WINDOW_CLOSED, "QUIT"):
break

parser = argparse.ArgumentParser(description="Log AMS2 samples to MoTeC")
parser.add_argument("--freq", type=int, default=20, help="frequency (Hz) to collect samples")
parser.add_argument("--saveraw", help="save raw samples to an sqlite3 db for later analysis", action="store_true")
parser.add_argument("--loadraw", help="load raw samples from an sqlite3 db", default="")
if event == "FREQ" and len(values['FREQ']) and values['FREQ'][-1] not in ('1234567890'):
window["FREQ"].update(values['FREQ'][:-1])

args = parser.parse_args()
if event in state:
state[event] = values[event]

filetemplate = os.path.join("logs", "ams2", "{name}_{driver}_{venue}_{vehicle}_{datetime}_{session}")
if event == "START":
filetemplate = os.path.join("logs", "ams2", "{venue}_{vehicle}_{driver}_{session}_{datetime}")

if args.saveraw:
rawfile = os.path.join("logs", "raw", "ams2", f"{time.time():.0f}.db" )
else:
rawfile = None
if values["RAWFILE"]:
rawfile = os.path.join("logs", "raw", "ams2", f"{time.time():.0f}.db" )
else:
rawfile = None

logger = AMS2Logger(
rawfile=rawfile,
sampler=AMS2Sampler(freq=values["FREQ"]),
filetemplate=filetemplate
)
logger.start()

if event == "STOP" and logger:
logger.stop()
logger.join()
logger = None

if logger:
window["QUIT"].update(disabled=True, button_color=BUTTON_DISABLED)
window["START"].update(disabled=True, button_color=BUTTON_DISABLED)
window["STOP"].update(disabled=False, button_color=BUTTON_ENABLED)
window["LOGFILE"].update(logger.filename)
# update with values
if logger.last_packet:
p = logger.last_packet

if args.loadraw:
sampler = RawSampler(rawfile=args.loadraw)
if p.driver:
window["LAP"].update( f"{p.driver.mCurrentLap}/{p.mLapsInEvent}" )
window["SEQ"].update(p.mSequenceNumber)
window["VEHICLE"].update(logger.get_vehicle())
window["VENUE"].update(logger.get_venue())
window["GAMESTATE"].update(p.mGameState.name)
window["RACESTATE"].update(p.mRaceState.name)
window["SESSION"].update(p.mSessionState.name.title())
else:
sampler = AMS2Sampler(freq=args.freq)
window["QUIT"].update(disabled=False, button_color=BUTTON_ENABLED)
window["START"].update(disabled=False, button_color=BUTTON_ENABLED)
window["STOP"].update(disabled=True, button_color=BUTTON_DISABLED)
window["LOGFILE"].update("Not Started")
window["LAP"].update("N/A")
window["SEQ"].update("N/A")
window["VEHICLE"].update("N/A")
window["VENUE"].update("N/A")
window["GAMESTATE"].update("N/A")
window["RACESTATE"].update("N/A")
window["SESSION"].update("N/A")

logger = AMS2Logger(
rawfile=rawfile,
sampler=sampler,
filetemplate=filetemplate
)
# try and save the state
try:
with open(STATE_FILE, "w") as f:
json.dump(state, f)
except Exception as e:
print(e)
pass

logger.start()
# Finish up by removing from the screen
window.close()

if __name__ == '__main__':
main()
4 changes: 2 additions & 2 deletions buildwin.bat
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
pyinstaller --onefile ams2.py
pyinstaller --add-data stm\gt7\db\*.csv;stm\gt7\db --onefile gt7.py
pyinstaller --noconsole --onefile ams2.py
pyinstaller --noconsole --add-data stm\gt7\db\*.csv;stm\gt7\db --onefile gt7.py
60 changes: 60 additions & 0 deletions gt7-cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from logging import getLogger, basicConfig, DEBUG
basicConfig(
level=DEBUG,
format="%(asctime)s.%(msecs)03d [%(levelname)s] %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S"
)
l = getLogger(__name__)

import argparse
import os
import time
from stm.sampler import RawSampler
from stm.gt7 import GT7Logger, GT7Sampler

def main():

parser = argparse.ArgumentParser(description="Log GT7 samples to MoTeC i2")
parser.add_argument("addr", type=str, help="ip address of playstation or raw file")
parser.add_argument("--driver", type=str, default="", help="Driver name")
parser.add_argument("--session", type=str, default="", help="Session e.g. Practice, Qualify, Race")
parser.add_argument("--vehicle", type=str, default="", help="Override name of vehicle")
parser.add_argument("--venue", type=str, default="", help="Venue/Track name, MoTeC will not generate a track map without this")
parser.add_argument("--freq", type=int, default=60, help="frequency to collect samples, currently ignored")
parser.add_argument("--saveraw", help="save raw samples to an sqlite3 db for later analysis", action="store_true")
parser.add_argument("--loadraw", help="load raw samples from an sqlite3 db", action="store_true")
args = parser.parse_args()

filetemplate = os.path.join("logs", "gt7", "{venue}_{vehicle}_{driver}_{session}_{datetime}")

if args.saveraw:
rawfile = os.path.join("logs", "raw", "gt7", f"{time.time():.0f}.db" )
else:
rawfile = None

if args.loadraw:
sampler = RawSampler(rawfile=args.addr)
else:
sampler = GT7Sampler(addr=args.addr, freq=args.freq)

logger = GT7Logger(
rawfile=rawfile,
sampler=sampler,
filetemplate=filetemplate,
driver=args.driver,
session=args.session,
vehicle=args.vehicle,
venue=args.venue
)

try:
logger.start()
while logger.is_alive():
logger.join(0.1)
except KeyboardInterrupt:
l.warning("stopping")
logger.stop()
logger.join()

if __name__ == '__main__':
main()
Loading

0 comments on commit 657bd06

Please sign in to comment.