I would like to create a Python programm like a terminal to send some request with Pyserial.
But when I send a request like "dataid 60000 get value" it show me an error message like :
TypeError: unicode strings are not supported, please encode to bytes: 'dataid 60000 get value'
I tried to use .encode but no result..
See below my code :
#Modules
from base64 import encode
import serial
port = "COM5"
baud = 115200
#Serial port configuration
com = serial.Serial(port, baud, timeout=1)
if com.isOpen():
print(com.name + ' is open...')
#Print output
while True:
cmd = input("Enter command or 'exit':")
if cmd == 'exit':
com.close()
exit()
else:
com.write(cmd)
out = com.read()
print('Receiving...'+out)
Thanks in advance ! :)
To send command over serial/console port, use:
com.write(cmd.encode("utf-8"))
or
com.write(b"string")
This encodes your input to bytes.
Related
I've a displacemente measurement and I want that Python give me the values, but I do not know, How receive the data.I use this code, and give me the following error - TypeError: can't concat bytes to str.
`import serial
port = "COM3"
baud = 115200
ser = serial.Serial(port, baud, timeout=1)
# open the serial port
if ser.isOpen():
print(ser.name + ' is open...')
while True:
cmd = input("Enter command or 'exit':")
# for Python 2
# cmd = input("Enter command or 'exit':")
# for Python 3
if cmd == 'exit':
ser.close()
exit()
else:
ser.write(cmd.encode('ascii','strict')+'\r\n')
out = ser.read()
print('Receiving...'+out)
`
write(... does only accept binary data.
Documentation pySerial API
write(data)
Write the bytes data to the port. This should be of type bytes (or compatible such as bytearray or memoryview). Unicode strings must be encoded (e.g.'hello'.encode('utf-8').
I have Python 3.6.1 and PySerial Installed. I am trying the
I am able to get the list of comports connected. I now want to be able to send data to the COM port and receive responses back. How can I do that? I am not sure of the command to try next.
Code:
import serial.tools.list_ports as port_list
ports = list(port_list.comports())
for p in ports:
print (p)
Output:
COM7 - Prolific USB-to-Serial Comm Port (COM7)
COM1 - Communications Port (COM1)
I see from the PySerial Documentation that the way to open a COM Port is as below:
import serial
>>> ser = serial.Serial('/dev/ttyUSB0') # open serial port
>>> print(ser.name) # check which port was really used
>>> ser.write(b'hello') # write a string
>>> ser.close() # close port
I am running on Windows and I get an error for the following line:
ser = serial.Serial('/dev/ttyUSB0')
This is because '/dev/ttyUSB0' makes no sense in Windows. What can I do in Windows?
This could be what you want. I'll have a look at the docs on writing.
In windows use COM1 and COM2 etc without /dev/tty/ as that is for unix based systems. To read just use s.read() which waits for data, to write use s.write().
import serial
s = serial.Serial('COM7')
res = s.read()
print(res)
you may need to decode in to get integer values if thats whats being sent.
On Windows, you need to install pyserial by running
pip install pyserial
then your code would be
import serial
import time
serialPort = serial.Serial(
port="COM4", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE
)
serialString = "" # Used to hold data coming over UART
while 1:
# Wait until there is data waiting in the serial buffer
if serialPort.in_waiting > 0:
# Read data out of the buffer until a carraige return / new line is found
serialString = serialPort.readline()
# Print the contents of the serial data
try:
print(serialString.decode("Ascii"))
except:
pass
to write data to the port use the following method
serialPort.write(b"Hi How are you \r\n")
note:b"" indicate that you are sending bytes
I have a device (Pololu Wixel) that I'm trying to communicate with using a serial connection over USB. Hyperterminal works fine but I'm trying to use Python for more flexibility. I can send commands to the device, but when I try to receive all I get is the command I just sent. However, if I open Hyperterminal, I'll receive the reply there to the command sent from the script. My code is below. I'm at a bit of a loss and it seems like this should be fairly straightforward. I appreciate any help.
import serial
import time
'''
Go through 256 COM ports and try to open them.
'ser' will be the highest port number. Fix this later.
'''
for i in range(256):
currentPort = "COM" + str(i+1)
try:
ser = serial.Serial(currentPort,baudrate=115200,timeout=5)
print("Success!!")
print(ser.name)
except:
pass
print(ser.isOpen())
str = "batt" #Command to request battery levels.
ser.write(str.encode())
x = ser.inWaiting()
print(x)
while ser.inWaiting() > 0:
out = ser.readline()
print(out.decode())
Add a break after finding an active port,
Try passing a different eol value to readline(), "\r" or "\r\n".
esp8266 and cp2102 don't work! Why?
import serial
sp="/dev/ttyUSB0"
port = serial.Serial(sp)
while True:
port.write("AT+RST")
rcv = port.read(10)
print rcv
I pressed "AT+RST"[Enter] and don't have "READY" after it.
Make sure you include CRLF (\r\n) characters at the end of your command. I lost a day messing with this before I figured that out. I got the local echo back of the command but since I never sent a \r\n I would not get any more data. Here is what works for me as a basic terminal in Python using pyserial:
import serial
import time
ser = serial.Serial('/dev/tty.usbserial-A8004xaO', 115200, timeout=2.5)
while True:
cmd = raw_input("> ");
ser.write(cmd + "\r\n")
ret = ser.read(len(cmd)) # eat echo
time.sleep( 0.2 )
while ( ser.inWaiting() ):
ret = ser.readline().rstrip()
print ret
You aren't setting a baud rate when opening the serial port. The default is probably not appropriate for the ESP8266.
i tried to do client and server and look what i do
#Server
import socket
Host=''
Port=305
OK=socket.socket()
OK.bind((Host,Port))
OK.listn(1)
OK.accept()
and another one for client
#Client
impot socket
Host='192.168.1.4'
Port=305
OK=socket.socket()
OK.connect((Host,Port))
First thing : for now every thing is ok but i want when client connect to server :
server print "Hello Admin" in client screen
second thing : i want make like input command ! like
COM=raw_input('enter you command system:')
then client enter dir for example then server print the result in client screen
Look here, this is a simple echo server written in Python.
http://ilab.cs.byu.edu/python/socket/echoserver.html
When you create a connection, the story isn't over. Now it's time to send data over the connection. Create a simple "protocol" (*) and use it to transfer data from client to server and/or back. One simple example is a textual protocol of commands separated by newlines - this is similar to what HTTP does.
(*) Protocol: an agreement between two parties on the format of their communication.
I think you might want to do something like this:
client, addr = OK.accept()
client.send("Hello Admin")
And then use
data = client.recv(1024)
to get data from the client.
If you want to get command input from the client, you just need to execute the commands the client sends and send the output back back to the client.
from commands import getoutput
client.send(getoutput(client.recv(1024)))
Thats about the easiest solution possible.
For Client:
import os
import sys
impot socket
Host=raw_input ("Please enter ip : ")
Port=raw_input ("please Enter port :")
OK=socket.socket()
OK.connect((Host,Port))
print " Enter Command")
cmd = raw_input()
os.system(cmd)
I think that your codes has an issue:
you seem to have OK = socket.socket(), but I think it should be:
OK = socket.socket(socket.AF_INET, socket.STREAM), which would help if your making a connection. And your server has a problem: OK.listn(1) should be OK.listen(1). And, don't forget about send() and recv().
#Client
import socket
Host='192.168.1.4'
Port=305
OK=socket.socket(socket.AF_INET, socket.STREAM)
OK.connect((Host,Port))
while True:
com = raw_input("Enter your command: ")
OK.send(com)
data = OK.recv(5000) #Change the buffer if you need to, I have it setup to run 5000
print "Received:\n" + data
which should work for the client
#Server
import socket
import os
Host=''
Port=305
OK=socket.socket(socket.AF_INET, socket.STREAM)
OK.bind((Host,Port))
OK.listen(1)
conn, addr = OK.accept()
while True:
data = conn.recv(2048) #Change the buffer if needed
if data == "":
break
r = os.system(data)
conn.send(str(r)) #Note this will send 0 or 1, 0 = ran, 1 = error
Note: These fixes would work for Windows, I don't know about Unix systems.*