Jump to content

[1.8.x to 1.12.x] kRPC: Control the game using C#, C++, Java, Lua, Python, Ruby, Haskell, C (Arduino)... (v0.5.2, 18th March 2023)


djungelorm

Recommended Posts

I am looking for a way to generate a list of parts that have no docking ports above them in the tree hierarchy. My guess is that it will be some form of recursion function, but my python skills are rudimentary. The motivation is to activate solar panels and cargo bays on my SSTO only, not the payload (that is conveniently separated from the vessel by docking ports). Can anyone help me out on this?

Link to comment
Share on other sites

  • 4 weeks later...

I'm having trouble with the luarocks stuff -
 

Quote

C:\WINDOWS\system32>luarocks install protobuf
Installing http://luarocks.org/repositories/rocks/protobuf-1.1.1-0.rockspec...
Cloning into 'protobuf-lua'...
remote: Enumerating objects: 190, done.
remote: Total 190 (delta 0), reused 0 (delta 0), pack-reused 190
Receiving objects: 100% (190/190), 63.65 KiB | 372.00 KiB/s, done.
Resolving deltas: 100% (101/101), done.
cl /MD /O2 -c -Foprotobuf/pb.obj -IC:/Program Files (x86)/Lua/5.1/include protobuf/pb.c
'cl' is not recognized as an internal or external command,
operable program or batch file.

Error: Build error: Failed installing protobuf/wire_format.lua in C:\Program Files (x86)\Lua\5.1\rocks/protobuf/1.1.1-0/lua/protobuf

 

Link to comment
Share on other sites

Hi good afternoon.
I play with kRPC and it works wonderfully with
Python 2.7.15 and Python 3.7. und Kerbal Space Program 1.6.1

All four test programs do not work from kRPC.MechJeb

--------------------------
- pip install krpc is ok.
---------------------------

Now I wanted to test the kerbal kRPC.MechJeb:
-Mechjeb2 installed.
-Copy KRPC.MechJeb.dll to Kerbal Space
   Program / GameData / kRPC directory.

I tested two addresses in kRPC.

this address :
-----------------------------
conn = krpc.connect(name='Launch into orbit',
    address='127.0.0.1',
    rpc_port=1000, stream_port=1001)
-----------------------------
not function !        

this addres :
-----------------------------
conn = krpc.connect(name='Launch into orbit',
    address='127.0.0.1',
    rpc_port=50000, stream_port=50001)
-----------------------------
not function !    

program LaunchIntoOrbit.py

import krpc
	conn = krpc.connect(name='Launch into orbit',
    address='127.0.0.1',
    rpc_port=1000, stream_port=1001)
	sc = conn.space_center
mj = conn.mech_jeb
ascent = mj.ascent_autopilot
	#All of these options will be filled directly into Ascent Guidance window and can be modified manually during flight.
ascent.desired_orbit_altitude = 100000
ascent.desired_inclination = 6
	ascent.force_roll = True
ascent.vertical_roll = 90
ascent.turn_roll = 90
	ascent.autostage = True
ascent.enabled = True
sc.active_vessel.control.activate_next_stage() #launch the vessel
	with conn.stream(getattr, ascent, "enabled") as enabled:
    enabled.rate = 1 #we don't need a high throughput rate, 1 second is more than enough
    with enabled.condition:
        while enabled():
            enabled.wait()
print("Launch complete!")
conn.close()


errormeldung with LaunchIntoOrbit.py :
-------------------------------------------
f:\python27>python.exe f:\python27\pebi-py\LaunchIntoOrbit.py
Traceback (most recent call last):
  File "f:\python27\pebi-py\LaunchIntoOrbit.py", line 9, in <module>
    ascent = mj.ascent_autopilot
  File "<string>", line 1, in <lambda>
  File "f:\python27\lib\site-packages\krpc\client.py", line 163, in _invoke
    raise self._build_error(response.results[0].error)
krpc.types.MJServiceException: Exception has been thrown by the target of an invocation.: Non-static field requires a target
Server stack trace:
  at KRPC.MechJeb.ExtensionMethods.TypeExtensions.CreateInstance[AscentAutopilot] (System.Type type, System.Object[] args) [0x00000] in <filename unknown>:0
  at KRPC.MechJeb.MechJeb.GetComputerModule[AscentAutopilot] (System.Object[] modules, Int32 id, System.Object[] args) [0x00000] in <filename unknown>:0
  at KRPC.MechJeb.MechJeb.GetComputerModule[AscentAutopilot] (System.Object[] modules, Int32 id) [0x00000] in <filename unknown>:0
  at KRPC.MechJeb.MechJeb.get_AscentAutopilot () [0x00000] in <filename unknown>:0
  at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (object,object[],System.Exception&)
  at System.Reflection.MonoMethod.Invoke (System.Object obj, BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00000] in <filename unknown>:0
----------------------------------------


thanks.
greeting

Edited by funkheld
Link to comment
Share on other sites

Hi good afternoon.
with kos i have this laserdist on the run with python.
how can you please implement the program for krpc?

Thank you.
Greeting

 

	set laser TO SHIP:MODULESNAMED("LaserDistModule")[0].
	until false 
{
  print "Distanz = " + round(laser:Getfield("Distance"),1) + " Meter   " at(0,5).
  wait 0.2.
}

Edited by funkheld
Link to comment
Share on other sites

  • 2 weeks later...
  • 1 month later...
On 2/13/2019 at 6:51 PM, funkheld said:

Hi good afternoon.
with kos i have this laserdist on the run with python.
how can you please implement the program for krpc?

Thank you.
Greeting

 


	set laser TO SHIP:MODULESNAMED("LaserDistModule")[0].
	until false 
{
  print "Distanz = " + round(laser:Getfield("Distance"),1) + " Meter   " at(0,5).
  wait 0.2.
}

Hi @funkheld, I'm not sure what you want to do, but if you want to calculate the distance between the active vessel and the target you can do it like it is described here:

 

Link to comment
Share on other sites

Hi @djungelorm, first of all I want to say thank you for this wonderful mod! I love it to make python scripts for KSP! Right at the moment I am developing a mission-control-screen-like-thing (a little bit like telemachus) with a moving map, ground-track, graphs with apo- and periapsis and a lot of telemetry-data. Therefore I'd like to ask if there is a way to stream not just single variables but ab bunch of variables at one time or even a whole vessel-object. Right now I stream every single variable in it's own thread (without threads my framerate drops significantly). But with threads the data is out of sync.

Link to comment
Share on other sites

I've been searching around and looking at the krpc source and I can't work out how to get the result of an expression:

dynamic_pressure = conn.get_call(getattr, vessel.flight(), 'dynamic_pressure')
velocity = conn.get_call(getattr, vessel.flight(), 'true_air_speed')
heatflux = conn.krpc.Expression.multiply(
    conn.krpc.Expression.call(dynamic_pressure),
    conn.krpc.Expression.call(velocity)
)

If someone can tell me how to get the result of the heatflux expression that'd be great. Thanks.

 

Link to comment
Share on other sites

  • 2 weeks later...

A and hardly surprising small observation: While trying to make additions to my client, I crashed it quite a lot. After a while, KSP (1.6.1) started stuttering. I installed MemGraph, and allocated a bunch of ram, only for the stutter to return after several more crashes. Turning off kRPC and turning it on again in game freed a lot of ram and stopped the stuttering, so it might be that the mod does not handle crashed connections all that well. Is there a time out on connections?

Anyway, the workaround is really simple, so it is probably not worth investing time into. This is more of a heads up for other people having the same problem.

Link to comment
Share on other sites

  • 2 weeks later...

Greetings, if someone would be so nice and write up a tutorial for (any version of) the C++ API on Windows I would apparaciate it. I found 2 tutorials by the author on GitHub, and while it nice we have those but neither worked for me. I also see a couple of request for this on the subreddit as well so I'm probably not the only noob struggling with this. Thanks!

Link to comment
Share on other sites

  • 5 weeks later...

Hey everyone, I was fiddling around with the new robotic parts for Breaking Ground and I came up with a snippet that allows me to control the parts.   

part_name = "piston.02"
module_name = "ModuleRoboticServoPiston"
field_name = "Target Extension"

for part in vessel.parts.all:
  if part.name == part_name:
    for module in part.modules:
      if module.name == module_name:
        module.set_field_float(field_name, 0.0)

It's not the easiest way, eventually I think it would be nice for KRPC to have a more direct interface, but for now this work around should work. Super excited to see what people come up with using the new parts!

Link to comment
Share on other sites

  • 2 weeks later...
On 5/30/2019 at 9:35 PM, namesnonames said:

Hey everyone, I was fiddling around with the new robotic parts for Breaking Ground and I came up with a snippet that allows me to control the parts.   


part_name = "piston.02"
module_name = "ModuleRoboticServoPiston"
field_name = "Target Extension"

for part in vessel.parts.all:
  if part.name == part_name:
    for module in part.modules:
      if module.name == module_name:
        module.set_field_float(field_name, 0.0)

It's not the easiest way, eventually I think it would be nice for KRPC to have a more direct interface, but for now this work around should work. Super excited to see what people come up with using the new parts!

Have you gotten this to work without bugging out, even if the part action window is closed?  I'm the current developer of kOS, which uses the same model as kRPC does for setting the Part Action Window float fields, and I'm trying to implement support for the new DLC robotics sliders and I keep running into a brick wall where the DLC PartModules only seem to work right when the Part Action Window is visible on screen.

I came here to ask if kRPC users are having the same issue as kOS users are having.  The two mods use almost identical techniques for scripted manipulation of PartModules, so there's a chance kRPC is having the exact same problem we are having and maybe we can compare notes and find out just what's going on with these parts.

The problems I am experiencing are:

1 - If your script keeps setting the "target extension" field in a loop to some middling but varying value (set it to, say, 0.5, half a second later, set it to a slightly higher value of 0.55, half a second later set it to back to 0.5, etc - keep "wiggling" the position by small amounts like this in a loop), then it starts bugging out after a few seconds, slamming the piston back to position 0.0 every so often when your script never commanded it to.  If you open the Part Action Window and keep it showing on the screen, the slamming back to 0.0 immediately stops happening and the piston starts obeying your script's commands again, even though you never changed anything in your script and in fact it was still running in the same run (you didn't kill and restart your program - ALL you did was open the PAW while it was running).

2 - The value of the "Current Extension" field tends to freeze in place a few seconds after the PAW is closed, making it hard for a script to query the current extension value and use that as a feedback mechanism.

3 - The value of the "Current Extension" field tends to never get updated in the first place if you have not yet opened the PAW for the part since the scene first loaded.

4 -The UI_FLoatRange.minValue, UI_FloatRange.maxValue, and UI_FloatRange.stepIncrement are bogus values and the DLC's sliders completely ignore them, as far as I can tell (with PAW either open or closed).  kOS tries to enforce these values (not letting a script set a value to something the player wouldn't be able to set it to, so you can't cheat by, say, setting a Reaction Wheel's "Wheel Authority" to like 5000% which has exactly the effect you'd think) But because the range values these DLC's PartModules are reporting are not truthful, this is making kOS deny the script's attempt to set the value to a legal value.

My conclusion is that these parts have some of their work done inside their GUI code in such a fashion that it's bypassing some of its work if the GUI panel is not open.

Problem #4 I have found a programmatic solution for, but problems 1 through 3 have me totally frustrated.  If kRPC has the same issues we can try to help each other on researching the problem.  If kRPC does NOT have the same issues, well at least I can compare code and see what we're doing differently.

Edited by Steven Mading
Link to comment
Share on other sites

On further investigation, I've found the steps that trigger this one, and I would suspect kRPC users will have the same problem so I'll point out the cause and the workaround I had to use:

7 hours ago, Steven Mading said:

1 - If your script keeps setting the "target extension" field in a loop to some middling but varying value (set it to, say, 0.5, half a second later, set it to a slightly higher value of 0.55, half a second later set it to back to 0.5, etc - keep "wiggling" the position by small amounts like this in a loop), then it starts bugging out after a few seconds, slamming the piston back to position 0.0 every so often when your script never commanded it to.  If you open the Part Action Window and keep it showing on the screen, the slamming back to 0.0 immediately stops happening and the piston starts obeying your script's commands again, even though you never changed anything in your script and in fact it was still running in the same run (you didn't kill and restart your program - ALL you did was open the PAW while it was running).

It turns out that merely setting the "target extension" over and over is NOT sufficient to cause the bug.  That actually works fine.  I was doing more than just that step.  I was ALSO setting the "Motor" boolean KSPField to True every update tick along with it, using code similar to this pseudocode:

//
// Psuedocode - not a real language
//
while true:
{
   Set KSPField called "target extension" to a new value.
   Set KSPField called "Motor" to true.  (This is the "Motor" button on the PAW that says "enabled" when true.)
   wait half a second
}

It appears that whenever you set KSPField "Motor" to true, Even if it was already true anyway before you did so, And you also set the "target extension" value in the SAME FixedUpdate, then the ModuleRoboticServoPiston resets itself to the zero position for one physics frame before trying to move back to the correct value.  But this does NOT happen if the PAW is open when you do so.

I don't quite get why this happens but it does - the ModuleRoboticServoPiston (and I presume the other RoboticServo modules but I was only testing with this one so far) seems to notice when the C# code has called BaseField.setValue() on the "Motor" field (perhaps they are using a callback hook on it), and whenever you do so, even if it's to set it to the same value it already had, it temporarily resets something in the module for a single frame that makes the piston jerk back to zero in an instant.  So for people trying to play with the robotic parts, be aware of this.  Set "Motor" to true only once, then avoid calling it again unless you really do want to change it back to false.

Edited by Steven Mading
Link to comment
Share on other sites

1 hour ago, Steven Mading said:

On further investigation, I've found the steps that trigger this one, and I would suspect kRPC users will have the same problem so I'll point out the cause and the workaround I had to use:

It turns out that merely setting the "target extension" over and over is NOT sufficient to cause the bug.  That actually works fine.  I was doing more than just that step.  I was ALSO setting the "Motor" boolean KSPField to True every update tick along with it, using code similar to this pseudocode:

Thank you, @Steven Mading, not just for figuring this all out but also for sharing that with us!

Link to comment
Share on other sites

@Steven Mading Sorry for the late response, I have not had any of those issues through kRPC. While the sample code I posted was about pistons I've actually been messing with rotors more. They've been behaving fine though. Hope you get it figured out though, the more people that have access to coding the robotic parts the cooler this community gets. :cool: As a side note I've been doing some cool stuff with it since I posted.

 

Link to comment
Share on other sites

  • 2 weeks later...

Yeah I am getting the PAW needing to be opened problem. All I have is a rotor on a pod and if I set its "RPM Limit" field to a specific value (say 50) then try and read the "Current RPM" field, it only shows/updates if the PAW is open. I came across this while starting to make an autopilot for my helicopter

 

If anyone cares to try:

Craft file

Python code:

Spoiler



import krpc
import time
import os

conn = krpc.connect(name='Derp')
vessel = conn.space_center.active_vessel
sc = conn.space_center
srf_frame = vessel.orbit.body.reference_frame

for part in vessel.parts.all:
    if part.tag == "rot1":
        for module in part.modules:
            if module.name == "ModuleRoboticServoRotor":
                module.set_field_int("Torque Limit(%)", 100)
                module.set_field_int("RPM Limit", 50)

while True:
    for part in vessel.parts.all:
        if part.tag == "rot1":
            for module in part.modules:
                if module.name == "ModuleRoboticServoRotor":
                    current_RPM = module.get_field("Current RPM")
    os.system('cls')
    print("Engine 1 RPM: " + current_RPM)
    time.sleep(0.5)


 

 

Link to comment
Share on other sites

  • 1 month later...
  • 5 weeks later...
On 8/12/2019 at 1:33 PM, GreenDude said:

Hi guys.  Do any of you know how to programmatically access the stage locking through krpc?  I'm trying to implement a master arm switch.

Stage locking is usually mapped to Alt-L and prevents accidental pressing of the space bar.

Not currently possible I'm afraid. I've added an issue to the github to get this added: https://github.com/krpc/krpc/issues/541

Link to comment
Share on other sites

  • 7 months later...
  • 3 weeks later...
  • 1 month later...

Hey,

I started today to play with Kerbal again. Play "with Kerbal" and not "play Kerbal" since I am trying to insall all my loved mods from former times...

kRPC is in my version of CKAN only available if I include the mods for the 1.5 KSP Version. Maybe this is the wrong Forum to metnion it, only I saw on git that there is a build for 1.9.

Cheers 

Isaak

Link to comment
Share on other sites

  • 1 month later...
On 7/22/2020 at 11:08 AM, blueisaak said:

Hey,

I started today to play with Kerbal again. Play "with Kerbal" and not "play Kerbal" since I am trying to insall all my loved mods from former times...

kRPC is in my version of CKAN only available if I include the mods for the 1.5 KSP Version. Maybe this is the wrong Forum to metnion it, only I saw on git that there is a build for 1.9.

Cheers 

Isaak

I'm curious if you found any resolution to this.  I, too, only see CKAN presenting an apparent old version and am not sure if this is because CKAN isn't up to speed or if CKAN hasn't deemed the later versions compatible and the git version is 'beta'.  The forum seems fairly quiet

Link to comment
Share on other sites

  • 3 weeks later...
On 8/29/2020 at 8:00 AM, darthgently said:

I'm curious if you found any resolution to this.  I, too, only see CKAN presenting an apparent old version and am not sure if this is because CKAN isn't up to speed or if CKAN hasn't deemed the later versions compatible and the git version is 'beta'.  The forum seems fairly quiet

I installed the 0.4.8 version of the mod using CKAN after temporarily enabling 1.5 compatibility. It seems to work in KSP 1.10.1. Ihave not tested every API, but so far I am able to get orbital telemetry without an issue

Link to comment
Share on other sites

This thread is quite old. Please consider starting a new thread rather than reviving this one.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...