Skip to content

Commit

Permalink
Merge pull request #111 from mi-ka-n/main
Browse files Browse the repository at this point in the history
Improve aircraft matching
  • Loading branch information
maartentamboer authored May 28, 2022
2 parents 35f4c39 + fc0c7ab commit e9d537d
Show file tree
Hide file tree
Showing 4 changed files with 108 additions and 8 deletions.
53 changes: 53 additions & 0 deletions aircraftstaterequest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
from SimConnect import *
from SimConnect.Enum import *
from SimConnect.Constants import *
import time
from ctypes import *
from ctypes.wintypes import *
from MSFSPythonSimConnectMobiFlightExtension.src.simconnect_mobiflight import SimConnectMobiFlight

class CustomSimconnect(SimConnectMobiFlight):
def __init__(self):
super().__init__()

# Workaround for Simconnect 0.4.24
self.dll.RequestSystemState.argtypes = [
HANDLE,
SIMCONNECT_DATA_REQUEST_ID,
c_char_p
]

def handle_state_event(self, ObjData):
dwRequestID = ObjData.dwRequestID
if dwRequestID in self.Requests:
_request = self.Requests[dwRequestID]
_request.outData = cast(ObjData.szString, c_char_p).value
else:
LOGGER.warn("Event ID: %d Not Handled." % (dwRequestID))

class SystemStateRequest(object):
def __init__(self, sm, attempts=10):
self._sm = sm
self._attempts = attempts
self._request_id = 0

# Make it compatible with original Simconnect dispatcher
self.outData = None
self.LastID = 0

def _request_system_state(self, szState):
p_szState = c_char_p(szState.encode())
self._request_id = self._sm.new_request_id().value
self._sm.Requests[self._request_id] = self
self._sm.dll.RequestSystemState(self._sm.hSimConnect, self._request_id, p_szState)
last_id_tmp = DWORD(0)
self._sm.dll.GetLastSentPacketID(self._sm.hSimConnect, last_id_tmp)
self.LastID = last_id_tmp.value

def get_system_state(self, szState):
current_attempt = 0
self._request_system_state(szState)
while current_attempt < self._attempts and self.outData is None:
time.sleep(0.1)
self._attempts += 1
return self.outData
19 changes: 17 additions & 2 deletions configfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,14 @@ def configure(self):
for elem in base_data['aircraft']:
aircraft_contains = elem['aircraft_contains']
file = elem['file']
if aircraft_contains in str(self._aircraft):
config_file = file
if isinstance(aircraft_contains, list):
for contain in aircraft_contains:
if contain.lower() in self._aircraft:
config_file = file
break
else:
if aircraft_contains.lower() in self._aircraft:
config_file = file
self._configure_additional_simvars(base_data)
if 'automatic_layer_revert' in base_data:
GlobalStorage().active_layer_changer.enable_layer_revert_timer(base_data['automatic_layer_revert'])
Expand Down Expand Up @@ -191,3 +197,12 @@ def _configure_additional_simvars(self, data):
helper.list[elem['name']] = simvar_elem
if helper not in self._aq.list:
self._aq.list.append(helper)

@staticmethod
def get_if_use_base_matching():
with open('Configurations/config.json') as base_json_file:
base_data = json.load(base_json_file)
if 'use_aircraft_base_matching' in base_data:
return base_data['use_aircraft_base_matching']
else:
return False
18 changes: 17 additions & 1 deletion globalstorage.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from trigger import Trigger
from fader import Fader
from activelayerchanger import ActiveLayerChanger

from aircraftstaterequest import SystemStateRequest

class GlobalStorage(metaclass=Singleton):
def __init__(self):
Expand All @@ -22,6 +22,8 @@ def __init__(self):
self._vr = None
self._global_variables = {}
self._active_layer_changer = None # type: ActiveLayerChanger
self._sq = None
self._base_matching = None

def clear(self):
self._buttons = []
Expand Down Expand Up @@ -64,6 +66,12 @@ def get_global_variable(self, key: str):
def set_active_layer_changer(self, ac: ActiveLayerChanger):
self._active_layer_changer = ac

def set_system_request(self, sq: SystemStateRequest):
self._sq = sq

def set_base_matching(self, base_matching: bool):
self._base_matching = base_matching

@property
def encoders(self) -> List[RotaryEncoder]:
return self._encoders
Expand Down Expand Up @@ -99,3 +107,11 @@ def mobiflight_variable_requests(self) -> MobiFlightVariableRequests:
@property
def active_layer_changer(self) -> ActiveLayerChanger:
return self._active_layer_changer

@property
def system_requests(self) -> SystemStateRequest:
return self._sq

@property
def base_matching(self) -> bool:
return self._base_matching
26 changes: 21 additions & 5 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from mocksimconnect import MockAircraftEvents, MockAircraftRequests
from activelayerchanger import ActiveLayerChanger
from midiconnection import MidiConnection
from aircraftstaterequest import CustomSimconnect, SystemStateRequest


def connect_to_simulator(offline: bool):
Expand All @@ -19,7 +20,7 @@ def connect_to_simulator(offline: bool):
waiting_time = 10
while not is_connected and not offline:
try:
sm = SimConnectMobiFlight()
sm = CustomSimconnect()
is_connected = True
except Exception:
print(f"Connection to simulator not possible. Retry in {waiting_time}s.")
Expand All @@ -28,15 +29,17 @@ def connect_to_simulator(offline: bool):


def initialize(global_storage: GlobalStorage,
sm: SimConnectMobiFlight,
sm: CustomSimconnect,
midi_connection: MidiConnection):
if sm:
sm = SimConnectMobiFlight()
sm = CustomSimconnect()
vr = MobiFlightVariableRequests(sm)
vr.clear_sim_variables()
global_storage.set_aircraft_events(AircraftEvents(sm))
global_storage.set_aircraft_requests(AircraftRequests(sm, _time=200))
global_storage.set_aircraft_requests(AircraftRequests(sm, _time=200, _attemps=20))
global_storage.set_mobiflight_variable_requests(vr) # Add MobiFlight
sq = SystemStateRequest(sm)
global_storage.set_system_request(sq)
else:
global_storage.set_aircraft_events(MockAircraftRequests())
global_storage.set_aircraft_requests(MockAircraftEvents())
Expand All @@ -57,16 +60,29 @@ def initialize(global_storage: GlobalStorage,
global_storage.add_fader(fader)

global_storage.set_active_layer_changer(ActiveLayerChanger(midi_connection.outport))
global_storage.set_base_matching(ConfigFile.get_if_use_base_matching())


def run_aircraft_configuration(global_storage: GlobalStorage):
aq = global_storage.aircraft_requests
vr = global_storage.mobiflight_variable_requests
sq = global_storage.system_requests
current_aircraft = "None"
base_matching = global_storage.base_matching
# Main program loop which checks for aircraft change
# and reads the simvars for loaded configuration
while True:
aircraft = aq.get('TITLE')
if base_matching:
aircraft_loaded = sq.get_system_state('AircraftLoaded')
if aircraft_loaded is not None:
aircraft_loaded = aircraft_loaded.decode().lower()
aircraft_cfg_loc = aircraft_loaded.find('aircraft.cfg')
aircraft = aircraft_loaded[aircraft_loaded.rfind('\\', 0, aircraft_cfg_loc - 1) + 1:aircraft_cfg_loc - 1]
else:
aircraft_title = aq.get('TITLE')
if aircraft_title is not None:
aircraft = aircraft_title.decode().lower()

if aircraft and aircraft != current_aircraft:
print("Aircraft changed from", current_aircraft, "to", aircraft)
current_aircraft = aircraft
Expand Down

0 comments on commit e9d537d

Please sign in to comment.