While using a Python socket connection and I received the following from the server (simulator):
'C\xbc\x7fZC\xbc\x7f5C\xbc\x7f&C\xbc\x7f!C\xbc\x7f\x14C\xbc\x7f\x16C\xbc\x7f!C\xbc\x7f\x12C\xbc\x7f\x19C\xbc\x80\x03C\xbc\x81~C\xbc\x80FC\xbc\x7f\xd1C\xbc~\xcdC\xbc~\xd7C\xbc\x7f$;4\xe0\xb8;\x81\xf6\xd7;R\xf4T:\xc5v\xb4:\xc1>\xc1:\xd9\x15\x9a:\xa8M7;K\xde{:\xfb\\\xcd\xbc\tR\xd4\xba\xe1\xb6\xf3\xbb\xc9\xb8\xf4\xbby\x8a\x199\x9dH\x009\x0cp\x00:\xeb<\x00'
But my actual output should be (size 32x1):
376.99493 376.99380 376.99335 376.99319 376.99280 376.99286
376.99319 376.99274 376.99295 377.00009 377.01166 377.00214
376.99857 376.99063 376.99094 376.99329 0.0027599763
0.0039661932 0.0032189088 0.0015065284 0.0014743434
0.0016562224 0.0012840395 0.0031107950 0.0019177437
-0.0083815642 -0.0017220661 -0.0061560813 -0.0038076697
0.00029999018 0.00013393164 0.0017946959
How can I convert the ASCII codes to get those numbers in Python 2.7.
To convert the floats from a socket, you can use struct.unpack.
Code:
num_floats = int(len(raw_data) / 4)
format_str = '>' + 'f' * num_floats
data = struct.unpack(format_str, raw_data[:num_floats * 4])
Test Code:
import struct
raw_data = b'C\xbc\x7fZC\xbc\x7f5C\xbc\x7f&C\xbc\x7f!C\xbc\x7f\x14C\xbc' \
b'\x7f\x16C\xbc\x7f!C\xbc\x7f\x12C\xbc\x7f\x19C\xbc\x80\x03C' \
b'\xbc\x81~C\xbc\x80FC\xbc\x7f\xd1C\xbc~\xcdC\xbc~\xd7C\xbc' \
b'\x7f$;4\xe0\xb8;\x81\xf6\xd7;R\xf4T:\xc5v\xb4:\xc1>\xc1:\xd9' \
b'\x15\x9a:\xa8M7;K\xde{:\xfb\\xcd\xbc\tR\xd4\xba\xe1\xb6\xf3' \
b'\xbb\xc9\xb8\xf4\xbby\x8a\x199\x9dH\x009\x0cp\x00:\xeb'
num_floats = int(len(raw_data) / 4)
format_str = '>' + 'f' * num_floats
data = struct.unpack(format_str, raw_data[:num_floats * 4])
print(data)
Results:
(376.99493408203125, 376.9938049316406, 376.99334716796875,
376.9931945800781, 376.9927978515625, 376.99285888671875,
376.9931945800781, 376.99273681640625, 376.9929504394531,
377.0000915527344, 377.01165771484375, 377.00213623046875,
376.9985656738281, 376.9906311035156, 376.9909362792969,
376.9932861328125, 0.00275997631251812, 0.003966193180531263,
0.0032189087942242622, 0.001506528351455927, 0.0014743433566763997,
0.001656222390010953, 0.001284039462916553, 0.003110795048996806,
0.0019177338108420372, 4.2194070097596986e+21, 456834187264.0,
-7.263825409609126e-06, -0.00011669746163534, -7.377517891143851e-33,
131300.1875, 1.5874123484317317e+29)
Related
I have the below code in CPP that I am trying to port to Python to send data to a UDPS
#define VERSION_MAIN "V6.60"
#define VERSION_BIN_MAJOR 0x06
#define VERSION_BIN_MINOR 0x60
unsigned char temp[3];
temp[0] = VERSION_MAIN[0];
temp[1] = VERSION_BIN_MAJOR;
temp[2] = VERSION_BIN_MINOR;
I have tried code like the following:
byteone = bytes(VERSION_MAIN, 'utf-8')
hex_string = '0x06'
decimal_int = int(hex_string, 16)
decimal_string = str(decimal_int)
digits = [int(c) for c in decimal_string]
zero_padded_BCD_digits = [format(d, '04b') for d in digits]
s = ''.join(zero_padded_BCD_digits)
bytetwo = bytes(int(s[i : i + 8], 2) for i in range(0, len(s), 8))
hex_string = '0x60'
decimal_int = int(hex_string, 16)
decimal_string = str(decimal_int)
digits = [int(c) for c in decimal_string]
zero_padded_BCD_digits = [format(d, '04b') for d in digits]
s = ''.join(zero_padded_BCD_digits)
bytethree = bytes(int(s[i : i + 8], 2) for i in range(0, len(s), 8))
values = (byteonw,bytetwo,bytethree )
s= struct.Struct(f'!3B')
packed_data = s.pack(*values)
but I keep getting pesky errors
struct.error: required argument is not an integer
Can anyone give me a hand please.
Thanks
No need to convert V into an int, pack can manage the char type as well.
from struct import pack
VERSION_MAIN = "V6.60"
VERSION_BIN_MAJOR = 0x06
VERSION_BIN_MINOR = 0x60
version = pack("!c2B", VERSION_MAIN[0].encode('utf-8'), VERSION_BIN_MAJOR, VERSION_BIN_MINOR)
# version = b'V\x06`'
Hello im getting "ValueError: could not convert string to float: " error in python I know what this error means but i cant fix it... i have converted string to float but getting same error anyone can help me ?
#CAKE POOL
cake_pool = '0x73feaa1ee314f8c655e354234017be2193c9e24e'
cake_staked_url = "https://api.bscscan.com/api?module=account&action=tokenbalance&contractaddress=0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82&address=" + cake_pool + "&tag=latest"
response = requests.get(cake_staked_url)
cakeurl = response.json()
staked_cake = float(cakeurl['result']) / 1000000000000000000
staked_cake = float(staked_cake) <---- converted string to float
print(type(staked_cake) , str(staked_cake)) <--- result 'float'
staked_cake = '{0:,.2f}'.format(float(staked_cake))
print("CAKE POOL: " + str(staked_cake) + " CAKE STAKED")
#END OF CAKE POOL
#BNB POOL
bnb_pool = '0x326D754c64329aD7cb35744770D56D0E1f3B3124'
bnb_staked_url = "https://api.bscscan.com/api?module=account&action=tokenbalance&contractaddress=0x0e09fabb73bd3ade0a17ecc321fd13a19e81ce82&address=" + bnb_pool + "&tag=latest"
response = requests.get(bnb_staked_url)
bnburl = response.json()
staked_bnb = float(bnburl['result']) / 1000000000000000000
staked_bnb = float(staked_bnb) <---- converted string to float
print(type(staked_bnb), staked_bnb) <--- result 'float'
print(staked_bnb)
total = float(staked_cake) + float(staked_bnb) <---- i want to sum 'staked_cake' and 'staked_bnb' but getting error
print(total)
staked_bnb = '{0:,.2f}'.format(float(staked_bnb))
print("BNB POOL: " + staked_bnb + " CAKE STAKED")
#END OF BNB POOL
FIXED :D
staked_cake = '{0:,.2f}'.format(float(staked_cake))
This is why i was getting error message :D
Print each of your strings and check if you can convert them to float or not. I'm sure you would find ones that you can't. Let me know if this doesn't work
Can someone please help me with converting this code?
I tried to make RIJNDAEL256 function out of this code:
EncryptRJ256("lkirwf897+22#bbtrm8814z5qq=498j5", "741952hheeyy66#cs!9hjv887mxx7#8y", "A padded string to BLOCKSIZE length.")
Public Function EncryptRJ256(ByVal prm_key As String, ByVal prm_iv As String, ByVal prm_text_to_encrypt As String) As String
Dim s As String = prm_text_to_encrypt
Dim managed2 As New RijndaelManaged With {
.Padding = PaddingMode.Zeros,
.Mode = CipherMode.CBC,
.BlockSize = 256
}
Dim stream As New MemoryStream
Dim stream2 As New CryptoStream(stream, managed2.CreateEncryptor(Encoding.ASCII.GetBytes(prm_key), Encoding.ASCII.GetBytes(prm_iv)), CryptoStreamMode.Write)
Dim bytes As Byte() = Encoding.ASCII.GetBytes(s)
stream2.Write(bytes, 0, bytes.Length)
stream2.FlushFinalBlock()
Return Convert.ToBase64String(stream.ToArray)
End Function
I need the output of the encrypted string to be something like this:
Dv0Y/AFXdFMlDrcldFCu8v5o9zAlLNgyM+vO+PFeSrpO8Ve82mdUcc4rkzp9afDYc75NmkSd4mdflt38kceOdA==
A padded string to BLOCKSIZE length
I came up with this but the output is invalid. It's probably because of wrong padding but I have no idea how to fix it:
from rijndael.cipher.crypt import new
from rijndael.cipher.blockcipher import MODE_CBC
import base64
PADDING = b'.'
def r_pad(payload, block_size=32):
return payload + (block_size - len(payload) % block_size) * PADDING
KEY = 'lkirwf897+22#bbtrm8814z5qq=498j5'
IV = '741952hheeyy66#cs!9hjv887mxx7#8y'
plain_text = "A padded string to BLOCKSIZE length."
rjn = new(KEY, MODE_CBC, IV, blocksize=32)
encd = rjn.encrypt(r_pad(plain_text))
data = base64.b64encode(encd)
print(data)
rjn = new(KEY, MODE_CBC, IV, blocksize=32)
data = base64.b64decode(data)
decd = rjn.decrypt(r_pad(data))
print (decd)
This is the output:
Dv0Y/AFXdFMlDrcldFCu8v5o9zAlLNgyM+vO+PFeSrqWdzP1S1cumviFiEjNAjz5njnMMC9lfxsBl71x5y+xCw==
A padded string to BLOCKSIZE length.............................Å¿:è°⌐┘n┤«╞Px╜:æC┬♣╬Q┤▼«U_♦â☻ìr
How silly of me! Here's what fixed my issue:
from rijndael.cipher.crypt import new
from rijndael.cipher.blockcipher import MODE_CBC
import base64
PADDING = b'\x00'
def pad(payload, block_size=32):
return payload + (block_size - len(payload) % block_size) * PADDING
def un_pad(payload):
return payload.replace(PADDING, '')
KEY = 'lkirwf897+22#bbtrm8814z5qq=498j5'
IV = '741952hheeyy66#cs!9hjv887mxx7#8y'
plain_text = "A padded string to BLOCKSIZE length."
rjn = new(KEY, MODE_CBC, IV, blocksize=32)
encd = rjn.encrypt(pad(plain_text))
data = base64.b64encode(encd)
print(data)
rjn = new(KEY, MODE_CBC, IV, blocksize=32)
data = base64.b64decode(data)
decd = rjn.decrypt(un_pad(data))
print (decd)
I'm struggling with serial write communication. Basically I don't know which option to choose to combine both integers and float values in the correct way for serial write.
The problem: I need to send data values (chars,int, floats) to a microcontroller (ARM8 processor) for control of wheels for a robot platform. By means of a RS422 to USB converter I'm able to read data values from the same microcontroller, by means of this Python code:
import serial
from struct import unpack
# Initialization
counter = 0
#open serial for reading (BMW to PC communication)
s_port = 'COM8'
b_rate = 460800
ser = serial.Serial(port=s_port,baudrate=b_rate,timeout=0.01)
#method for reading incoming bytes on serial
while counter<20:
data = ser.readline()
data = data.encode("hex")
strlen = len(data)
rev_data = "".join(reversed([data[i:i+2] for i in range(0, len(data), 2)]))
if strlen==80:
Soh = data[0:2]
Nob = data[2:4]
Adr = data[4:6]
Cmd = data[6:8]
Hrt = data[8:12]
Po1 = data[12:28]
Po2 = data[28:44]
En1 = data[44:60]
En2 = data[60:76]
Crc = data[76:78]
Eot = data[78:80]
So1 = unpack('B', Soh.decode("hex")) # unsigned char
No1 = unpack('B', Nob.decode("hex")) # unsigned char
Ad1 = unpack('B', Adr.decode("hex")) # unsigned char
Cm1 = unpack('B', Cmd.decode("hex")) # unsigned char
Hr1 = unpack('h', Hrt.decode("hex")) # short
Po1 = unpack('d', Po1.decode("hex")) # double
Po2 = unpack('d', Po2.decode("hex")) # double
En1 = unpack('d', En1.decode("hex")) # double
En2 = unpack('d', En2.decode("hex")) # double
Cr1 = unpack('B', Crc.decode("hex")) # unsigned char
Eo1 = unpack('B', Eot.decode("hex")) # unsigned char
StartOfHeader = So1[0]
NoOfBytes = No1[0]
Address = Ad1[0]
Command = Cm1[0]
Heartbeat = Hr1[0]
Potentiometer1 = Po1[0]
Potentiometer2 = Po2[0]
Encoder1 = En1[0]
Encoder2 = En2[0]
CRC = Cr1[0]
EndOfTransmission = Eo1[0]
counter = counter+1
ser.close()
In Labview the serial write communication is already working, so that is my starting point:
But as I need to work with Python the trick is to make it working in Python.
To my knowledge the data is converted to ASCII, based on the "Type Cast" function in Labview (http://digital.ni.com/public.nsf/allkb/287D59BAF21F58C786256E8A00520ED5)
Honestly I don't nothing about ASCII messages, so I'm not 100% sure.
Now, I want to do the same trick for the serial write in Python 2.7. Starting from chr,int, float values converting to hexadecimal string and then write to the serial port. I suppose to use an ASCII conversion at the end, but I don't know if it's ASCII and the right Python command to do the conversion in the right way.
This is my serial write coding in Python so far (excuse me, for the long and inefficient coding lines):
# Initialization
counter = 0
#open serial for reading (BMW to PC communication)
s_port = 'COM9'
b_rate = 460800
ser = serial.Serial(port=s_port,baudrate=b_rate,timeout=0.05)
#method for writing to serial
while counter<100:
Soh = chr(1)
Nob = chr(46)
Adr = chr(49)
Cmd = chr(32)
DFS = float(1)
DRS = float(2)
DFD = int(3)
DRD = int(4)
DFC = int(5)
DRC = int(6)
SFCP = float(7)
SRCP = float(8)
SFC = int(9)
SRC = int(10)
CRC = chr(77)
EOT = chr(4)
S1 = Soh.encode("hex")
N1 = Nob.encode("hex")
A1 = Adr.encode("hex")
C1 = Cmd.encode("hex")
D11 = hex(struct.unpack('<I', struct.pack('<f', DFS))[0])
D1 = D11[2:]
D12 = hex(struct.unpack('<I', struct.pack('<f', DRS))[0])
D2 = D12[2:]
D3 = '{0:08x}'.format(DFD)
D4 = '{0:08x}'.format(DRD)
D5 = '{0:08x}'.format(DFC)
D6 = '{0:08x}'.format(DRC)
S11 = hex(struct.unpack('<I', struct.pack('<f', SFCP))[0])
S2 = S11[2:]
S12 = hex(struct.unpack('<I', struct.pack('<f', SRCP))[0])
S3 = S12[2:]
S4 = '{0:08x}'.format(SFC)
S5 = '{0:08x}'.format(SRC)
C2 = CRC.encode("hex")
E1 = EOT.encode("hex")
hex_string = E1 + C2 + S5 + S4 + S3 + S2 + D6 + D5 + D4 + D3 + D2 + D1 + C1 + A1 + N1 + S1
rev_hex_string = "".join(reversed([hex_string[i:i+2] for i in range(0, len(hex_string), 2)]))
##command = ...
ser.write(command)
counter = counter+1
ser.close()
This Python code generates the same hexadecimal string (called rev_hex_string) as the Labview programm. But till now, I was unable to do the serial write with Python.
I don't know how to proceed. Do I need ASCII for serial write? And which Python codes to use? encode("ascii"), decode("hex")? I'm totally lost in the many possibilities....
In case I use encode("ascii") or decode("hex") in Python it only generates a " .01" (ASCII???) message.
When I switch the normal view in Labview it has a much longer message:
" .01 €? # | - à# A M"
(I still missing some characters, but this is the most)
Besides that; do I need carriage returns and/or buffer flushing?
I have to say I'm new to serial write communication. I hope you can help me.
Sorry for the long post, I hope to be as precise as possible.
I am new to PyTables and implemented a few basic techniques of inserting and retrieving data from a table in Pytables. However, I am not sure about how to insert data in an existing table of PyTables because all I read/get in the tutorial is creating a new table (using h5file.createTable() method). Here is the basic code that tutorial has about inserting data into PytTables table created from scratch:
h5file = openFile("tutorial1.h5", mode = "w", title = "Test file")
group = h5file.createGroup("/", 'detector', 'Detector information')
table = h5file.createTable(group, 'readout', Particle, "Readout example")
for i in xrange(10):
particle['name'] = 'Particle: %6d' % (i)
particle['TDCcount'] = i % 256
particle['ADCcount'] = (i * 256) % (1 << 16)
particle['grid_i'] = i
particle['grid_j'] = 10 - i
particle['pressure'] = float(i*i)
particle['energy'] = float(particle['pressure'] ** 4)
particle['idnumber'] = i * (2 ** 34)
# Insert a new particle record
particle.append()
table.flush()
P.S. There is one place in this tutorial that talks about appending data to an existing table, but uses the table that was created from scratch and basically gives no idea about selecting pre-existing table for appending data. Kindly help. Thanks.
You need open your file in append mode "a". Also do not create the group and table again. This appends another 10 rows:
import tables
class Particle(tables.IsDescription):
name = tables.StringCol(16) # 16-character String
idnumber = tables.Int64Col() # Signed 64-bit integer
ADCcount = tables.UInt16Col() # Unsigned short integer
TDCcount = tables.UInt8Col() # unsigned byte
grid_i = tables.Int32Col() # 32-bit integer
grid_j = tables.Int32Col() # 32-bit integer
pressure = tables.Float32Col() # float (single-precision)
energy = tables.Float64Col() # double (double-precision)
h5file = tables.openFile("tutorial1.h5", mode = "a")
table = h5file.root.detector.readout
particle = table.row
for i in range(10, 20):
particle['name'] = 'Particle: %6d' % (i)
particle['TDCcount'] = i % 256
particle['ADCcount'] = (i * 256) % (1 << 16)
particle['grid_i'] = i
particle['grid_j'] = 10 - i
particle['pressure'] = float(i*i)
particle['energy'] = float(particle['pressure'] ** 4)
particle['idnumber'] = i * (2 ** 34)
# Insert a new particle record
particle.append()
h5file.close()