I tried to communicate Python and Arduino with pyserial on Win8
but it had error like this
Traceback (most recent call last):
File "C:\Users\Fon\Desktop\x.py", line 7, in <module>
ser.open() # open serial port
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 66, in open
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM4': WindowsError(2, 'The system cannot find the file specified.')
this is my code
import serial
ser = serial.Serial()
ser.port = 3 # serial port
ser.baudrate = 115200 # set baudrate 115200
ser.timeout = 60 # timeout 60 second
ser.open() # open serial port
while True:
ser.write('l') # send '1' to port to get light
light = ser.read(4)
print "light", light
in this code I tried to open port 'COM4', I already check this port is available and I already tried another port but it not worked any port.
Am I using wrong port? or something? ;(
Related
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.
I was developing a program that individual elements from the list to another machine (sender-server,reciever-client). I am sharing my program below
-------------------------client.py------------------------
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 4444 # Reserve a port for your service.
s.connect((host, port))
s.send("Hi server1")
while True:
a=int(s.recv(1024))
tmp=0
while tmp<=a:
print s.recv(1024)
tmp=tmp+1
----------------------------------server.py------------------------------
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 4444 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5)
print "Server listening"
while True:
c=s.accept()
b=['a','b']
d=len(b)
a=str(d)
c.send(a)
for i in range(0,len(b)):
tmp=str(b[i])
c.send(tmp)
When I run both server and client, the server raises this:
Traceback (most recent call last):
File "server.py", line 14, in <module>
c.send(a)
AttributeError: 'tuple' object has no attribute 'send'
You'll have to fix the indentation on line 11 of client.py.
socket.accept() returns a tuple (conn, addr) where conn is a socket object. You have to use that object in line 14 to send things. What you're doing is calling send() from the entire tuple which has no method named send and so the AttributeError gets raised. I'd suggest changing line 11 to c = s.accept()[0].
I am telnet into Keysight N1914A power meter and python subprocess.check_out[("Measure:Power?)] is not working. So I am trying to use the python telnetlib. I do not need username or password to log in. IP address and port number is all it needs.
There are lots of examples showing how to log in the device. My question is that how to obtain the results from the device after input commands.
For example: in the device, I type *IDN? it will result its device information; and when I type Measure:Power? it will result the power in decibel format.
import time
import csv
from string import split
import getpass
import sys
import telnetlib
import subprocess
Host = "192.168.1.10"
PORT = 5024
TIMEOUT =10
i = open('practice1.csv', 'wb')
tn = telnetlib.Telnet(Host,PORT)
print "You log in"
time.sleep(5)
while True:
#Powertemp1 = subprocess.check_output(["Measure:Power?"])
#tn.write("Measure:Power?")
tn.write("*IDN?")
Powertemp1 = tn.read_all()
print type(Powertemp1)
print Powertemp1
#Powertemp = float(Powertemp1)
#print '&s' % Powertemp
#wr = csv.writer(i, dialet = 'excel')
#wr.writerow([Powertemp])
time.sleep(5)
type(tn.read_all()) is str, but in the actual screen it is around 40 empty lines, and nothing is stored in the output text file.
Here is the result:
You log in
Traceback (most recent call last):
File "sunlook.py", line 25, in <module>
tn.write("*IDN?")
File "/usr/lib/python2.7/telnetlib.py", line 282, in write
self.sock.sendall(buffer)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 32] Broken pipe
I got this error in my program:
Traceback (most recent call last):
File "scriptA.py", line 17, in <module>
socketPub.bind("tcp://localhost:%s"% portPub)
File "socket.pyx", line 434, in zmq.backend.cython.socket.Socket.bind (zmq/backend/cython/socket.c:3928)
File "checkrc.pxd", line 21, in zmq.backend.cython.checkrc._check_rc (zmq/backend/cython/socket.c:6058)
zmq.error.ZMQError: No such device
This is a simple script I have done to reproduce it:
import zmq
import random
import sys
import time
port = "5566"
if len(sys.argv) > 1:
port = sys.argv[1]
int(port)
portSub = "5556"
context = zmq.Context()
portPub = "5566"
#contextPub = zmq.Context()
socketPub = context.socket(zmq.PUB)
socketPub.bind("tcp://localhost:%s"% portPub)
socket = context.socket(zmq.SUB)
socket.connect("tcp://localhost:%s"% portSub)
socket.setsockopt(zmq.SUBSCRIBE,'')
while True:
socket.send("BB", zmq.SNDMORE)
socket.send("16", zmq.SNDMORE)
socket.send("14", zmq.SNDMORE)
socket.send("11", zmq.SNDMORE)
socket.send("4")
time.sleep(3)
I want to subscribe to one point and be able to send to another one. Is it possible? 2 differents end points. A sends to B and B sends to C.
Try to replace localhost by 127.0.0.1.
For more information, have a look at this stackoverflow thread
Your port numbers do not match. From your code:
portSub = "5556"
portPub = "5566"
So you are binding to one port and connecting to another. Make sure the ports match or simply do:
portSub = "5556"
portPub = portSub
Furthermore, I'm not sure if your binding-string "tcp://localhost:%s"% portPub is correct. When working with ZMQ, I always use the Asterisk * instead of localhost or 127.0.0.1. This always works for me and is something you can try if changing the port number does not make it work: "tcp://*:%s"% portPub (or I prefer f'tcp://*:{portPub}', which is more readable I think). I think you have to use the binding-string I propose. Your connection-string seems to be fine.
I am trying to connect to a remote MySql server from my local machine.
I want to run it whenever the DEBUG constant is set to true.
Here's the script:
import select
import SocketServer
import sys
import threading
import paramiko
SSH_PORT = 22
DEFAULT_PORT = 4000
g_verbose = True
class ForwardServer (SocketServer.ThreadingTCPServer):
daemon_threads = True
allow_reuse_address = True
class Handler (SocketServer.BaseRequestHandler):
def handle(self):
try:
chan = self.ssh_transport.open_channel('direct-tcpip',
(self.chain_host, self.chain_port),
self.request.getpeername())
except Exception, e:
verbose('Incoming request to %s:%d failed: %s' % (self.chain_host,
self.chain_port,
repr(e)))
return
if chan is None:
verbose('Incoming request to %s:%d was rejected by the SSH server.' %
(self.chain_host, self.chain_port))
return
verbose('Connected! Tunnel open %r -> %r -> %r' % (self.request.getpeername(),
chan.getpeername(), (self.chain_host, self.chain_port)))
while True:
r, w, x = select.select([self.request, chan], [], [])
if self.request in r:
data = self.request.recv(1024)
if len(data) == 0:
break
chan.send(data)
if chan in r:
data = chan.recv(1024)
if len(data) == 0:
break
self.request.send(data)
chan.close()
self.request.close()
verbose('Tunnel closed from %r' % (self.request.getpeername(),))
def forward_tunnel(local_port, remote_host, remote_port, transport):
# this is a little convoluted, but lets me configure things for the Handler
# object. (SocketServer doesn't give Handlers any way to access the outer
# server normally.)
class SubHander (Handler):
chain_host = remote_host
chain_port = remote_port
ssh_transport = transport
ForwardServer(('', local_port), SubHander).serve_forever()
def verbose(s):
if g_verbose:
print s
HELP = """\
Set up a forward tunnel across an SSH server, using paramiko. A local port
(given with -p) is forwarded across an SSH session to an address:port from
the SSH server. This is similar to the openssh -L option.
"""
def forward():
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
try:
print 'connecting'
client.connect('*******', username='***', password='****!')
print 'connected'
except Exception, e:
print '*** Failed to connect to %s:%d: %r' % ('*****', 22, e)
sys.exit(1)
try:
forward_tunnel(3306, '127.0.0.1', 3306, client.get_transport())
except SystemExit:
print 'C-c: Port forwarding stopped.'
sys.exit(0)
I have two problems here:
1) I don't know how and when to call my forward function when django raises.
2) When I access django locally and run the script from the console I get the following exception:
exception happened during
processing of request from
('127.0.0.1', 41872) Traceback (most
recent call last): File
"/usr/lib/python2.6/SocketServer.py",
line 558, in process_request_thread
self.finish_request(request, client_address) File
"/usr/lib/python2.6/SocketServer.py",
line 320, in finish_request
self.RequestHandlerClass(request, client_address, self) File
"/usr/lib/python2.6/SocketServer.py",
line 615, in init
self.handle() File "/home/omer/Aptana Studio 3
Workspace/Website/src/ssh_tunnel/tunnel.py",
line 51, in handle
verbose('Tunnel closed from %r' % (self.request.getpeername(),)) File
"", line 1, in getpeername
File "/usr/lib/python2.6/socket.py",
line 165, in _dummy
raise error(EBADF, 'Bad file descriptor') error: [Errno 9] Bad file
descriptor
Was this a bad idea to begin with?
Should I do this manually every time?
I don't think it's a bad idea.
I don't think you need to do it manually.
The exception is a bug in paramiko's forward code sample. This has been addressed by jhalcrow in the pull request here:
https://github.com/paramiko/paramiko/pull/36
This post has some code to do it in a more event driven way, i.e if you wanted to call it via some web event hooks in your django code or the like:
Paramiko SSH Tunnel Shutdown Issue
humm, i didn't try this, but if you are on linux, could you run
ssh -L 3306:localhost:3306 remote.host.ip
through python system call when DEBUG is set?
also if you are on Windows, try putty with port forwarding