Reputation: 3
I´m looking for some help converting CAN packets from a PCAN-GPS unit to long/lat GPS coordinates.
For example i receive Data=90F98E400A0045 for longitude and the package is in the following format:
imgur link
So I get the Degree and Indicator part which match my location from Google Maps but when I try to convert the hex value to a floating point I either get enormous or tiny float values that are not longitude values.
I wrote this code (and some other variations) in Python. My location is somewhere in germany ;)
s = ['E8', '5F', '8F', '40', '0A', '00', '45']
con = []
x = ""
def tohex(hex_string):
return ''.join('{0:04b}'.format(int(c, 16)) for c in hex_string)
def long(str):
min = str[:32]
vorz = min[:1]
mat = int(min[1:24], 2)
exp = int(min[24:32], 2)
l = (2**exp) * float("0."+mat.__str__())
deg = str[32:48]
print(int(deg,2))
return l
for e in s:
con.append(tohex(e))
x += tohex(e)
print("%.100f" % long(x))
Upvotes: 0
Views: 1503
Reputation: 1663
The more efficient solution is to use the
struct.unpack()
function.
Solution for Python 3.5.x
1- store the binary data recorded from CANbus in a bytes object.
tCanLng1=bytes([0xE8, 0x5F, 0x8F, 0x40, 0x0A, 0x00, 0x45])
2- define the format specifier of the GPS_PositionLongitude
structure.
For
GPS_LongitudeMinutes
(float) is'f'
(4 bytes).For
GPS_LongitudeDegree
(int16) is'h'
(2 bytes).For
GPS_IndicatorEW
(char) is'c'
(1 byte).End for the byte alignment (little-endian) add as first specifier
'<'
3- Then perform the unpack of the CANbus binary data as follow:
>> vCanLng=struct.unpack('<fhc',tCanLng1)
>> vCanLng
(4.480457305908203, 10, b'E')
4- And the result for your position in Germany is:
GPS_LongitudeMinutes = vCanLng[0] = 4.480457305908203
GPS_LongitudeDegree = vCanLng[1] = 10
GPS_IndicatorEW = vCanLng[2] = 'E'
GPS_PositionLongitude = 10° 4.480457305908203 E = (10 + (4.480457305908203/60))° E = 10.0746742884318 ° East.
Upvotes: 1