Serial communication between two Linux running laptops using Python - python

I'm trying to send and receive messages between two Linux running laptops via serial communication using Python. The receiver system must see the message "waiting for the message" until it receives the message from the sender. I was searching for sample code to test this. The sample code I have for the sender is as follows:
import serial
com = serial.Serial('/dev/ttyUSB0',baudrate=115200)
com.write('2')
com.close()
But I cannot figure out what to put for the receiver code, where it will display a message on the receivers display as "waiting" and once the message is received it should display "received".
Does anyone have a sample code to work this out?

Reading a serial device is as easy as reading a file:
import serial
com = serial.Serial('/dev/ttyUSB0',baudrate=115200)
print "Waiting for message"
char = com.read(1)
print char
com.close()

Related

Python, Data Received from RS232 COM1 port is returning b'\x05' and b'\x04'

I am doing an instrument integration where the instrument name is Horiba ES60. I am using an RS232 port for communicating for PC and instrument.
I have tested the PC and instrument connection through the Advance Serial Port logger and am getting the monitor result.
I have confirmed that the instrument setting and my script setting are the same.
I have written a simple script in python to read the port data. below is the script.
import time
import serial
sSerialPort = serial.Serial(port = "COM1", baudrate=9600,
bytesize=8, timeout=1, stopbits=serial.STOPBITS_ONE)
sSerialString = "" # Used to hold data coming over UART
print("Connected to : ",sSerialPort.name)
while(True):
# Wait until there is data waiting in the serial buffer
if(sSerialPort.in_waiting > 0):
# Read data out of the buffer until a carraige return / new line is found
sSerialString = sSerialPort.readline()
# Print the contents of the serial data
print(sSerialString)
Output:
b'\x05'
b'\x04'
The expected output is different and I am getting the above one.
Can someone please help to understand what's going wrong?
how to deal with port data in python.

Output incoming UDP data to new terminals with Python3.7 on Windows

I have a client/server UDP program running on python3.7 on Windows. After establishing a connection, the client listens for incoming data from the server. Each time a client receives data/message (from server), a new terminal should open displaying that message and the client should be able to respond to that message on that terminal. So if a client receives 4 incoming messages from the server, 4 terminals should open with each one displaying their corresponding message.
As of now, my program works just fine but on one terminal.
Could someone please help me? I was able to make a new terminal open for each incoming message with os.system("start cmd") but that's as far as I was able to get. These terminal instances just point to the project's directory with nothing running on them and I understand why, this is just as much 'progress' as I was able to make.
Here is the sample of my code I am referring to :
def clientListen():
while 1:
try:
data, server = client_listen_socket.recvfrom(1024)
if data:
reply = pickle.loads(data)
if str(reply) == 'Connection Successful':
print('\n ~~~ INCOMING MESSAGE FROM ' + str(serverName) + ' ~~~\n') #REPLACE->localhost
print(reply)
clientServerConnectionOutput()
else:
# *OPEN TERMINAL DISPLAYING REPLY*
print('\n ~~~ INCOMING MESSAGE FROM ' + str(serverName) + ' ~~~\n') #REPLACE->localhost
print(reply)
except socket.error:
pass
So each time it receives data, (if data), under the else clause, this is where I want a new terminal to open displaying the reply.
Any help would be greatly appreciated!
Thanks

Python sockets recv() issue

I have a socket server running on an Arduino board and am trying to control it via a Python script. Using the basic example socket documentation, I have this:
import socket
import sys
TCP_IP = '192.168.254.100'
TCP_PORT = 5012
BUFFER_SIZE = 1024
MESSAGE = "Status"
# Create a TCP/IP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
# data = s.recv(BUFFER_SIZE)
# print (data)
s.close()
sys.exit()
My script works fine when I comment out the lines to receive the response of the server. However, if I attempt to read the response, my server and python script hangs.
On the server side, here is a snippet of what the code looks like:
void loop() {
// listen for incoming clients
client = server.available();
if (client){
Serial.println("Client connected");
while (client.connected()){
// Read the incoming TCP command
String command = ReadTCPCommand(&client);
// Debugging echo command to serial
command.trim();
Serial.println(command);
// Debugging echo command back to client
client.println(command);
// Phrase the command
PhraseTCPCommand(&client, &command);
}
// Stop the client
client.stop();
Serial.println("Client disconnected");
}
}
The library I am utilising for the server is the Arduino WiFi library.
The function PhraseTCPCommand, takes the command and triggers external events with the GPIO pins of the board. This action is performed fine by the Python script when the recv() is commented out. The response string sent from the server is terminated with a newline and carriage return. Could that be causing issues?
Additionally, I am able to connect and receive responses from the server with no issues using either telnet, netcat or PuTTY, which leads me to believe it's something to do with the way my Python script attempts to read the response from the server.
The response string sent from the server is terminated with a newline
and carriage return. Could that be causing issues?
No, what is causing the issue is possibly that the command MESSAGE is not terminated with a newline and the function ReadTCPCommand() expects one. Change to:
MESSAGE = "Status\n"
The issue here could be that your message has not been fully sent, and reflects a common misunderstanding of socket programming. Low level calls such as send do not promise to send the full message. Instead the caller must check the number of bytes actually sent (from the return value) and continue to iteratively call the function until the full message is sent.
In general, a bare send call without such iteration is a mistake.
Python does provides a higher level function socket.sendall however that will perform this job for you.

How to use socat to transfer serial commands in a script over TCP/IP?

I have a web application that will constantly post some queries and get replies from a device through the serial port on Raspberry Pi. Like this:
#cherrypy.expose
def login (self, **data):
passcode = data.get("passcode", None)
print "logging in using passcode %s"%passcode ,type(passcode)
import serial
import time
#open connection
serialport=serial.Serial ("/dev/ttyAMA0", 9600, timeout=0.5)
#write in user sign in code
serialport.write("\x03LI%s\x0D"%passcode)
reply=serialport.readlines(1)
print reply, type(reply)
#check if log in success
if not "00" in reply[0]:
if "FE" in reply[0]:
state="engineer"
else:
state="user"
else:
state="none"
print state
time.sleep(1)
return state
Currently I am using direct 3 wires (gnd, txd, rxd) from Raspberry Pi to the device's (gnd, rxd, txd). The serial port of Raspberry Pi is /dev/ttyAMA0 and say the device has an IP of 10.0.0.55. i could send netcat command one at a time like this:
nc 10.0.0.55 1001
^CLI1234^M //this is an example of the serial command sent to the device from Raspberry Pi terminal
How should i do it with **socat**? I don't want to change the script but just to manipulate some configuration in socat (or something else) that would forward the command to the device's IP. I want to get rid of the 3 wires connected to R-Pi UART. i hardly find examples on socat that would suit this requirement (or may be i don't know what keyword i should use). Please enlighten me :) Thanks a lot!

How to monitor a bluetooth stream using Python?

Can someone show me the simplest way to just print received bluetooth stream?
I need to verify that a computer receives data that a mobile phone sends via bluetooth.
I have something lik this:
import serial
import time
import sys
port = serial.Serial('COM6', 19200, timeout=2)
while True:
line = port.readline()
line = line.split()
print >>output, line
output.flush()
But I am not sure if it is correct for bluetooth.
PyBluez should be enough for WindowsXP, provided you have a compatible dongle.
It has examples for what you need.

Categories