Python27: Class to create pyserial connection, handle Error - python-2.7

I am reading data from a sensor via pyserial. The Sensor is connected via USB which can be differ from time to time, that's the reason I implemented a method which finds the right usb port.
My example code:
class Sensor:
'Class to implement a sensor'
#constructor of Vaisala with default setup of the serial connection
def __init__(self):
self.port = Sensor.read_port(self)
self.ser = serial.Serial(
port = Sensor.read_port(self),
baudrate =19200,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout = 2
)
#returns the port to which the sensor is connected
def read_port(self):
#method to determine port
This example works with my given sensor. My question now is how do I handle errors in this case.
For example, if there is no Sensor connected, the terminal will raise an SerialException because the method read_port() couldn't find a sensor. I tried to use in the read_port() a try case with exception but I wasn't successful at all. Could someone give me a hint how could I solve my problem?
I could also instead of using the constructor of the class, implementing another function called for example serial_connection(), which sets the port, baudrate and so on, but I think than I wouldn't need to use a class.
Thanks for any help!
Max

If there is no device the error will occur during the init. So:
class Sensor:
'Class to implement a sensor'
#constructor of Vaisala with default setup of the serial connection
def __init__(self):
try:
self.port = Sensor.read_port(self)
self.ser = serial.Serial(
port = Sensor.read_port(self),
baudrate =19200,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout = 2)
except SerialException:
import os
print "Error connecting"
os.exit(0)
#returns the port to which the sensor is connected
def read_port(self):
#method to determine port

Related

Store data that would be sent over the socket when it disconnects and manage it when socket reconnects

I have a problem where I need to store data on a disk when the TCP socket disconnects for whatever reason that would otherwise be sent over that socket and simultaneously check when a new connection is established and I can't find a solution to this.
What I have is:
def start_server_for_clients(srv, port):
client = None
try:
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(('', port))
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.listen(5)
print('Waiting for clients on port %s' % port)
while True:
client, address = srv.accept()
client.settimeout(10)
print('Connected client %s %s.' % (address[0], address[1]))
t = threading.Thread(target=handle_client, args=(client, address))
t.daemon = True
t.start()
except Exception as e:
print(e)
if client:
client.close()
handle_client is a function where data is processed and sent over the socket every second in a while loop. I need that processed data either way: connected or not and store it.
Now my logic to separate data processing and socket communication into different parts but where does it fit into threading once the connection is back up again because I would need to clear off the stored data first while simultaneously storing/buffering newly accumulated data and only then proceed to instant communication between sockets? Do I need to use select in this thread and spawn another one to for storing and recovering?

unable to post data to mosquitto broker continuously

I am trying to send data continuously from raspberry pi to a windows pc using MQTT,
I am trying to send 5 data to mosquitto, but the mosquitto seems to get only one value
coding in raspberry pi
import paho.mqtt.client as mqtt
client=mqtt.Client()
client.connect("192.168.0.104",1883,60)
for i in range(0,5):
data={"protocol":"mqtt"}
client.publish("/test",str(data))
coding at the broker to receive data is
import paho.mqtt.client as mqtt
print("attempting to connect...")
def on_connect(client, userdata, flags, rc):
if(rc==0):
print("connection successful broker linked")
elif(rc==1):
print("connection refused - incorrect protocol version")
elif(rc==2):
print("connection refused - invalid client identifier")
elif(rc==3):
print("connection refused- server unavailable")
elif(rc==4):
print("connection refused- bad username or password")
elif(rc==5):
print("connection refused- not authorised")
else:
print("currently unused")
client.subscribe("s/test")
def on_message(client, userdata, msg):
data=eval(msg.payload)
print(data)
client = mqtt.Client()
client.connect("localhost",1883,60)
client.on_connect = on_connect
client.on_message = on_message
client.loop_forever()
Have you thought about following the answer I posted here?
https://github.com/eclipse/mosquitto/issues/972
You need to make sure the network loop runs for the publishing client as well a the subscriber. The network loop actually handles sending the messages.
The following is the simplest modification to your code.
import paho.mqtt.client as mqtt
client=mqtt.Client()
client.connect("192.168.0.104",1883,60)
for i in range(0,5):
data={"protocol":"mqtt"}
client.publish("/test",str(data))
client.loop()

sending command to my Camera via usb port RAS PI (python)

I'm trying to send command to my Flir camera TAU2 using USB and normally i should receive a respond from it, so what i'm doing first is that i'm configuring my serial port
and then i'm sending my command via the serial port:
and then listening to the serial for a respond :
this is a part of my code:
def __init__(self):
self.serCam = serial.Serial(port='/dev/ttyUSB0',
baudrate=9600,
parity=serial.PARITY_NONE,
stopbits=1,
xonxoff=False
)
def close_connection(self):
if self.serCam.isOpen():
self.serCam.close()
def serial_Read(self):
while self.serCam.inWaiting():
try:
self.state=serCam.readline()
return state
print state
except:
pass
def control(self):
self.len= self.serCam.write(serial.to_bytes([0x6E,0x00,0x00,0x0B,
0x00,0x00,0x2F,0x4A,0x00,
0x00,0x00]))
print ('commande envoye' )
return len
i don't receive anything from my camera, do you have any idea please from where it can be ?

pysftp gives pysftp.exceptions.ConnectionException: (host, port) with no details on it

I'm trying to connect to sftp server with pysftp library. Here is my code:
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection("sftp://host", "login", "password", cnopts=cnopts) as sftp:
sftp.listdir()
It gives me exception:
pysftp.exceptions.ConnectionException: ('host', port)
But I have no clue what this exception means and what the problem is.
You don't have much explanation because this library has bugs. See the source code on BitBucket.
The ConnectionException class is not well implemented:
class ConnectionException(Exception):
"""Exception raised for connection problems
Attributes:
message -- explanation of the error
"""
def __init__(self, host, port):
# Call the base class constructor with the parameters it needs
Exception.__init__(self, host, port)
self.message = 'Could not connect to host:port. %s:%s'
As you can see, the format 'Could not connect to host:port. %s:%s' is not filled with the host and port values.
However, the name of the exception is clear: you have a connection error.
The details of the error are, unfortunately, lost:
def _start_transport(self, host, port):
'''start the transport and set the ciphers if specified.'''
try:
self._transport = paramiko.Transport((host, port))
# Set security ciphers if set
if self._cnopts.ciphers is not None:
ciphers = self._cnopts.ciphers
self._transport.get_security_options().ciphers = ciphers
except (AttributeError, socket.gaierror):
# couldn't connect
raise ConnectionException(host, port)
You can try to get the last error (not sure):
import sys
sys.exc_info()
note: I suggest you to use another library (for instance Paramiko).

Receive code not working XBee python

Configured two xbee pro s2b using X-CTU, one as coordinator and other as router, API=2, baudrate as 9600. The sender code (coordinator) is as below:
import time
from xbee import XBee
import serial
PORT = "/dev/ttyUSB0"
BAUDRATE = 9600
#open serial port
sender_port = serial.Serial(PORT, BAUDRATE)
print "serial port object>>>", sender_port
#xbee object API=2
sender = XBee(sender_port,escaped=True)
#address of the remote xbee to which data is to sent
ADDRESS = "\x00\x13\xA2\x00\x40\xD9\x6F\xE5"
#send data using the tx_long_addr
while True:
try:
print "sending data..."
sender.tx_long_addr(frame_id='A', dest_addr=ADDRESS, data="hello")
time.sleep(1)
except KeyboardInterrupt:
break
sender.halt()
sender_port.close()
below is the receiver code (router)
import time
from xbee import XBee
import serial
PORT = "/dev/ttyUSB1"
BAUDRATE = 9600
def byte2hex(byteStr):
return ''.join(["%02X" % ord(x) for x in byteStr]).strip()
def decodereceivedFrame(data):
source_address = byte2hex(data['source_addr'])
xbee_id = data['id']
rf_data = data['rf_data']
options = byte2hex(data['options'])
return [source_address, xbee_id, rf_data, options]
#open serial port at receiving end
remote = serial.Serial(PORT, BAUDRATE)
#xbee object API=2
remote_xbee = XBee(remote, escaped=True)
while True:
try:
print "yes i m here"
data = remote_xbee.wait_read_frame()
print "data >>>", data
decoderdata = decodereceivedFrame(data)
print "data received<<<<", decoderdata
except KeyboardInterrupt:
break
remote_xbee.halt()
remote.close()
But on executing the receiver code, nothing happens, it does not print the received message. On X-CTU frames are being transmitted and received without any errors, am i doing something wrong in the code. Please guide .
Thank you
Found the issue, my fault----
sender = ZigBee(sender_port, escaped=True)
sender.send('tx', frame_id='A', dest_addr="\x5E\x71", dest_addr_long="\x00\x13\xA2\x00\x40\xD9\x6F\xE5", data="Hello")
Works now ..!!! :)