Jump to content

[1.12.x] kRPC: Control the game using C#, C++, Java, Lua, Python, Ruby, Haskell, C (Arduino)... (v0.5.4)


djungelorm

Recommended Posts

Hello,

I started to build a controller for KSP with my Arduino, but I am a beginner and I have some worries with English (I'm french, sorry for my language :) )

And so, I have a little trouble to understand the documentation of this wonderful plugin :P

 

 

I love just detect the quantity of liquid fuel in my current stage, and, as soon as the quantity of liquid fuel drops below as 10%, I am warned by alarm.

To summarize :

How to read the amount of fuel present in stage ?

How to read the current stage number ?

 

Thank you very much :) 

Link to comment
Share on other sites

Hi! Glad you like the mod :)

You can get the current stage using Control.current_stage and use the resources class to get the amount of LFO in the current stage. Here's an example in Python:

import krpc
conn = krpc.connect()
vessel = conn.space_center.active_vessel
stage = vessel.control.current_stage
resources = vessel.resources_in_decouple_stage(stage)
print 'LFO =', resources.amount('LiquidFuel')

 

Link to comment
Share on other sites

Hi !

Thank you very much ! Your example work fine ! I didn't use it properly ...

However, I had found alternative solution, but it's not optimized and wobbly ...

I have another question : Can you set, in properties of this mod, the possibility for automatically allow the connexion from Python to KSP without th authorisation of the user ?

Thank you :) 

(sorry for my imperfect english)

Edited by Gouttfi
add question
Link to comment
Share on other sites

First: Thanks for such an awesome addition to KSP :) Do you take donations?

2nd: I am learning python, and was wondering how I can get the below snip of code to print to the same line? I have been looking online and there were so many ways that did not make much sense to me.

Is this even possible?

The below is from the first tutorial.

#Print the altitude out live until speed reaches 0
while vessel.flight(vessel.orbit.body.reference_frame).vertical_speed < -0.1:
	print('Altitude = %.1f meters' % vessel.flight().surface_altitude)
time.sleep(1)
print('Landed!')

I apologise in advance for any late reply as it is late and I must be off to bed.

 

x0x0

 

Kerbal007

Link to comment
Share on other sites

Thanks for the offer! I don't take donations, but if you'd like to donate to the B612 foundation instead that'd be awesome :)http://b612foundation.org/donate

It is possible in Python, but it is indeed a bit of a mess... Python's print function automatically appends a line feed character to anything you pass it, which prevents you from printing over the existing line. Appending a comma to the end of the argument prevents it from doing this. The following example should do what you want. It repeatedly prints out the altitude, followed by a carriage return character (to move the cursor back to the start of the line). It also has to flush the output to standard output (Python buffers its output until the next line feed character, so as we aren't printing a line feed we need to force the output to flush to the terminal). When the loop finishes it prints a line feed (to go to a new line, and leave the last altitude printed) and then prints the done message.
 

import sys
while vessel.flight(vessel.orbit.body.reference_frame).vertical_speed < -0.1:
    print('Altitude = %.1f meters\r' % vessel.flight().surface_altitude),
    sys.stdout.flush()
time.sleep(1)
print('')
print('Landed!')

 

Link to comment
Share on other sites

Thanks so much, I will check them out, not seen that before.

The code worked a treat altho in test it spat out

Altitude = 0.6 meterssers

at the end which I am not sure why, /r perhaps?

I have also added the below for a nice little countdown which I came across

print 'Countdown to launch'
for i in xrange(10,0,-1):
    time.sleep(1)
    sys.stdout.write(str(i)+' ')
    sys.stdout.flush()

 

#inspired.

Link to comment
Share on other sites

Aha, that's because you're overwriting an existing line, and the new line being written is shorter. Maybe try printing a bunch of spaces just before the \r to overwrite the old line completely.

Btw a much cleaner (but more involved) way of doing this is to use the curses library.

Edited by djungelorm
Clarify
Link to comment
Share on other sites

kRPC 0.2.3 has been released! Here are the highlights:

  • Support for engines with multiple modes
  • Support for cargo bays, fairings and air intakes
  • Fixes for 1.0.5 landing gear and radiators
  • All the client libraries are now thread safe
  • Improved MSVC support in the C++ client
  • Java client now supports JDK 1.7 (as well as 1.8)

A full change log can be found here: https://github.com/krpc/krpc/releases/tag/v0.2.3

This release is for KSP 1.0.5. A version compatible with the KSP 1.1 pre-release can be downloaded from here: https://krpc.s3.amazonaws.com/deploy/feature/ksp-1.1-pre/302.1/krpc-0.2.3-18-g0eb3274.zip

 

Link to comment
Share on other sites

Hi!

First and foremost, a big thank you and well done on the mod! Your hard work is very much appreciated.

I am hoping for a little help with a project where i am planning to build a control panel. In my usual style i have gone totally overboard... a few buttons just wont cut it. The idea is is a complete panel that removes all keyboard input, everything will be switches and indicators around a 10" display to show flight data.

I have done proof of concept of the display (streams are awesome!) and of digital and analogue inputs from an arduino. The next step was to map out all the controls i want and find the corresponding interface in KRPC.... and that's where i got stuck on a few items:

1. Trim controls and fine control mode

2. Map view, map focus, cycle active ship, IVA view, camera modes

3. EVA controls in general (use part, board, headlamps etc) and KAS/KIS controls to grap/attach/equip.

4. Game controls like quicksave, or pause (for when my wife yells 'get off that damn game already!')

I am not too worried about the first one as i can offset/scale my analogues to do this, but i am a but stuck on ideas for the rest.

Is it possible to control these things via KRPC?

I noted the service API and the potential to extend, however my tech knowledge wasn't good enough to follow without more example (my coding days are long ago when classes weren't a thing yet) and the link in the docs more detailed examples throws a 404. So this looks like it might be my way forward but i cant tell for sure.

Thanks in advance for any help!

 

 

Link to comment
Share on other sites

That sounds like a cool project :) I think all of the features you require sound like reasonable things to either add to kRPC or are doable from client code. Here's a summary of the current state of things:

1) Toggling fine controls isn't currently possible, and I don't think it's really needed? You can just scale the control inputs from your client code. And are there trim settings for aero surfaces in KSP? I'm working on adding aero control surfaces (along with a major upgrade of the built-in autopilot so it's less rubbish) so this should be possible once that's completed.

2) Switching map view, map focus, IVA and camera modes also aren't currently possible. They sound like easy additions though. Changing the active ship can be done by setting conn.space_center.active_vessel = x where x is a vessel object (for example those obtained via conn.space_center.vessels).

3) I've only added functionality with vessels in mind, not EVA kerbals. So unless the headlamps etc. map to the same controls as a vessel these won't currently work. You can interact with the part modules of arbitrary mods via the Part and Module objects in kPRC, but this probably won't help with the KAS/KIS EVA options.

4) Quicksave and pause are also not supported. Quicksave should be an easy addition. Pausing would cause issues... as pausing will stop FixedUpdate from firing and cause the server to hang.

Which link is giving you a 404? I just updated the docs for the new 0.2.3 release so maybe it's been fixed?
 

Link to comment
Share on other sites

I second the need for map view, moving camera, bringing up the menu, etc. I think you know the project I'm working on and it would help a TON. Also quicksave and quickload.

One problem I notice, that I'm not sure if you're aware of, is to get target_pitch_and_heading to work, I have to stop and start the server between runs. Say I launch and revert, pretty much everything works except the rocket won't aim where I want it. Stopping and starting the server seems to fix this.

Again, thanks a ton for such an amazing mod!!! I hope 1.1 doesn't break it too much :)

Link to comment
Share on other sites

It actually works fine in 1.1 with minimal changes!! Just got a bunch of features to add for the new wheels.

And yeah I'm aware of that autopilot bug. I've held off on making changes to the autopilot code until the rewrite is done - which will do auto tuning of the PID parameters based on moi and torque. I'm close to having it work in python, then I just need to port it over to C#.

Link to comment
Share on other sites

34 minutes ago, Gouttfi said:

hi !

It's possible to update your documentation, because I am beginner in python and your documentation (for my opinion) lack examples.

Thank you :)

Sorry for my english

Hello @Gouttfi, on the very first page of this thread you will actually find some example scripts to:

 

Link to comment
Share on other sites

yes of course, but when I talk about examples, I think little examples, as one or two lines of code, not necessarily for every commands from your plugin, but some that could be hard to use ...

example, from python documentation -> Space Center API -> Control :

 

sas

The state of SAS.

      Attribute:Can be read or written

      Return type:bool

example code : vessel.control.sas = False

 

 

Edited by Gouttfi
sorry for my bad english :-p
Link to comment
Share on other sites

It's a bit difficult for me to be the judge of which bits of the API are hard to use - as the author it seems obvious to me! If there are particular things that are unclear then please mention them, and I will add a note with an example.

For example, I did this recently with vessel.flight explaining what the default reference frame is as that caused a lot of confusion.

Link to comment
Share on other sites

9 hours ago, djungelorm said:

... You can just scale the control inputs from your client code. And are there trim settings for aero surfaces in KSP?

Yep that's not to hard to do. Moving my 0 point will do trim and scaling the maximum will do fine controls. It wont be linear anyway as it will need a dead band.  However the game does have this built in, trims are MOD + WASDQE and to reset trim is MOD X.

9 hours ago, djungelorm said:

 Changing the active ship can be done by setting conn.space_center.active_vessel = x where x is a vessel object (for example those obtained via conn.space_center.vessels).

Ah yes.. there is a pro tip... read the documentation carefully! it does say this property is read and write :) However when in flight, does conn.space_center.vessels consider physics range? I was hoping to replicate the '[' and ']' key functions that only operate on nearby vessels. Or does it list all vessels, so matching the list in the tracking center? I will do some experiments on this one.

EVA controls are a different key binding so this wont work. Same for KAS. They must be actions defined in the EVA kerbal vessel modules though, so I will have a play and see if I can see any of them via the part and module options.

I see the issue now of the pause, its a game stop rather than a time rate of 0, so this one is out. If I can get quicksave at some point though it would do, as I can save when I get yelled at and reload when I get released :D

In the web documentation at http://krpc.github.io/krpc/extending.html under further examples there is a link to https://github.com/krpc/krpc/tree/latest-version/src/kRPCSpaceCenter/Services which gives the 404. Note I cant check the PDF as I am at work and they get narky, but I think its the same.

Link to comment
Share on other sites

space_center.vessels will give you all the vessels. There isn't a way to get a list of vessels in physics range, but a potential workaround would be to filter that list based on distance from the active vessel. For example, the following script will print out all the vessels within 22.5km of the active vessel (which I think is the default physics range):

import krpc
import math

def norm(v):
    return math.sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2])

conn = krpc.connect()
active_vessel = conn.space_center.active_vessel
vessels = conn.space_center.vessels
vessel_distances = [(v, norm(v.position(active_vessel.reference_frame))) for v in vessels]

for vessel,distance in vessel_distances:
    if distance < 22500: # 22.5km
        print vessel.name, '%.1f km' % (distance/1000)

I've had a look into adding camera controls, quick save and load. The API is pretty straightforward so will be very easy to add :) I've added issues on github to track these changes in case you're interested: https://github.com/krpc/krpc/issues/246 https://github.com/krpc/krpc/issues/246

And I've fixed that link on the docs site. It should have been: https://github.com/krpc/krpc/tree/latest-version/service/SpaceCenter/src/Services

Edited by djungelorm
typo
Link to comment
Share on other sites

Ok, take a breath, calm down... i think i have just stumbled onto the greatest thing ever.... well, in KSP anyway, which is everything important right? :D

space_center.draw_line()   and by placing a vessel at the threshold of the runway i get its coordinates for the start. Now if i can work out the position of the end of a vector that is 10km long at 3 deg slope heading west... i have LANDING GUIDANCE!!!

This could be a couple of lines either side of the runway, or even 4 lines forming a rectangular tube to fly down. And putting one at the other end is just a matter of coordinates.

Now if only i remembered enough maths to add my 10km vector in the celestial body reference frame to the start point! At 11pm that aint happening.. but tomorrow i will certainly give it a go! 

If i manage to get the vectors calculated out i will share them of course!

This is so going on my control panel. Runway select to 09, landing guidance to ON...   ooooooo, aaahhhhh

Link to comment
Share on other sites

CKAN states it works "only" up to 1.0.5 - so I can't install it with CKAN into 1.1

Some posting above said it works in 1.1 except for some wheel problems.

Should I start working on something or wait for the definitive 1.1 release of Mod 'n Game?

And since I have to sharpen my C++ skills - will support for it be dropped in favor of C# it will both languages stay available?

Edited by Darkstar One
Link to comment
Share on other sites

The "pre-release" of kRPC for 1.1 has to be manually installed, and is available from here: https://krpc.s3.amazonaws.com/deploy/feature/ksp-1.1-pre/302.1/krpc-0.2.3-18-g0eb3274.zip

I've not thoroughly tested it, so there may be bugs, and I still need to add wheel changes (that's why it's not on ckan yet).

And all the client languages will be supported for the foreseeable future. I certainly won't be "replacing" C++ with C#!!

Link to comment
Share on other sites

So i made some progress on landing guidance. if anyone else would like it here it is. It sets up lines either side of the runway at 4 (red), 5 (white) and 6 (yellow) deg slope for 20km from runway 09 threshold. 3.5 degrees, as per an airliner, did not seem kerbal enough so i went for a military 5. A shuttle 21 deg approach could be interesting too for an unpowered craft.

The only shame is that it is hard coded. I cant find a way to calculate them directly, which would be nice so you can tune slope / distance. I used a test rig comprising a Mk1 cockpit on the front of a T frame of girders with some more girders for legs so i know the rig will sit as flat and straight as possible. This was important as it lets me use the vessels reference frame as a runway reference frame. 

I could then define the start and end position for each line in the 'runway reference frame'. The starts are simply (+/-30,0,0) and the ends are (+/-30, -length, -tan(slope)*length). Each of these points (2 start, 6 end) are transformed into the kerbin reference frame using space_center.transform_position() and pasted into the code.

To get the other end you just need to rinse/repeat with a vessel at the other threshold, but make sure it sits dead flat (pitch and roll).

import krpc

conn = krpc.connect(name='blah')
vessel = conn.space_center.active_vessel

conn.space_center.clear_drawing()

v1_start = (158095.3939033646, -478.99761794020907, -578869.7132278137)
v2_start = (158094.96184479096, -538.996063121335, -578869.7134211722)
v1l_end = (139184.84695719907, -342.79930986318584, -585527.6834731719)
v1m_end = (139278.06869656406, -343.45641409607947, -585866.255670956)
v1h_end = (139371.60232570115, -344.14248819162003, -586205.9386240399)
v2l_end = (139184.35853335817, -402.79511157271287, -585527.523517651)
v2m_end = (139277.66372229127, -403.45750069248425, -585866.328863767)
v2h_end = (139371.1656752824, -404.1432818151327, -586205.927123417)


l_col = (255,0,0)
m_col = (255,255,255)
h_col = (255,255,0)

conn.space_center.draw_line(v1_start, v1l_end, vessel.orbit.body.reference_frame, l_col)
conn.space_center.draw_line(v1_start, v1m_end, vessel.orbit.body.reference_frame, m_col)
conn.space_center.draw_line(v1_start, v1h_end, vessel.orbit.body.reference_frame, h_col)
conn.space_center.draw_line(v2_start, v2l_end, vessel.orbit.body.reference_frame, l_col)
conn.space_center.draw_line(v2_start, v2m_end, vessel.orbit.body.reference_frame, m_col)
conn.space_center.draw_line(v2_start, v2h_end, vessel.orbit.body.reference_frame, h_col)

 

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...