The online racing simulator
Quick and Dirty MATLAB code for live position/speed/head
So I spent some time trying to find some code I could use to connect MATLAB to LFS. My primary interest was to write AI or bot drivers, but the interface between MATLAB and LFS is significantly complex to devote the entire post.

I'm pretty sure the easiest way to get live measurements is through insim. The following code accesses insim directly from MATLAB. In other words to get this code working you don't need any other libs except for the standard MATLAB stuff.

Serious coders will notice the style is very causual/arbitrary. I was going for a very short yet easy to understand code that is fast and can easily be changed, so forgive me for not OOP.

I've tried playing around with the java robot in order to control the car.

Hope this saves you some time comments welcome!

Notes:

1. Serious limitation of code is how the array sizes grow to accommodate new measurements. While for up to 10000 samples on a fast computer I've seen no problems your mileage may vary.
2. Need to type '/insim 50000' into the LFS client to start updates.
3. This code has only been tested for a single car in single player mode where you are the host.
4. For exact description of data gathered look at insim.txt file in your lfs installation.*


clc
clear all

t = tcpip('localhost', 50000); %Connecting on 50000 so type '/insim 50000' into lfs client
set(t,'InputBufferSize',4000); %No idea about buffer size, this works fine for me
fopen(t)
% Magic ini byte strings, the 40 is the update speed, equivalent to 25 updates/ sec
%1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
fwrite(t,[44 1 0 0 0 0 36 0 0 0 40 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 'new2' 0 0 0 0 0 0 0 0 0 0 0 0]);
ci = 0;
ok = 0;
prob = 0;
j= 0;
tic
while true
ci = ci + 1;
if ci > 10000
break
end
psize = get(t,'BytesAvailable');
while psize == 0
pause(0.01)
psize = get(t,'BytesAvailable');
end
tempHead = fread(t,2)';
if (tempHead(2) == 38)&&(tempHead(1) == 32)
tempc = [char(0) char(0) fread(t,30)'];
elseif (tempHead(2) == 3)&&(tempHead(1) == 4)
'ver' %keep alive?
tempc = fread(t,psize-2)';
fwrite(t,[4 3 0 0]);
else
prob = prob + 1
tempc = fread(t,psize-2)';
end
if(length(tempc)==32) %If expected packet length parse data about car
j = j + 1;
tempcoords = get(0,'PointerLocation');
coord(j) = tempcoords(1);
posX(j) = typecast(uint32([ tempc(9:12)] * [ 2^0 2^8 2^16 2^24]'),'INT32');
posY(j) = typecast(uint32([ tempc(13:16)] * [ 2^0 2^8 2^16 2^24]'),'INT32');
posZ(j) = typecast(uint32([ tempc(17:20)] * [ 2^0 2^8 2^16 2^24]'),'INT32');
speed(j)= tempc(25:26)*[2^0 2^8]';
dir(j) = tempc(27:28)*[2^0 2^8]';
head(j) = tempc(29:30)*[2^0 2^8]';
end
if mod(ci, 100) == 0
display(['I# ' num2str(ci) ' update/s: ' num2str(ci/toc) ' speed: ' num2str(speed(j)) ]);
display(['posX: ' num2str(posX(j)) ' posY: ' num2str(posY(j)) ' posZ: ' num2str(posZ(j))]);
end
end


FGED GREDG RDFGDR GSFDG