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 ?
Related
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()
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.
Well this is a code for the "host" of a two way chatroom. The client's code is very similar. I have tried to compile both of them into an exe with various ways and none of them had a nice result. The exe simply doesnt run. I got all modules, i've tried many codes( many adding the dll files etc into the program too.) I try to compile it as a pyw since it has graphics inside. There is one more py file that has some more info that those two (client and host) pyw files get somehow, but they can still run without it with python.exe . I dont know how can I help you understand so let me know if you got any questions. Thanks in advance.
This is the host in python 2.7 code:
import thread
from ChatFns import *
#---------------------------------------------------#
#---------INITIALIZE CONNECTION VARIABLES-----------#
#---------------------------------------------------#
#Initiate socket and bind port to host PC
WindowTitle = 'Chat - Host User'
s = socket(AF_INET, SOCK_STREAM)
HOST = gethostname()
PORT = 8000
conn = ''
s.bind((HOST, PORT))
#---------------------------------------------------#
#------------------ MOUSE EVENTS -------------------#
#---------------------------------------------------#
def ClickAction():
#Write message to chat window
EntryText = FilteredMessage(EntryBox.get("0.0",END))
LoadMyEntry(ChatLog, EntryText)
#Scroll to the bottom of chat windows
ChatLog.yview(END)
#Erace previous message in Entry Box
EntryBox.delete("0.0",END)
#Send my mesage to all others
conn.sendall(EntryText)
#---------------------------------------------------#
#----------------- KEYBOARD EVENTS -----------------#
#---------------------------------------------------#
def PressAction(event):
EntryBox.config(state=NORMAL)
ClickAction()
def DisableEntry(event):
EntryBox.config(state=DISABLED)
#---------------------------------------------------#
#-----------------GRAPHICS MANAGEMENT---------------#
#---------------------------------------------------#
#Create a window
base = Tk()
base.title(WindowTitle)
base.geometry("400x470")
base.resizable(width=FALSE, height=FALSE)
#Create a Chat window
ChatLog = Text(base, bd=0, bg="white", height="8", width="50", font="Arial",)
ChatLog.insert(END, "Waiting for client user to connect...\n")
ChatLog.config(state=DISABLED)
#Bind a scrollbar to the Chat window
scrollbar = Scrollbar(base, command=ChatLog.yview, cursor="heart")
ChatLog['yscrollcommand'] = scrollbar.set
#Create the Button to send message
SendButton = Button(base, font=30, text="Send", width="12", height=5,
bd=0, bg="#E6E6E6", activebackground="#FA5858",
command=ClickAction)
#Create the box to enter message
EntryBox = Text(base, bd=0, bg="white",width="29", height="5", font="Arial")
EntryBox.bind("<Return>", DisableEntry)
EntryBox.bind("<KeyRelease-Return>", PressAction)
#Place all components on the screen
scrollbar.place(x=376,y=6, height=386)
ChatLog.place(x=6,y=6, height=386, width=370)
EntryBox.place(x=128, y=401, height=60, width=265)
SendButton.place(x=6, y=401, height=60)
#---------------------------------------------------#
#----------------CONNECTION MANAGEMENT--------------#
#---------------------------------------------------#
def GetConnected():
s.listen(1)
global conn
conn, addr = s.accept()
LoadConnectionInfo(ChatLog, 'Connected with: ' + str(addr) + '\n---------------------------------------------------------------')
while 1:
try:
data = conn.recv(1024)
LoadOtherEntry(ChatLog, data)
if base.focus_get() == None:
FlashMyWindow(WindowTitle)
playsound('notif.wav')
except:
LoadConnectionInfo(ChatLog, '\n [ User disconnected. ]\n [ Waiting for them to connect...] \n ')
GetConnected()
conn.close()
thread.start_new_thread(GetConnected,())
base.mainloop()
Python is an interpreted language, it's not supposed to be compiled into an .exe file. However, there are tools like http://py2exe.org/ that create an executable file with Python, strapping the interpreter itself into the file.
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 ..!!! :)
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