The online racing simulator
Searching in All forums
(882 results)
Bass-Driver
S3 licensed
i'm so ****** stupid. def looking at the wrong stuff :SSchwitzFace -> palm


Thanks, it is working

Now i can get info of 1 single mod and i can the entire list of mods under 1 single command.
now its time to build a script around that.

Still need to add more info to the code to make the script properly working.


Thank you everyone.
Last edited by Bass-Driver, .
Bass-Driver
S3 licensed
ok now spending hours with the following issue.
trying to retrieve the info of 1 single car.

But after Deserializing the response from the API i get NULL.
I know it has something todo with setting up the classes, but i cannot figure out what i'm doing wrong here.

Websites i used to setup the classes.
https://json2csharp.com/

Here is some info:
Data i receive:


<?php 
{"data":{"id":"1AF20E","name":"TOMMY28","descriptionShort":"Tommy 28 - A vintage racing car from 1920'","description":"feel the vintage racing with big moustache and reckless drivers\r\ndo not search extrem grip, do not search evil power, but be extremely sharp in your track feeling with this 1928 Tommy racing car.\r\n\r\n2 configs :\r\n- Sport : stricly minimum to race\r\n- Sport Lux : tiny windscreen and lights (very usefull when LFS release the night races)\r\n\r\nMartin18 has work on the 8 inline engine !\r\nFlame CZE give me authorisation for his Hadraplan's steering wheel, clocks and mirrors (modified)\r\nNene87 help me on editor and blender at the beginning\r\n\r\nClocks are old but it works.\r\nsee the motor behind events ;)\r\nlook at the hand-polishing chromes !\r\n2 versions\r\n\r\nantiroll bar are finally added to maintain fun to drive (it was very slippery without)\r\n\r\n- skins with racing numbers and vintage look\r\n- suspensions 3d anim on the rear\r\n- lean driver animation","userId":79595,"userName":"Tomfuel","wip":true,"publishedAt":1640879379,"numDownloads":3803,"curUsage":0,"rating":4.34,"numRatings":43,"staffPick":false,"tweakMod":false,"version":5,"lastDownloadedAt":1640881808,"class":2,"ev":false,"coverUrl":"https:\/\/www.lfs.net\/attachment\/276798","screenshotUrls":["https:\/\/www.lfs.net\/attachment\/274160","https:\/\/www.lfs.net\/attachment\/274161","https:\/\/www.lfs.net\/attachment\/274162","https:\/\/www.lfs.net\/attachment\/274163","https:\/\/www.lfs.net\/attachment\/274164","https:\/\/www.lfs.net\/attachment\/274165","https:\/\/www.lfs.net\/attachment\/274166","https:\/\/www.lfs.net\/attachment\/274167"],"vehicle":{"iceCc":5237,"iceNumCylinders":8,"iceLayout":0,"evRedLine":0,"drive":1,"shiftType":1,"power":81.76211547851562,"maxPowerRpm":3586,"torque":233.3720703125,"maxTorqueRpm":1687,"mass":889.9309692382812,"bhp":109.66752549133301,"powerWeightRatio":91.87467152480184,"bhpTon":125.20896003186276,"fuelTankSize":39.000003814697266}}}
?>

The Classes i've set up

public class GetCarInfo
{
public ModCarEntry CarInfo { get; set; }
}

public class ModCarEntry
{
public string id { get; set; }
public string name { get; set; }
public string descriptionShort { get; set; }
public string description { get; set; }
public int userId { get; set; }
public string userName { get; set; }
public bool wip { get; set; }
public int publishedAt { get; set; }
public int numDownloads { get; set; }
public int curUsage { get; set; }
public double rating { get; set; }
public int numRatings { get; set; }
public int version { get; set; }
public int lastDownloadedAt { get; set; }
public int _class { get; set; }
public bool ev { get; set; }
public string coverUrl { get; set; }
public List<string> screenshotUrls { get; set; }

public CarDetails details { get; set; }
}
public class CarDetails
{
public int iceCc { get; set; }
public int iceNumCylinders { get; set; }
public int iceLayout { get; set; }
public int evRedLine { get; set; }
public int drive { get; set; }
public int shiftType { get; set; }
public double power { get; set; }
public int maxPowerRpm { get; set; }
public double torque { get; set; }
public int maxTorqueRpm { get; set; }
public double mass { get; set; }
public double bhp { get; set; }
public double powerWeightRatio { get; set; }
public double bhpTon { get; set; }
public double fuelTankSize { get; set; }
}

Bass-Driver
S3 licensed
First you have to connect to your Discord bot.

Open Myinc.LPR file in the includes folder.


<?php 
#####DISCORD VARIABLES#####
$DiscordToken "";
$DiscordChannelReceive ""#discordchannel to sent commands to LFSLapper. (Rightclick on the channel and click 'Copy ID')
$DiscordBotStatus "Powered by LFSLapper";
?>

Once your LFSLapper is connected to your DiscordBot .Check the console for the next message: DiscordBot Connected

Open LFSLapper.LPR and look for the next event: Event OnMSO
And create a new command like shown below.

The function to send messages from LFSLapper to Discord can be done with:

sendmessagetodiscord($DiscordChannel,$Message);


<?php 
Event OnMSO
$userName$text # Player event
    
$idxOfFirtsSpace indexOf$text" ");

    IF( 
$idxOfFirtsSpace == -THEN
      $command 
$text;
      
$argv "";
    ELSE
      
$command subStr$text,0,$idxOfFirtsSpace );
      
$argv trimsubStr$text,$idxOfFirtsSpace ) );
    ENDIF
    
    SWITCH( 
$command )
         CASE 
"!message":
              
$Message $argv;
              
$DiscordChannel "";
              
sendmessagetodiscord($DiscordChannel,$Message);
         BREAK;    
    ENDSWITCH
EndEvent
?>


Last edited by Bass-Driver, .
Bass-Driver
S3 licensed
hello,i've good news, got it working.

First i tried xspeedasx his code with his explaination about .Wait() and .Count
but that didnt do anything, which result is more Task related errors.

Then i googled how to call an async task function in C#.
I came across this page: https://stackoverflow.com/ques ... askt-method-synchronously

In one of the posts it say to use

// For Task<T>: will block until the task is completed...
var result = task.Result;

Basically what xspeedasx was explaining with .Wait().
Then i used LakynVonLegendaus his bit of code from previous post to display some info.

This is the code:


<?php 
public void getmoddedcarinfo(GLScript.unionVal valArrayList args)
        {
            
infoPlayer currInfoPlayer newCfg.getCurrInfoPlayer();
            
string ident val.nameFunction;

            var 
CarInfo LFSRestAPI.GetModdedCars(newCfg.varsLapper.RestAPIClientIDnewCfg.varsLapper.RestAPIClientSecret).Result;
            for (
int i 0CarInfo.Counti++)
            {
                
Console.WriteLine(CarInfo[i].id " = " CarInfo[i].name);
            }
        }
?>

Last edited by Bass-Driver, .
Bass-Driver
S3 licensed
ok installing the system.text.json assembly made my projectfile corrupt.
cool :/

Edit: Thank god i created a backup of the sourcecode, before i changed the Net framework version from 4.6.1 to 4.8
Last edited by Bass-Driver, .
Bass-Driver
S3 licensed
Well, thats what i was thinking. Because i've did that at the first try. and because it did give me an error, i did think it wasnt the right way to do it.

but somehow it give me an error. i also removed 'await'

The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

with await removed:

'Task<List<LFSRestAPI.ModCarEntry>>' does not contain a definition for 'Count' and no extension method 'Count' accepting a first argument of type 'Task<List<LFSRestAPI.ModCarEntry>>' could be found (are you missing a using directive or an assembly reference?)

but which assembly??

LFSLapper is using net.framework 4.8


<?php 
public void getmoddedcarinfo(GLScript.unionVal valArrayList args)
        {

            
infoPlayer currInfoPlayer newCfg.getCurrInfoPlayer();
            
string ident val.nameFunction;

            var 
await LFSRestAPI.GetModdedCars(newCfg.varsLapper.RestAPIClientIDnewCfg.varsLapper.RestAPIClientSecret);

            for (
int i 0v.Counti++)
            {
                
Console.WriteLine(v[i].name);
            }
        }
?>

Last edited by Bass-Driver, .
Bass-Driver
S3 licensed
oke, i clearly missed a step in the process. Thank you for that.
I got a bit further now. But somehow i seems to be crashing at the foreach loop.
with the next error message: Object reference not set to an instance of an object.

i used this webpage as an example.
https://www.codegrepper.com/co ... each+object+in+array+json
and
https://social.msdn.microsoft. ... ?forum=winappswithcsharp

and
https://social.msdn.microsoft. ... s?forum=aspgettingstarted

/* get data */
var list = LFSRestAPI.GetModdedCars(newCfg.varsLapper.RestAPIClientID, newCfg.varsLapper.RestAPIClientSecret);

/* Serialize data to string */
string json = JsonConvert.SerializeObject(list, new JsonSerializerSettings());
//Console.WriteLine(json); // this works yippie:)

============================================================================
/* Deserialize string to object */
LFSRestAPI.ModCarEntriesResponse Cars = JsonConvert.DeserializeObject<LFSRestAPI.ModCarEntriesResponse>(json);

foreach (var car in Cars.Data)
{
Console.WriteLine("" + car.name);
}[/php]



====================================================================

/* Deserialize string to object */
var Cars = JsonConvert.DeserializeObject<List<LFSRestAPI.ModCarEntry>>(json);

foreach (var car in Cars)
{
Console.WriteLine("" + car.name);
}[/php]

edit:
tried this aswell
===============================================================
List<LFSRestAPI.ModCarEntry> cars = JsonConvert.DeserializeObject<List<LFSRestAPI.ModCarEntry>>(json);
foreach (LFSRestAPI.ModCarEntry car in cars)
{
Console.WriteLine("field0: " + car.id);
}

Last edited by Bass-Driver, .
Bass-Driver
S3 licensed
@PeterN:
i do use Async for the Discord API, so that is working as intented.

@xspeedasx:
ye sorry,i was not clear enough about my "challenge" i'm dealing here.

As you can see i created a var named 'list'. I'm trying to read the objects (modded cars i assume) from 'list'.

Tried this method i have found on the web.

<?php 
using Newtonsoft
.Json.Linq;
JArray NewArray JArray.Parse(list.ToString());
            foreach (
JObject Car in NewArray)
            {
                
Console.WriteLine($"{Car["id"]} -> {Car["name"]}");
            }
?>

and trying to get the amount of mods: (this crashes Lapper)


<?php 
JArray NewArray 
JArray.Parse(list.ToString());
            
int nrofmods NewArray.Count;
?>

Also i have tried other methods aswell, but no luck.
There is so much information about Json, i have no idea where to look at, when you are not familiar with Json etc.

I'm sure its something simple i havent seen (most of the time).

Thanks in advanced.
Bass-Driver
S3 licensed
For the past days i have been trying to add the 'LFS REST API' into LFSLapper.
I used the code from xspeedasx from this post: https://www.lfs.net/forum/post/1970141#post1970141

I've managed to get data from the API, so that is a step forward.
But i get stuck on reading the actual data.

i've been reading about Json objects, async tasks etc, but nothing has helped me much. So i have no clue what todo anymore.

There were 2 options: stop working on the sourcecode of LFSLapper or asking for help.
Well i going to ask for help as a non-programmer. No idea why i'm still working on the sourcecode of LFSLapper with all the complexity Smile, because this is beyond my level.
Everything i did in the sourcecode was help from the code itself or from the web like stackoverflow.com etc

Anyway, could someone send me in the right direction on what todo.
Thank you.



<?php 
//scriptFunction.cs
/* Function i call from a LFSLapper Script, this is fine.
CASE "!gm":
    GetModdedCarInfo();
BREAK;*/

public void GetModdedCarInfo(GLScript.unionVal valArrayList args)
        {
            
infoPlayer currInfoPlayer newCfg.getCurrInfoPlayer();
            
string ident val.nameFunction;

            var list = 
LFSRestAPI.GetModdedCars(newCfg.varsLapper.RestAPIClientIDnewCfg.varsLapper.RestAPIClientSecret);
           
        }

//LFSRestAPI.cs

using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using System;
using Configurator;

namespace 
LapperThreads
{
    public class 
LFSRestAPI
    
{
        public static 
async Task<List<ModCarEntry>> GetModdedCars(string RestclientIDstring RestclientSecret)
        { 
            
/*just a few warning messages*/
            
if (string.IsNullOrWhiteSpace(RestclientSecret))
            {
                
Console.WriteLine("ClientSecret Empty");
            }
            if (
string.IsNullOrWhiteSpace(RestclientID))
            {
                
Console.WriteLine("ClientID Empty");
            }

            var 
client = new HttpClient();
            var 
content = new FormUrlEncodedContent(new Dictionary<stringstring>
            {
                {
"client_secret",  RestclientSecret },
                {
"client_id"RestclientID },
                {
"grant_type""client_credentials"}
            });
            var 
tokenResponse await client.PostAsync("https://id.lfs.net/oauth2/access_token"content);
            var 
tokenText await tokenResponse.Content.ReadAsStringAsync();
            var 
tokenObject JsonConvert.DeserializeObject<TokenResponse>(tokenText);
            var 
accessToken tokenObject.access_token;

            
client.DefaultRequestHeaders.Add("Authorization""Bearer " accessToken);

            var 
carEntriesResponse await client.GetStringAsync("https://api.lfs.net/vehiclemod/");
            return 
JsonConvert.DeserializeObject<ModCarEntriesResponse>(carEntriesResponse).Data;
        }

        public class 
TokenResponse
        
{
            public 
string token_type getset; }
            public 
int expires_in getset; }
            public 
string access_token getset; }
        }

        public class 
ModCarEntriesResponse
        
{
            public List<
ModCarEntryData getset; }
        }

        public class 
ModCarEntry
        
{
            public 
string id getset; }
            public 
string name getset; }
            public 
string descriptionShort getset; }
            public 
string description getset; }
            public 
int userId getset; }
            public 
string userName getset; }
            public 
bool wip getset; }
            public 
int publishedAt getset; }
            public 
int numDownloads getset; }
            public 
int curUsage getset; }
            public 
float rating getset; }
            public 
int numRatings getset; }
            public 
int version getset; }
            public 
int lastDownloadedAt getset; }
            public 
int _class getset; }
            public 
bool ev getset; }
        }
}
}
?>

Last edited by Bass-Driver, .
Bass-Driver
S3 licensed
i do not see your server ingame, but i see in the online list on lfs.net ( [DS] Driver Seat )
i've tried to join your server, but it says 'connect timed out'
Bass-Driver
S3 licensed
New insim version:

V2.7(11-12-2021)
-Fix: Window overlap when using Timetable and Reportwindow at the same time.
-Fix: [Times] more efficient way to set/get WR Save when finishing with a WR/PB.(Rewrite)
-Update: [Times] New system to retrieve/save times from/to database (Rewrite)
-Update: [Times] Scheduled save local times to database ( every 15 min if anything has changes within the timetable (PB/WR))
-Update: [TimeTable]: Displays the current list of times of your current car, instead of total timelist.
-Update: [TimeTable]: Filter on 1 car instead of multiple car.
-Disabled [TimeTable]: WR List
-Removed: [TimeTable]: Username filter

Bass-Driver
S3 licensed
As always, a nice looking and well made layout.
Good job.
Wish i could hire your building skills for our TimeAttack server. Tongue

A bummer about your mistake with saving the layout. Happend to me too a few times.
Bass-Driver
S3 licensed
Never used the /o command myself, so you may remove the command from the dedicated servers.
Bass-Driver
S3 licensed
New version online.

V2.6(24-11-2021)
-Add: Modsupport
-Add: CarDamage (TestFase) , get damage while colliding with AutoX objects or Other cars
-Add: [Admincommands]: !amod/!dmod (Add/Delete mod to/from whitelist)
-Add: [PlayerCommand]: !fix (Fix cardamage)

-Update: [LFSLapper] Updated library to 7.0.9.0 Test #5
-Update: [TimeTable] changed design to support mods (SkinID)
-Update: [Top HUD] Small design changes.

Bass-Driver
S3 licensed
New testversion available: Testversion #5
Download available in first post.

Contains a few fixes regarding to Insim Packets and carnames (SkinID)

=================================================
Fix:
================================================
1: [Event]: OnPlayerSelectCar() didnt displayed the name of the car correctly
2: [Event]: Several Events like (OnDist(), OnDriftScore()) didn't execute when more than 8 players on the track
Caused by MCI packet manager didn't allow more than 8 players on the track.

Bass-Driver
S3 licensed
Our servers stopped 2 twice today in a short period of time.
Previous week 2 times aswell. Like yesterday, probably adding a new version to the masterserver.

no /exit command in the logs.

VM.TimeAttack
VM.Dev

Starts to be annoying.
Last edited by Bass-Driver, .
Bass-Driver
S3 licensed
Good looking layout. Thumbs up
i wanted to join your server, but it was pass protected.
Bass-Driver
S3 licensed
Hello,

New Testversion available: Test #4
Download in first post.

Contains a Lappercrash fix and 1 updated file.


=================================================
Changed:
=================================================
1: Updated trackList.cfg

=================================================
Fixed:
=================================================
1: Lappercrash when loading more than 30 objects at once


Bass-Driver
S3 licensed
Since LFS Hosting doesnt support FTP/VPS access for custom InSims applications/libraries.
We are forced to run the InSim application at a 3rd party hosting company, which cost you more money.
Or your pc/server at home, which has to stay on for 24/7.

I do run my InSim (LFSLapper) from a pc at home. So for me its not that much of a problem. But ye, i whould like to have the InSim app and LFS DCON at the same machine.
Bass-Driver
S3 licensed
try /refresh
That worked for me.
Bass-Driver
S3 licensed
New Testversion available : Testversion #3
Download in first post.

This version contains 2 functions to set/get allowed modded cars.

=================================================
New:
=================================================

1: [LapperFunction]: SetListAllowedMods(); Set allowed mods. Max 120 mods allowed


<?php 
        
CASE "!setmodlist":
                
SetListAllowedMods("4A1C57,FA2989,39CEEB,238F06"); 
                
#SetListAllowedMods(""); #Allow all mods.
        
BREAK;
        
?>


2: [LapperFunction]: GetListAllowedMods(); Get list of allowed mods.


<?php 
        
CASE "!getmodlist":
            
$List getlistallowedmods();
            
$NrOfMods ToNum($List["NrOfAllowedMods"]);
            
            
privmsg("^7===== ^3List of Allowed mods ^7(".$NrOfMods.") ^3mods ^7=====");
            
            IF(
$NrOfMods == 0THEN
                privmsg
("^3All mods are allowed!");
            ELSE    
                FOR ( 
$i 0$i $NrOfMods $i $i 1)
                    
privmsg("^7Mod ^0[^3".$i+1."^0]^7: ".$List[$i,"SkinID"]);
                ENDFOR
            ENDIF    
        BREAK;
?>

Last edited by Bass-Driver, .
Bass-Driver
S3 licensed
@ Van Sterberkt : Thank you


New Testversion available

+---------------------------------------------------------------+
|Changes from 7.0.9.0 TEST #1 to 7.0.9.0 TEST #2
+---------------------------------------------------------------+
=================================================
New:
=================================================
1: New Playervar: "SkinName". GetPlayerVar("SkinName");
=================================================
Changed:
=================================================
1: PlayerVar: GetPlayerVar("Car"); , Will now display the SkinID, if you've selected a mod.

Bass-Driver
S3 licensed
Good news Omg omg omg

It were a few frustrating days, because i had no idea what todo with the new insim packet sizes etc. But i finally managed to get LFSLapper working on LFS version W43. Atleast it does load LFSLapper and the things it must do.

Grab the first test version in the first post.

Thank you all who helped me. Much appreciated Smile
Bass-Driver
S3 licensed
I did manage to Connect LFSlapper with the server by multiply some values with 4 in the TCP section of the insim. Most of the code is not commented or is in french.
so that is some progress.

Still have some issues with reading the correct packets and their values.
FGED GREDG RDFGDR GSFDG