Receive code not working XBee python - python-2.7

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 ..!!! :)

Related

Pymongo on raspberry pi 3 wait too much to raise an error

I have an issue with pymongo on raspberry pi 3. The thing is when I run the script normally (I mean, I have internet connection and database connection, so there is not problem writing on database) I disconnect the wi-fi or ethernet from the Raspberry in order to get an error and handle it later but, when I disconnect the internet the script stops in the "insert_one" command of pymongo, like waiting until it gets internet connection again... so... the error raised several minutes later, like 25 minutes and that is not good for me, because I need to get the error inmediatly, so I can do some savings on a csv file.
from pymongo import MongoClient
from pymongo import errors
from pymongo import client_options
from pymongo import settings
url = 'emaweather.hopto.org'
port = 27017
client_options.ClientOptions.server_selection_timeout = 1
try:
client = MongoClient(url, port)
db = client['weather-mongo']
print('Cliente: ' ,client)
print('DB: ', db)
except errors.ConnectionFailure as e:
print('Error: ', e)
def main():
while True:
try:
__readCSV()
utc_now = pytz.utc.localize(datetime.datetime.utcnow())
pst_now = utc_now.astimezone(pytz.timezone("America/Asuncion"))
dateNowIsoFormat = pst_now.isoformat()
print (dateNowIsoFormat)
temperature,pressure,humidity = readBME280All()
dbDataTemp = temperature
print (dbDataTemp)
dbDataHum = round(humidity,2)
print (dbDataHum)
dbDataPress = round(pressure,2)
print (dbDataPress)
dbData = {"date": dateNowIsoFormat, "temp": dbDataTemp, "hum": dbDataHum, "press": dbDataPress}
db.data.insert_one(dbData)
print('Writed on MongoDB')
time.sleep(5)
except errors.PyMongoError as error:
print (error)
if __name__=="__main__":
main()

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 ?

Serial.serialutil.serialException: Attempting to use a port that is not open

I am using Python code to control my mini GRBL CNC machine that connected to Laptop with windows operating system over MQTT Protocol,
Here is the code.
import paho.mqtt.client as mqtt
import time
import serial
# Open grbl serial port
s = serial.Serial('COM5',115200)
# Wake up grbl
s.write("\r\n\r\n")
time.sleep(2) # Wait for grbl to initialize
s.flushInput() # Flush startup text in serial input
f = """
O1000
T1 M6
(Linear / Feed - Absolute)
G0 G90 G40 G21 G17 G94 G80
G54 X-75 Y-75 S500 M3 (Position 6)
G43 Z100 H1
Z5
G1 Z-20 F100
X-40 (Position 1)
Y40 M8 (Position 2)
X40 (Position 3)
Y-40 (Position 4)
X-75 (Position 5)
Y-75 (Position 6)
G0 Z100
M30
"""
# Runs when the client receives a CONNACK connection acknowledgement.
def on_connect(client, userdata, flags, result_code):
print "Successful connection."
# Subscribe to your topics here.
client.subscribe("hi")
# Runs when a message is PUBLISHed from the broker. Any messages you receive
# will run this callback.
def on_message(client, userdata, message):
if message.topic == "hi":
if message.payload == "run":
# Stream g-code to grbl
for line in f:
l = line.strip() # Strip all EOL characters for consistency
print 'Sending: ' + l,
s.write(l + '\n') # Send g-code block to grbl
grbl_out = s.readline() # Wait for grbl response with carriage return
print ' : ' + grbl_out.strip()
# Close file and serial
s.close()
# You could do something here if you wanted to.
elif message.payload == "STOP":
# Received "STOP". Do the corresponding thing here.
# Close file and serial
s.close()
print "CNC is stopped."
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("iot.eclipse.org", 1883, 60)
client.loop_forever()
But when i run it i got
successful connection
and then,
serial.serialutil.serialException: Attempting to use a port that is not open ,Although the CNC works fine from GUI.At first i thought that the opening GUI caused this error, but even when i closed it i am still having the same issue.So, maybe i am facing this problem because of MQTT, maybe it's a security issue because when i run that python code but without using PAHO MQTT protocol every things works fine, the same port opens and CNC works.
Isn't it supposed to work until i send "run" because the serial opening order comes after receiving the message?
You are closing the serial port when ever you get a message delivered. That means you can only ever process one message.

Python UDP networking socket.error: [Errno 10049]

I am trying to establish a simple UDP connection using Python code, between 2 PCs through internet.
Code run on PC_1:
import socket
import time
HOST = "ip_address_of_PC2"
PORT = 5555
data = "Hello World!!"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
s.sendto(data, (HOST, PORT))
print "sent: ",data
time.sleep(1)
code run on the 2nd PC:
import socket
HOST = "ip_address_of_PC1"
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
while True:
print s.recv(30)
While running the code on 2nd PC am getting following error message:
return getattr(self._sock,name)(*args)
socket.error: [Errno 10049] The requested address is not valid in its context
change print s.recv(30) to:
data, addr = s.recvfrom(30)
print data
and in the 2nd PC code, the HOST variable needs the value of the 2nd PC ip, not the first one:
HOST = "ip_address_of_PC2"
Code run on PC1:
import socket
import time
HOST = "public ip_address_of_PC2"
PORT = 5555
data = "Hello World!!"
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
s.sendto(data, (HOST, PORT))
print "sent: ",data
time.sleep(1)
Code run on PC2:
import socket
HOST = "private ip_address_of_PC2"
PORT = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST,PORT))
while True:
print s.recv(30)

Python27: Class to create pyserial connection, handle Error

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