EnergyLink: lots of cleanup

This commit is contained in:
Fabian Dill 2022-02-24 04:47:01 +01:00
parent 11a13967d5
commit 6bf2f5611a
5 changed files with 50 additions and 16 deletions

View File

@ -119,6 +119,7 @@ class CommonContext():
ui = None ui = None
keep_alive_task = None keep_alive_task = None
items_handling: typing.Optional[int] = None items_handling: typing.Optional[int] = None
current_energy_link_value = 0 # to display in UI, gets set by server
def __init__(self, server_address, password): def __init__(self, server_address, password):
# server state # server state
@ -548,7 +549,11 @@ async def process_server_cmd(ctx: CommonContext, args: dict):
# we can skip checking "DeathLink" in ctx.tags, as otherwise we wouldn't have been send this # we can skip checking "DeathLink" in ctx.tags, as otherwise we wouldn't have been send this
if "DeathLink" in tags and ctx.last_death_link != args["data"]["time"]: if "DeathLink" in tags and ctx.last_death_link != args["data"]["time"]:
ctx.on_deathlink(args["data"]) ctx.on_deathlink(args["data"])
elif cmd == "SetReply":
if args["key"] == "EnergyLink":
ctx.current_energy_link_value = args["value"]
if ctx.ui:
ctx.ui.set_new_energy_link_value()
else: else:
logger.debug(f"unknown command {cmd}") logger.debug(f"unknown command {cmd}")

View File

@ -107,15 +107,20 @@ class FactorioContext(CommonContext):
if "checked_locations" in args and args["checked_locations"]: if "checked_locations" in args and args["checked_locations"]:
self.rcon_client.send_commands({item_name: f'/ap-get-technology ap-{item_name}-\t-1' for self.rcon_client.send_commands({item_name: f'/ap-get-technology ap-{item_name}-\t-1' for
item_name in args["checked_locations"]}) item_name in args["checked_locations"]})
if cmd == "Connected" and self.energy_link_increment:
asyncio.create_task(self.send_msgs([{
"cmd": "SetNotify", "data": ["EnergyLink"]
}]))
elif cmd == "SetReply": elif cmd == "SetReply":
if args["key"] == "EnergyLink": if args["key"] == "EnergyLink":
logger.info(f"Got EnergyLink package: {args}")
if self.energy_link_increment and args.get("last_deplete", -1) == self.last_deplete: if self.energy_link_increment and args.get("last_deplete", -1) == self.last_deplete:
# it's our deplete request # it's our deplete request
gained = args["original_value"] - args["value"] gained = int(args["original_value"] - args["value"])
gained_text = Utils.format_SI_prefix(gained) + "J"
if gained: if gained:
logger.info(f"EnergyLink: Received {gained} Joules") logger.info(f"EnergyLink: Received {gained_text}. "
self.rcon_client.send_command(f"/ap-energylink {int(gained)}") f"{Utils.format_SI_prefix(args['value'])}J remaining.")
self.rcon_client.send_command(f"/ap-energylink {gained}")
async def game_watcher(ctx: FactorioContext): async def game_watcher(ctx: FactorioContext):
@ -267,7 +272,7 @@ async def factorio_server_watcher(ctx: FactorioContext):
factorio_process.wait(5) factorio_process.wait(5)
async def get_info(ctx, rcon_client): async def get_info(ctx: FactorioContext, rcon_client: factorio_rcon.RCONClient):
info = json.loads(rcon_client.send_command("/ap-rcon-info")) info = json.loads(rcon_client.send_command("/ap-rcon-info"))
ctx.auth = info["slot_name"] ctx.auth = info["slot_name"]
ctx.seed_name = info["seed_name"] ctx.seed_name = info["seed_name"]
@ -275,6 +280,8 @@ async def get_info(ctx, rcon_client):
death_link = bool(info.get("death_link", False)) death_link = bool(info.get("death_link", False))
ctx.energy_link_increment = info.get("energy_link", 0) ctx.energy_link_increment = info.get("energy_link", 0)
logger.debug(f"Energy Link Increment: {ctx.energy_link_increment}") logger.debug(f"Energy Link Increment: {ctx.energy_link_increment}")
if ctx.energy_link_increment and ctx.ui:
ctx.ui.enable_energy_link()
await ctx.update_death_link(death_link) await ctx.update_death_link(death_link)

View File

@ -438,11 +438,22 @@ def stream_input(stream, queue):
def tkinter_center_window(window: Tk): def tkinter_center_window(window: Tk):
window.update() window.update()
xPos = int(window.winfo_screenwidth()/2 - window.winfo_reqwidth()/2) xPos = int(window.winfo_screenwidth() / 2 - window.winfo_reqwidth() / 2)
yPos = int(window.winfo_screenheight()/2 - window.winfo_reqheight()/2) yPos = int(window.winfo_screenheight() / 2 - window.winfo_reqheight() / 2)
window.geometry("+{}+{}".format(xPos, yPos)) window.geometry("+{}+{}".format(xPos, yPos))
class VersionException(Exception): class VersionException(Exception):
pass pass
def format_SI_prefix(value, power=1000, power_labels=('', 'k', 'M', 'G', 'T', "P", "E", "Z", "Y")):
n = 0
while value > power:
value /= power
n += 1
if type(value) == int:
return f"{value} {power_labels[n]}"
else:
return f"{value:0.3f} {power_labels[n]}"

24
kvui.py
View File

@ -9,6 +9,7 @@ os.environ["KIVY_NO_ARGS"] = "1"
os.environ["KIVY_LOG_ENABLE"] = "0" os.environ["KIVY_LOG_ENABLE"] = "0"
from kivy.base import Config from kivy.base import Config
Config.set("input", "mouse", "mouse,disable_multitouch") Config.set("input", "mouse", "mouse,disable_multitouch")
Config.set('kivy', 'exit_on_escape', '0') Config.set('kivy', 'exit_on_escape', '0')
Config.set('graphics', 'multisamples', '0') # multisamples crash old intel drivers Config.set('graphics', 'multisamples', '0') # multisamples crash old intel drivers
@ -221,10 +222,11 @@ class GameManager(App):
text = original_say(text) text = original_say(text)
if text: if text:
for command in autofillable_commands: for command in autofillable_commands:
if text.startswith("!"+command): if text.startswith("!" + command):
self.last_autofillable_command = command self.last_autofillable_command = command
break break
return text return text
ctx.on_user_say = intercept_say ctx.on_user_say = intercept_say
super(GameManager, self).__init__() super(GameManager, self).__init__()
@ -234,18 +236,18 @@ class GameManager(App):
self.grid = MainLayout() self.grid = MainLayout()
self.grid.cols = 1 self.grid.cols = 1
connect_layout = BoxLayout(orientation="horizontal", size_hint_y=None, height=30) self.connect_layout = BoxLayout(orientation="horizontal", size_hint_y=None, height=30)
# top part # top part
server_label = ServerLabel() server_label = ServerLabel()
connect_layout.add_widget(server_label) self.connect_layout.add_widget(server_label)
self.server_connect_bar = TextInput(text="archipelago.gg", size_hint_y=None, height=30, multiline=False, self.server_connect_bar = TextInput(text="archipelago.gg", size_hint_y=None, height=30, multiline=False,
write_tab=False) write_tab=False)
self.server_connect_bar.bind(on_text_validate=self.connect_button_action) self.server_connect_bar.bind(on_text_validate=self.connect_button_action)
connect_layout.add_widget(self.server_connect_bar) self.connect_layout.add_widget(self.server_connect_bar)
self.server_connect_button = Button(text="Connect", size=(100, 30), size_hint_y=None, size_hint_x=None) self.server_connect_button = Button(text="Connect", size=(100, 30), size_hint_y=None, size_hint_x=None)
self.server_connect_button.bind(on_press=self.connect_button_action) self.server_connect_button.bind(on_press=self.connect_button_action)
connect_layout.add_widget(self.server_connect_button) self.connect_layout.add_widget(self.server_connect_button)
self.grid.add_widget(connect_layout) self.grid.add_widget(self.connect_layout)
self.progressbar = ProgressBar(size_hint_y=None, height=3) self.progressbar = ProgressBar(size_hint_y=None, height=3)
self.grid.add_widget(self.progressbar) self.grid.add_widget(self.progressbar)
@ -348,6 +350,16 @@ class GameManager(App):
self.log_panels["Archipelago"].on_message_markup(text) self.log_panels["Archipelago"].on_message_markup(text)
self.log_panels["All"].on_message_markup(text) self.log_panels["All"].on_message_markup(text)
def enable_energy_link(self):
if not hasattr(self, "energy_link_label"):
self.energy_link_label = Label(text="Energy Link: Standby",
size_hint_x=None, width=150)
self.connect_layout.add_widget(self.energy_link_label)
def set_new_energy_link_value(self):
if hasattr(self, "energy_link_label"):
self.energy_link_label.text = f"EL: {Utils.format_SI_prefix(self.ctx.current_energy_link_value)}J"
class FactorioManager(GameManager): class FactorioManager(GameManager):
logging_pairs = [ logging_pairs = [

View File

@ -50,7 +50,6 @@ function on_check_energy_link(event)
bridge.energy = bridge.energy + ENERGY_INCREMENT bridge.energy = bridge.energy + ENERGY_INCREMENT
end end
end end
game.print("Bridges: " .. bridgecount .. " With: " .. global.forcedata["player"].energy)
end end
end end
script.on_event(defines.events.on_tick, on_check_energy_link) script.on_event(defines.events.on_tick, on_check_energy_link)