Snap7 get_real command not working, how to fix? - python

client = snap.client.Client()
client.connect('XXX.XXX.X.XXX', 0, 2) #IP address, rack, slot
db = client.db_get(20)
print(db)
intDB = []
for i in range(1, 122):
reading = client.db_read(20, i, 1)
realReading = snap.util.get_real(reading, 0)
array = [realReading]
intDB.append(array)
print(intDB)
This code is supposed to print a DB in bytearrays and then print an array with the floats values of the PLC output. However, when I run the code, I get the following error message:
Traceback (most recent call last):
File "C:/Users/Asus/PycharmProjects/PLC-Connection/main.py", line 19, in <module>
realReading = snap.util.get_real(reading, 0)
File "C:\Users\Asus\PycharmProjects\PLC-Connection\venv\lib\site-packages\snap7\util.py", line 357, in get_real
real = struct.unpack('>f', struct.pack('4B', *x))[0]
struct.error: pack expected 4 items for packing (got 1)

I think that the problem is reading the data:
reading = client.db_read(20, i, 1)
20 is the datablock, i is the index, and you read only 1 byte (3rd parameter).
For retrieving a real, you need 4 bytes read out.

Related

Why do I get a MemoryError in 64bit python when doing a replace within a 8MB file? (Bytes)

I have a mitmproxy flow that contains multiple image files. The flow itself is in bytes. I am trying to dump the old images to files, then replace them within the flow with my own images.
However, I hit a Memory Error in Python and I don't understand why. The flow file itself is 8mb, the pictures I am trying to replace the old ones with are small, less then 100kb. There should be plenty of memory for that?
startList = list(re.finditer(b'\xff\xd8',flowContent))
x = 1
for a in startList:
end = flowContent.find(b'\xff\xd9',a.start())
fileContent = flowContent[a.start():end]
fileName = 'image'+str(x)+".jpg"
dumpfile = open('dump/'+fileName,'wb')
dumpfile.write(fileContent)
dumpfile.close()
replace = open('replace/replace'+str(x)+'.jpg','rb')
myImage = Image(replace)
replace.close()
nowTime = datetime.now()
myImage.datetime = nowTime.strftime(DATETIME_STR_FORMAT)
myImage.datetime_digitized = nowTime.strftime(DATETIME_STR_FORMAT)
myImage.datetime_original = nowTime.strftime(DATETIME_STR_FORMAT)
newImage = open('replace/replace'+str(x)+'U.jpg',"wb")
newImage.write(myImage.get_file())
newImage.close()
replaceF = open('replace/replace'+str(x)+'U.jpg','rb')
replaceContent = replaceF.read()
replaceF.close()
flowContent = flowContent.replace(fileContent,replaceContent)
#flowContent = re.sub(fileContent,myImage.get_file(),flowContent)
x = x+1
The error is on this line:
Traceback (most recent call last):
File "E:\SpecialK\flow.py", line 41, in <module>
flowContent = flowContent.replace(fileContent,replaceContent)
MemoryError

'_csv.reader' object is not callable

This program is supposed to emit sound based on a CSV file.
There is a frequency range in the dataset of 37-32677. In the beginning I didn't add this in and got this same error message. I tried adding in this range and I am still getting the same error.
import winsound
import csv
winsound.Beep(261,100)
def preload(filename):
file = open(filename)
data = csv.reader(file)
return data
def getNote(sensorVal):
return int(sensorVal * 75)
def setup():
cleanedData = {}
notes = []
data = preload("data1.csv")
for row in data(range(36,32677)):
print(row)
if row[1] != "trial number":
sensorVal = float(row[4])
channel = int(row[7])
if channel not in cleanedData:
cleanedData[channel] = []
cleanedData[channel].append({"sensorVal":sensorVal})
notes.append(getNote(sensorVal))
return cleanedData,notes
def play(notes,time):
for note in notes:
winsound.Beep(note,time)
data, notes = setup()
play(notes, 200)
Error message:
Traceback (most recent call last):
File "C:/Users/clair/PycharmProjects/winSound/main.py", line 32, in <module>
data, notes = setup()
File "C:/Users/clair/PycharmProjects/winSound/main.py", line 16, in setup
for row in data(range(36,32677)):
TypeError: '_csv.reader' object is not callable
Process finished with exit code 1

string index out of range? - python

im buliding a chat and i'm keep getting the next error:
Traceback (most recent call last):
File "C:/Users/ronen/Documents/CyberLink/tryccc.py", line 651, in <module>
main()
File "C:/Users/ronen/Documents/CyberLink/tryccc.py", line 630, in main
print_message(data_from_server, len(temp_message), username)
File "C:/Users/ronen/Documents/CyberLink/tryccc.py", line 265, in print_message
temp_l = data[0]
IndexError: string index out of range
i am trying to get the first char of the data string and convert it into int but i get this error
the problem is in the first line of the code
def print_message(d_temp, line_length, this_username):
temp_l = d_temp[0] #the problematic line
len_username = int(temp_l)
username_sender = d_temp[1:(len_username + 1)]
message_sent = d_temp[(len_username + 1): -4]
hour_time = d_temp[-4: -2]
min_time = d_temp[-2:]
printed_message = "\r" + hour_time + ":" + min_time + " " + username_sender + " : " + message_sent
print printed_message, # Prints this message on top of what perhaps this client started writing.
# if this client started typing message
complete_line_with_space(len(printed_message), line_length)
data- the data (string) from the server
line_length - the length of the temp massage
this_username - the client's username
thank you to all the helpers
empty d_temp will give this error.
This might be the reason:
>>> d_temp = ""
>>> d_temp[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
This happens because print_message is executed with an empty string as first parameter
print_message("",...)
This means the problem is somewhere else in your code.

Python - send uint8 and uint16 to socket

I'm trying to send some data with a python script to a java server. I use the socket module in python to send and recieve data.
When I send data, I need to specify a header with the datalength in it. The header is as following:
a uint8 for the version number
a uint8 for padding ('reserved')
a uint16 for the length of the data that is sent
That is a total of 32 bits.
I can use numpy to create an array with a certain data type, but the problem is sending this data through the socket. I use the following function to send data:
def send(socket, message):
r = b''
totalsent = 0
# as long as not everything has been sent ...
while totalsent < len(message):
# send it ; sent = actual sent data
sent = socket.send(message[totalsent:])
r += message[totalsent:]
# nothing sent? -> something wrong
if sent == 0:
raise RuntimeError("socket connection broken")
# update total sent
totalsent = totalsent + sent
return r
message = (something_with_numpy(VERSION_NUMBER, PADDING, len(data)))
send(socket, message)
I keep getting TypeErrors with this function. These pop up at len(message), r += message[...], or some other place.
I was wondering if there is a better way to do this, or how to fix this so it does work?
UPDATE: here are some exact error traces. I have tried several different things, so these error traces might have become irrelevant.
Traceback (most recent call last):
File "quick.py", line 47, in <module>
header += numpy.uint8(VERSION_NUMBER)
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S3') dtype('S3') dtype('S3')
header = numpy.array([VERSION_NUMBER * 255 + PADDING, len(greetData)], dtype=numpy.uint16)
Traceback (most recent call last):
File "quick.py", line 48, in <module>
print(header + greetData)
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S22') dtype('S22') dtype('S22')
Traceback (most recent call last):
File "quick.py", line 47, in <module>
r = send(conn, numpy.uint8(VERSION_NUMBER))
File "quick.py", line 13, in send
while totalsent < len(message):
TypeError: object of type 'numpy.uint8' has no len()
Traceback (most recent call last):
File "quick.py", line 47, in <module>
r = send(conn, numpy.array([VERSION_NUMBER], dtype=numpy.uint8))
File "quick.py", line 17, in send
r += message[totalsent:]
TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S3') dtype('S3') dtype('S3')
You'll want to use the struct module to format the header before sending the data.
import struct
def send_message(socket, message):
length = len(message)
version = 0 # TODO: Is this correct?
reserved = 0 # TODO: Is this correct?
header = struct.pack('!BBH', version, reserved, length)
message = header + message # So we can use the same loop w/ error checking
while ...:
socket.send(...)

Python write file empty

I'm trying to write a script to convert an Intel HEX file to a Verilog mem format.
I can print the strings I want to save OK (eg the read & parse bit's working) but when I try to write to a file nothing ever appears :(
ihexf = open("test.hex","r")
vmemf = open("test.mem","w")
for line in ihexf:
rlen_s = line[1:3]
addr_s = line[3:7]
rtyp_s = line[7:9]
rlen = int(rlen_s, 16)
addr = int(addr_s, 16)
rtyp = int(rtyp_s, 16)
# print(rlen_s,addr_s,rtyp_s)
if rtyp == 0:
# print('#'+addr_s)
vmemf.write('#'+addr_s+'\n')
for i in range (0, rlen):
laddr = addr + i
val_s = line[9+i*2:9+i*2+2]
val = int(val_s, 16)
# print(val_s)
vmemf.write(val_s+'\n')
# print("")
else:
print("------- End Of File ------")
ihexf.close()
vmemf.close()
My test.hex looks like
:20000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000FF000000FF000000FF555540FF0A
:20000800155540FF055540FF015540FF005540FF001540FF000540FF000140FF000040FF56
:20001000000040FF000140FF000540FF001540FF005540FF015540FF055540FF155540FF4E
:00000001FF
Any clues what I'm doing wrong?
Make sure you have closed the file and very importantly that you reposition the file pointer to the start of the file and start reading chunks.
ihexf.seek(0,0)
OK - I worked out what was happening (I think!)
Existing code works on linux but not Windows.
On Windows I was seeing the following once the script finished:
#0000
#0008
#0010
#0018
------- End Of File ------
Traceback (most recent call last):
File "C:\Users\Nigel\SkyDrive\Files\python\intexhex2v.py", line 8, in <module>
rlen = int(rlen_s, 16)
ValueError: invalid literal for int() with base 16: ''`
Looks like things were messing up at the end of the file read.
Adding break after the End-Of-File print fixed everything
Thanks

Categories

Resources