Skip to content

Instantly share code, notes, and snippets.

@TeWu
Last active July 1, 2019 14:02
Show Gist options
  • Save TeWu/43dd0a2509ece96b02b78e7be60f9b9d to your computer and use it in GitHub Desktop.
Save TeWu/43dd0a2509ece96b02b78e7be60f9b9d to your computer and use it in GitHub Desktop.
krpc-rb Events API
##
## Some non-binding thoughts on krpc-rb Events API.
## (This API Concept is probably too high-level.)
##
KRPC.connect do |client|
v = client.space_center.active_vessel
# Fires once
v.orbit.once :apoapsis_altitude, :change do |apo|
puts "new apoapsis: #{apo}"
end
# Fires multiple times
v.orbit.when :apoapsis_altitude, :change do |apo|
puts "new apoapsis: #{apo}"
end
# Condition
v.orbit.when :apoapsis_altitude, below: 20.km do |apo|
puts "apoapsis below 20, exactly #{apo}"
end
# Once + Argumet to RPC method + Condition
v.resources.once :amount, 'SolidFuel', equals: 0 do
# Separate those SRBs!
end
# Condition using proc/lambda
v.orbit.when :apoapsis_altitude, ->{|apo| apo < 20.km} do |apo|
puts "apoapsis below 20, exactly #{apo}"
end
# Condition using proc/lambda (version 2)
v.orbit.when ->{|o| o.apoapsis_altitude < 20.km} do |orbit|
puts "apoapsis below 20, exactly #{orbit.apoapsis_altitude}"
end
# Complex condition using expressions
ve = v.to_expr
v.orbit.once :apoapsis_altitude, above: ve.orbit.body.atmosphere_depth.plus(2.km) do |apo| ## OR
v.orbit.once :apoapsis_altitude, above: ->(e){ e.body.atmosphere_depth.plus(2.km) } do |apo| ## OR
v.orbit.once :apoapsis_altitude, above: [:body, :atmosphere_depth] do |apo|
puts "above atmosphere"
end
oe = v.orbit.to_expr # The same as: KRPC::Expression.new(v.orbit)
KRPC.once oe.apoapsis_altitude.gt(oe.body.atmosphere_depth) do |event|
puts "above atmosphere"
end
# Debounce
v.orbit.while :apoapsis_altitude, below: 80.km, debounce: 50 do |_|
# nothing
end
# Remove event
event = v.orbit.when :apoapsis_altitude, :change do |apo, event|
puts "new apoapsis: #{apo}"
event.cancel if apo > 100.km
end
sleep 1
event.cancel # aliased as 'remove' and 'close' ???
event.removed?
# block - waiting for condition
v.orbit.await :apoapsis_altitude, above: 80.km
# Blocks until client#close is called, or all events are removed
client.await_events
end
## Some links for fun:
## https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future
## https://docs.python.org/2/library/threading.html#event-objects
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment