'Serial' object has no attribute 'is_open' - python

I've been using code on my RPi2 to communicate to an RS485 Shield to drive various relays. I recently got a RPi3, and the code that has previously worked on the RPi2 has an error on the RPi3.
To begin with, I know that the uart (/dev/ttyAMA0) is "stolen" on the RPi3 for the bluetooth controller. Using this post, I reassigned the uart to the GPIO header so the RS485 shield should work as before. I give you this history, even though I suspect the problem is not with the hardware per se.
Here's the problem. When I execute the code below on the RPi3, I get an error:
Traceback (most recent call last):
File "serialtest.py", line 15, in <module>
if usart.is_open:
AttributeError: 'Serial' object has no attribute 'is_open'
Obviously, within the pySerial library, the serial object DOES have the 'is_open' attribute. Any suggestions on why this error is thrown? I haven't found any references to this specific error in web searches.
#!/usr/bin/env python
import serial
import time
import binascii
data = "55AA08060100024D5E77"
usart = serial.Serial ("/dev/ttyAMA0",19200)
usart.timeout = 2
message_bytes = data.decode("hex")
try:
usart.write(message_bytes)
#print usart.is_open # True for opened
if usart.is_open:
time.sleep(0.5)
size = usart.inWaiting()
if size:
data = usart.read(size)
print binascii.hexlify(data)
else:
print('no data')
else:
print('usart not open')
except IOError as e :
print("Failed to write to the port. ({})".format(e))

If you have an old version of pyserial on the Raspberry Pi, pyserial might not have the is_open, but isOpen() method instead. The isOpen() method was depricated in version 3.0 according to the documentation. You can check the pyserial version with serial.VERSION.

Related

Serial port permission error, and 'unexpected keyword argument' related to 'Systole' package when plotting raw PPG time series

I'm trying to assess if an Oximeter plugged in via USB is correctly collecting heart rate data. I am using the Systole package, and some pre-writtend code sourced here (Scroll down to Recording PPG Signal :Recording PPG Signal code
I am having 2 errors, the first is:SerialException: could not open port 'COM4': PermissionError(13, 'Access is denied.', None, 5)
And the second is:TypeError: plot_raw() got an unexpected keyword argument 'show_heart_rate'
The script I am trying to run:
from systole.recording import Oximeter
#Option for usin a simulated device, which I am not doing
from systole import serialSim
# Use a USB device
import serial
ser = serial.Serial("COM4") # Use this line for USB recording
#Plotting
oxi = Oximeter(serial=ser).setup().read(duration=10)
oxi.plot_raw(show_heart_rate=True, figsize=(13, 8))
Below is my desired output:
like I said in a comment the error 'COM4': PermissionError(13, 'Access is denied.', None, 5) means that the COM port is already taken by another program.
I think that the second error is because of this line:
oxi = Oximeter(serial=ser).setup().read(duration=10)
according to systole api documentation you are supposed to do:
# ................................
oxi = Oximeter(serial=ser)
oxi.setup()
oxi.read(duration=10)
# ................................
oxi.plot_raw(show_heart_rate=True, figsize=(13, 8))
systole api documentation
I'm sorry but are you sure you are pointing to the right file? this generation of errors occurs when the file is not reached because it does not exist.
also in the service documentation to write or read a file you should do:
import serial
s = serial.Serial('COM7')
res = s.read() # or s.write()
print(res)

UnetSocket send() returns a Nonetype object

I am trying out the python code specified in the UnetStack Handbook. While running tx.py and rx.py, UnetSocket object is created successfully as I print it out on the terminal, but the send() function sends Nonetype data at the receiver.
tx.py ===>>
from unetpy import UnetSocket
s = UnetSocket('localhost',1101)
print(s)
s.send('hellooo',31)
s.close()
rx.py =====>>>
from unetpy import UnetSocket
s = UnetSocket('localhost',1102)
rx = s.receive()
print('here ',rx)
print('from node : ',bytearray(rx.data).decode())
s.close()
First I run 2-node-network.groovy on the Simulator.
Then rx.py and next tx.py from the terminal.
Error at rx.py
Traceback (most recent call last):
File "rx.py", line 6, in
print('from node : ',bytearray(rx.data).decode())
AttributeError: 'NoneType' object has no attribute 'data'
O/p at tx.py
<unetpy.UnetSocket object at 0x7fe2909d4550>
I managed to reproduce your problem with the latest versions of unetpy + fjagepy. Seems to be a bug introduced in 1.7.1 release of fjagepy (I am assuming you have version 1.7.1 installed). Try:
pip install fjagepy==1.7.0
and then repeat your test to see if it works.
P.S. I have reported the problem to the maintainer for fjågepy and so hopefully we should have a fix in the next release. Until then you can use 1.7.0 release, if that works for you.

Python modbus communcation reading words on Mitsubishi PLC using ModbusTcpClient library

I am trying to communicate and read the words on a Mitsubishi PLC (Q06udeh) using the following code:
from pymodbus.client.sync import ModbusTcpClient
client = ModbusTcpClient('10.1.1.4',port=5007)
client.connect()
result = client.read_holding_registers(1,1)
print result
t = result.registers[0]
print t
I am getting following output:
None
Traceback (most recent call last):
File "C:\Users\serkan\Desktop\sasda.py", line 8, in <module>
t = result.registers[0]
AttributeError: 'NoneType' object has no attribute 'registers'
No matter how I changed the accessing words with different parameters no hope, I still have no success.
Please help.
Using modbus_tk
First of all, you will need to install modbus_tk package:
pip install modbus_tk
Then, try to run this sample code:
# General MODBUS includes
import modbus_tk
import modbus_tk.defines as cst
# TCP MODBUS includes
from modbus_tk import modbus_tcp
def main():
device_id = 1
master = modbus_tcp.TcpMaster("10.1.1.4")
master.set_timeout(3) #it's really optional
master.set_verbose(True) # this is optional too
data = master.execute(device_id, cst.READ_HOLDING_REGISTERS, 100, 1) #Usage: 100 is registry number and 1 means that size of data is 16bit (modbus protocol specification)
print "data ", data
print "data[0] ", data[0]
if __name__ == "__main__":
main()
You can find more examples here:
https://github.com/ljean/modbus-tk/tree/master/examples

AttributeError: module 'socket' has no attribute 'AF_PACKET'

I am working on building a packet sniffing program using Python, however I have hit a speed bump. For some reason I think socket has not imported properly, because I am getting the following message when my program is run: AttributeError: module 'socket' has no attribute 'AF_PACKET'
I am using OS X and Pycharm is my IDE and I am running the latest version of Python if that helps.
Anyways here is my complete program so far:
import struct
import textwrap
import socket
def main():
connection = socket.socket(socket.AF_PACKET, socket.SOCKET_RAW, socket.ntohs(3))
while True:
rawData, address = connection.recvfrom(65535)
reciever_mac, sender_mac, ethernetProtocol, data = ethernet_frame(rawData)
print('\nEthernet Frame: ')
print('Destination: {}, Source: {}, Protocol: {}'.format(reciever_mac, sender_mac, ethernetProtocol))
# Unpack ethernet frame
def ethernet_frame(data):
reciever_mac, sender_mac, protocol = struct.unpack('! 6s 6s H', data[:14])
return getMacAddress(reciever_mac), getMacAddress(sender_mac), socket.htons(socket), data[14:]
# Convert the Mac address from the jumbled up form from above into human readable format
def getMacAddress(bytesAddress):
bytesString = map('{:02x}'.format, bytesAddress)
macAddress = ':'.join(bytesString).upper()
return macAddress
main()
Thanks for any help in advance!
Actually, AF_PACKET doesn't work on OS X, it works on Linux.
AF_PACKET equivalent under Mac OS X (Darwin)
I ran into this issue on macOS 10.13.1, using Python 3.6.3 and this cool scapy fork that is compatible with python3.
I was using version 0.22 of that tool and as suggested in this issue downgrading to version 0.21 fixed this issue!
In case scapy is not a viable alternative, you could also try the pcap library as suggested in this post (although using python 2 seems to be necessary here).

How to consistently print data from serial in python

I'm trying to print the data that comes across the serial from an Arduino but I am unable to do so. My attempted code is this:
import serial
import time
s = serial.Serial('/dev/tty.usbmodemfd141',9600)
while 1:
if s.inWaiting():
val = s.readline(s.inWaiting())
print val
Yet after about 30 lines or so are spit out I get the following error message:
Traceback (most recent call last):
File "py_test.py", line 7, in <module>
val = s.readline(s.inWaiting())
File "build/bdist.macosx-10.8-intel/egg/serial/serialposix.py", line 460, in read
serial.serialutil.SerialException: device reports readiness to read but returned no data (device disconnected?)
I imagine I am using inWaiting incorrectly, but I do not see how to use it any other way.
Have you tried wrapping the readline in a try/except SerialException block? You could then just pass on the SerialException. It could be an issue with the serial driver reporting data in the receive buffer when there is not any, in which case your code will just keep running. Not a great fix, but it may lead you to the correct solution.
try:
s.read(s.inWaiting())
except serial.serialutil.SerialException:
pass # or maybe print s.inWaiting() to identify out how many chars the driver thinks there is
I believe you want to use function read(), not readline(). You are retrieving the number of characters in the buffer, they don't necessarily end with a new-line
Your loop becomes:
while 1:
if s.inWaiting():
val = s.read(s.inWaiting())
print val
if you want to simply print the data coming out of the serially connected device.you can
simply do it by using readline().
first open the port by using open() then you need to use the readline().
note:/dev/ttyUSB0 is a port number for linux and com0 is windows
here is the code
import serial
BAUDRATE = 115200
device_name = "ttyUSB0"
tty = device_name
s = serial.Serial("/dev/" + tty, baudrate=BAUDRATE)
s.open()
print s
try:
while True:
line = s.readline() //after this you can give the sleep time also as time.sleep(1) before that import time module.
print line
finally:
s.close()

Categories

Resources