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

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.

Related

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 ?

How to send events from siddhi event simulator to android siddhi app

I have a siddhi cep application running on Android. Now I want to send events from event simulator from stream processing editor to android app via a socket connection. Till now I have been successful in making android server socket which listens to python client simulator made by me. But to ease the process, is it possible that I can use event simulator to send events to android siddhi app?
I was wondering if I can change some configurations such that event simulator sends events to android socket, so I looked at setting in deployment.yaml file
but the sending configurations are defined for HTTP
senderConfigurations:
-
id: "http-sender"
# Configuration used for the databridge communication
databridge.config:
# No of worker threads to consume events
# THIS IS A MANDATORY FIELD
workerThreads: 10
# Maximum amount of messages that can be queued internally in MB
# THIS IS A MANDATORY FIELD
maxEventBufferCapacity: 10000000
# Queue size; the maximum number of events that can be stored in the queue
# THIS IS A MANDATORY FIELD
eventBufferSize: 2000
# Keystore file path
# THIS IS A MANDATORY FIELD
keyStoreLocation : ${sys:carbon.home}/resources/security/wso2carbon.jks
# Keystore password
# THIS IS A MANDATORY FIELD
keyStorePassword : wso2carbon
# Session Timeout value in mins
# THIS IS A MANDATORY FIELD
clientTimeoutMin: 30
# Data receiver configurations
# THIS IS A MANDATO
Thanks in advance. If you need some more details please let me know
Edit 1
I actually found a way around to do it but it's having some issues. So basically I redirected output sink of event generator to port such that sink has all the data streams. The code for Stream Processor Studio editor is
#App:name("PatternMatching")
#App:description('Identify event patterns based on the order of event arrival')
define stream RoomTemperatureStream(roomNo string, temp double);
#sink(type="tcp", url='tcp://localhost:5001/abc', sync='false', tcp.no.delay='true', keep.alive='true', worker.threads="10", #map(type='text'))
define stream RoomTemperatureAlertStream(roomNo string, initialTemp double, finalTemp double);
--Capture a pattern where the temperature of a room increases by 5 degrees within 2 minutes
#info(name='query1')
from RoomTemperatureStream
select e1.roomNo, e1.temp as initialTemp, e2.temp as finalTemp
insert into RoomTemperatureAlertStream;
it sends the streams as text to python server, which needs to be started first, code of which is
#!/usr/bin/env python
# Author : Amarjit Singh
import pickle
import socket
import pandas
from pandas import json
if __name__ == "__main__":
# ------------------ create a socket object-----------------------#
try:
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
serversocket.close()
print("socket creation failed with error %s" % (err))
except KeyboardInterrupt:
serversocket.close()
print("KeyboardInterrupt - but server socket was closed ")
host = "127.0.0.1"
Server_port = 5001
# ------------------ binding to the port -----------------------#
try:
serversocket.bind((host, Server_port))
serversocket.listen(50) # queue up to 5 requests
print("\n Server has started and waiting for connection request ..... ")
# bind to the port
while True: # extra while is created so that server runs even if there is no data
running = True
clientsocket, addr = serversocket.accept() # accept a connection from client
print("Got a connection from Server%s" % str(addr)) # show connection success message
while running:
receivedData = clientsocket.recv(2048)
# json = receivedData
if receivedData:
print(receivedData)
print(receivedData[0])
print(receivedData[1])
print(receivedData[2])
# roomNo = str(receivedData[0])
# temp = int(client_tuple[1]) # from unicode to int
#
# print(" roomNo = %d: UUID = %s temp = %d" % (roomNo, temp))
except socket.error as err:
serversocket.close()
print("socket creation failed with error %s" % (err))
except KeyboardInterrupt:
serversocket.close()
print("KeyboardInterrupt - but server socket was closed ")
Initially, I was sending json data from simulator, but pickle.loads and json.loads did not work. but the problem with text is that data is displayed as
b'\x02\x00\x00\x00t\x00\x00\x003bed14d31-6697-4a74-8a3f-30dc012914ad-localhost:5001\x00\x00\x00\x03abc\x00\x00\x002roomNo:"X0ZYp",\ninitialTemp:15.97,\nfinalTemp:17.22'
b'\x02\x00\x00\x00t\x00\x00\x003bed14d31-6697-4a74-8a3f-30dc012914ad-localhost:5001\x00\x00\x00\x03abc\x00\x00\x002roomNo:"2X951",\ninitialTemp:13.42,\nfinalTemp:10.76'
b'\x02\x00\x00\x00t\x00\x00\x003bed14d31-6697-4a74-8a3f-30dc012914ad-localhost:5001\x00\x00\x00\x03abc\x00\x00\x002roomNo:"PUaJA",\ninitialTemp:15.46,\nfinalTemp:16.26'
b'\x02\x00\x00\x00t\x00\x00\x003bed14d31-6697-4a74-8a3f-30dc012914ad-localhost:5001\x00\x00\x00\x03abc\x00\x00\x002roomNo:"pnz0i",\ninitialTemp:10.42,\nfinalTemp:15.82'
how to remove this extra data?
Siddhi has a WebSocket connector[1] and it's still WIP. Using this dependency you will be able to add a WebSocket sink to your app and send events from that.
Unfortunately, you cannot directly send events from Stream Processor[2] Studio/Editor but if you have an app running in Stream Processor Editor and if it has a WebSocket sink then you can send events to App's sink stream from the Simulator which will intern send that message via WebSocket to the Siddhi app in android.
You can only simulate apps running inside the editor via the Event Simulator or simulate apps deployed in Stream Processor worker nodes via Event Simulator API.
[1]https://github.com/wso2-extensions/siddhi-io-websocket
[2]https://wso2.com/analytics

Python Client is unable to receive data sent from Python Server

I am trying to send some data from my python client to python server
I have followed this link
My python client code is as follows
#Socket client example in python
import socket #for sockets
import sys #for exit
#create an INET, STREAMing socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
print 'Failed to create socket'
sys.exit()
print 'Socket Created'
host = '10.4.1.25';
port = 80;
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Exiting'
sys.exit()
#Connect to remote server
s.connect((host , port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
message = "16973"
try :
#Set the whole string
s.sendall(message)
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
print 'Message send successfully'
#Now receive data
reply = s.recv(4096)
print reply
the python server code is
import socket
import sys
HOST = '' # Symbolic name meaning all available interfaces
PORT = 80 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
s.bind((HOST, PORT))
except socket.error , msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
s.listen(10)
print 'Socket now listening'
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#now keep talking with the client
data = conn.recv(1024)
conn.sendall(data)
conn.close()
s.close()
The Function sendall is used to send data to client , means when I enter the text in terminal on server I should see it on client as well. But this does not happen
The output which I get is
Server Output
$ python server.py
Socket created
Socket bind complete
Socket now listening
Connected with 10.4.1.255:44656
Client Output
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
I am unable to know what's going wrong here?
Also how can I send data (message) from Python Client to Python server??
Any help would be great !
Thanks!

Trapping a shutdown event in Python

I posted a question about how to catch a "sudo shutdown -r 2" event in Python. I was sent to this thread: Run code in python script on shutdown signal .
I'm running a Raspberry Pi v2 with Jessy.
I have read about
signal
and have tried to follow the ideas in the above thread, but so far I have not been successful. Here is my code:
import time
import signal
import sys
def CloseAll(Code, Frame):
f = open('/mnt/usbdrive/output/TestSignal.txt','a')
f.write('Signal Code:' + Code)
f.write('Signal Frame:' + Frame)
f.write('\r\n')
f.close()
sys.exit(0)
signal.signal(signal.SIGTERM,CloseAll)
print('Program is running')
try:
while True:
#get readings from sensors every 15 seconds
time.sleep(15)
f = open('/mnt/usbdrive/output/TestSignal.txt','a')
f.write('Hello ')
f.write('\r\n')
f.close()
except KeyboardInterrupt:
f = open('/mnt/usbdrive/output/TestSignal.txt','a')
f.write('Done')
f.write('\r\n')
f.close()
The program runs in a "screen" session/window and reacts as expected to a CNTL-C. However, when I exit the screen session, leaving the program running, and enter "sudo shutdown -r 2", the Pi reboots as expected after 2 minutes, but the TestSignal.txt file does not show that the signal.SIGTERM event was processed.
What am I doing wrong? Or better yet, how can I trap the shutdown event, usually initiated by a cron job, and close my Python program running in a screen session gracefully?
When you do not try to await such an event, but in a parallel session send SIGTERMto that process (e.g. by calling kill -15 $PID on the process id $PID of the python script running) , you should see an instructive error message ;-)
Also the comment about the mount point should be of interest after you repaired the python errors (TypeError: cannot concatenate 'str' and 'int' objects).
Try something like:
import time
import signal
import sys
LOG_PATH = '/mnt/usbdrive/output/TestSignal.txt'
def CloseAll(Code, Frame):
f = open(LOG_PATH, 'a')
f.write('Signal Code:' + str(Code) + ' ')
f.write('Signal Frame:' + str(Frame))
f.write('\r\n')
f.close()
sys.exit(0)
signal.signal(signal.SIGTERM, CloseAll)
print('Program is running')
try:
while True:
# get readings from sensors every 15 seconds
time.sleep(15)
f = open(LOG_PATH, 'a')
f.write('Hello ')
f.write('\r\n')
f.close()
except KeyboardInterrupt:
f = open(LOG_PATH, 'a')
f.write('Done')
f.write('\r\n')
f.close()
as a starting point. If this works somehow on your system why not rewrite some portions like:
# ... 8< - - -
def close_all(signum, frame):
with open(LOG_PATH, 'a') as f:
f.write('Signal Code:%d Signal Frame:%s\r\n' % (signum, frame))
sys.exit(0)
signal.signal(signal.SIGTERM, close_all)
# 8< - - - ...
Edit: To further isolate the error and adapt more to production like mode, one might rewrite the code like this (given that syslog is running on the machine, which it should, but I never worked on devices of that kind):
#! /usr/bin/env python
import datetime as dt
import time
import signal
import sys
import syslog
LOG_PATH = 'foobarbaz.log' # '/mnt/usbdrive/output/TestSignal.txt'
def close_all(signum, frame):
"""Log to system log. Do not spend too much time after receipt of TERM."""
syslog.syslog(syslog.LOG_CRIT, 'Signal Number:%d {%s}' % (signum, frame))
sys.exit(0)
# register handler for SIGTERM(15) signal
signal.signal(signal.SIGTERM, close_all)
def get_sensor_readings_every(seconds):
"""Mock for sensor readings every seconds seconds."""
time.sleep(seconds)
return dt.datetime.now()
def main():
"""Main loop - maybe check usage patterns for file resources."""
syslog.syslog(syslog.LOG_USER, 'Program %s is running' % (__file__,))
try:
with open(LOG_PATH, 'a') as f:
while True:
f.write('Hello at %s\r\n' % (
get_sensor_readings_every(15),))
except KeyboardInterrupt:
with open(LOG_PATH, 'a') as f:
f.write('Done at %s\r\n' % (dt.datetime.now(),))
if __name__ == '__main__':
sys.exit(main())
Points to note:
the log file for the actual measurements is separate from the logging channel for operational alerts
the log file handle is safeguarded in context managing blocks and in usual operation is just kept open
for alerting the syslog channel is used.
as a sample for the message routing the syslog.LOG_USER on my system (OS X) gives me in all terminals a message, whilst the syslog.LOG_ERR priority message in signal handler only targets the system log.
should be more to the point during shutdown hassle (not opening a file, etc.)
The last point (5.) is important in case all processes receive a SIGTERM during shutdown, i.e. all want to do something (slowing things down), maybe screenalso does not accept any buffered input anymore (or does not flush), note stdout is block buffered not line buffered.
The decoupling of the output channels, should also ease the eventual disappearance of the mount point of the measurement log file.

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