-
Notifications
You must be signed in to change notification settings - Fork 2
/
ser_util.py
57 lines (38 loc) · 1.22 KB
/
ser_util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import struct
import array
# Pass in list of 4 bytes, returns float
def BytesToFloat(bytes):
return bytestovar(bytes, 'f')
# Pass in a float variable, returns list of 4 bytes
def FloatToBytes(float):
return vartobytes(float, 'f', 4)
# Pass in list of 2 bytes, returns short
def BytesToShort(bytes):
return bytestovar(bytes, 'H')
# Pass in short, returns list of 2 bytes
def ShortToBytes(short):
return vartobytes(short, 'H', 2)
# Pass in list of 4 bytes, returns int
def BytesToInt(bytes):
return bytestovar(bytes, 'I')
# Pass in int, returns list of 4 bytes
def IntToBytes(int):
return vartobytes(int, 'I', 4)
# Packs a variable, given a data type and number of bytes
# Returns list of bytes, LSB first (little endian)
def vartobytes(data, type, numbytes):
s = struct.Struct(type)
packed = s.pack(data)
data = list()
for i in range(0,numbytes):
data.append(int(packed[i].encode('hex'), 16))
return data
def bytestovar(data, type):
extract = array.array('B', data).tostring()
s = struct.Struct(type)
return (s.unpack(extract))[0]
def readBytes(serial, numbytes):
data = list()
for i in range(0, numbytes):
data.append(serial.read())
return data