Reading Data from COM Port with pyserial, but empty output - pyserial

i want to read datas from temperature meassurement. The device is connected via USB to PC.
The code shown below just deliver this output:
Serial port is open
b''
b''
b''
b''
Does somebody have anye help for me, I already looked up all familiar problems and their solutions, but none of them could help me:/
import serial
ser = serial.Serial(port='COM10', baudrate = 9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE,timeout=2)
try:
ser.isOpen()
print("Serial port is open")
except:
print("ERROR")
exit()
if(ser.isOpen()):
try:
while( True ) :
print(ser.read())
except:
print("error")
else:
print("Cannot open serial port")

Related

Dual core on Raspberry Pi PICO W with MicroPython

I have an issue with running part of a code to be more specific defined as new thread CoreTask().
I have no idea why I cannot turn on/off built-in LED. The rest of the code looks to be working as expected (WIFI integration and 'httpd service' work fine).
I use Raspberry Pi Pico W with latest MicroPython loaded.
Please advice... Thanks!
import machine
import _thread
import network
import socket
import utime
from machine import Pin
led = machine.Pin('LED', machine.Pin.OUT)
ssid = 'someSSID'
password = 'somePASSWORD'
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
html = """<!DOCTYPE html>
<html>
<body>
<div id="humidity">100</div>
<div id="temperature">21</div>
</body>
</html>
"""
sLock = _thread.allocate_lock()
def CoreTask():
while True:
sLock.acquire()
print('LED...')
led.on()
utime.sleep(1)
led.off()
utime.sleep(1)
sLock.release()
_thread.start_new_thread(CoreTask, ())
while True:
sLock.acquire()
# Wait for connect or fail
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print('waiting for connection...')
utime.sleep(1)
# Handle connection error
if wlan.status() != 3:
raise RuntimeError('network connection failed')
else:
print('connected')
status = wlan.ifconfig()
print( 'ip = ' + status[0] )
# Open socket
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('listening on', addr)
# Listen for connections
while True:
try:
cl, addr = s.accept()
print('client connected from', addr)
request = cl.recv(1024)
print(request)
request = str(request)
response = html
cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
cl.send(response)
cl.close()
except OSError as e:
cl.close()
print('connection closed')
sLock.release()
I'm also keen to know a solution, so far the best try I have got the onboard led working in seperate thread is the following simple code, every other more complicated try was failed.
I have only tested this with onboard LED, so if anyone may try if threading works on real GPIO? If it does, I think this is not an issue as most of time we send out "status blinks" on other LED in project not the onboard one.
import machine
import _thread
import time
def led():
led = machine.Pin('LED', machine.Pin.OUT)
while True:
led.on()
time.sleep(.5)
led.off()
time.sleep(.5)
def pnt():
i=0
while True:
i += 1
print(f"\rThis is the {i} cycle......", sep="", end="")
time.sleep(1)
if __name__ == "__main__":
th1 = _thread.start_new_thread(pnt, ())
#th2 = _thread.start_new_thread(led, ()) This line did not work
led()
I think someone said in a video that the threading is still in experiment and has problems on pico w, and they are working on it.
I also could not workout how to achieve same result with uasycncio, it looks like calling the LED to blink is not about programming but real physical movement, so cannot be "await". Can anyone show ma a correct way?
It's is such an important function to waiting for program (connection loop) while sending "status blinks"

Why does Rasp Pi Pico can not connect to TCP Server after some point?

I use Raspberry Pi Pico with ESP8266 WiFi module, and I am trying to write a TCP client. Rasp Pi Pico is able to send AT commands and receive responses and send data through UART. Also the TCP client is able to send data to the TCP server, which runs in my laptop. However the problem is that the client is not able to connect to the server after some point.
Let me first show the server-side code. In server, I am trying to receive data basically. ConnectionResetError was a problem for me so I wrote the following except block. I am not sure it is buggy or not, since I'm kind of a noob in this area.
import socket
HOST = ""
PORT = 8080
mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
mysocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
mysocket.bind((HOST, PORT))
mysocket.listen(1)
while True:
print("Waiting...")
conn, addr = mysocket.accept()
print('[SERVER] - Connected from: %s' % str(addr))
while True:
try:
request = conn.recv(1024)
if not request:
break
conn.sendall(request.upper())
print('[SERVER] - Received Data: %s' % str(request))
except ConnectionResetError as cr_err:
break
conn.close()
print("[SERVER] - Disconnected")
Here is my client-side code. In client, I wrote two helper classes called ESP8266 and Sensor, in which I control the WiFi module and read analog value from a sensor. Pico first tries to start WiFi module, afterwards it tries to connect to TCP server and send data. After some point it does not connect to the TCP server, so it restart the WiFi module and reconnects.
class EndDevice:
def __init__(self, sensor_id):
self.__wifi_module = ESP8266(UART_PIN, BAUDRATE)
self.__sensor = Sensor(sensor_id, SENSOR_PIN)
def start(self):
self.__wifi_module.start()
self.__wifi_module.set_mode(STATION_MODE)
self.__wifi_module.join_access_point(AP_NAME, AP_PWD)
def reconnect(self):
self.__wifi_module.restart()
self.__wifi_module.set_mode(STATION_MODE)
self.__wifi_module.join_access_point(AP_NAME, AP_PWD)
def run(self):
retry_count = 0
while True:
if self.__wifi_module.start_connection("TCP", SERVER_HOST, SERVER_PORT):
self.__wifi_module.send_data(
str(self.__sensor.generate_package()))
self.__wifi_module.close_connection()
else:
retry_count += 1
if retry_count == MAX_RETRY:
break
if __name__ == "__main__":
pico = EndDevice("SM-0")
pico.start()
while True:
pico.run()
pico.reconnect()
Finally I will share some of the methods in classes ESP8266 and UARTHandler (which is used in ESP8266), so you can see if I do anything non-sense.
start_connection method in ESP8266 is as follows. In this method, I tried to send the corresponding AT command to connect to a TCP server. In the method self.__uart_handler.send_receive_cmd timeout duration is 2000ms, and other parameters are AT command, connection_type (TCP), server IP address and server port, in order.
def start_connection(self, conn_type, remote_ip, remote_port):
conn_type, remote_ip = "\"{}\"".format(conn_type), "\"{}\"".format(remote_ip)
response = self.__uart_handler.send_receive_cmd(2000, CONN_START, conn_type, remote_ip, str(remote_port))
if "OK" in response:
self.__log("Connected to {} at port {}.".format(remote_ip, remote_port))
return True
else:
self.__log("Failed to create a connection with {} at port {}.".format(remote_ip, remote_port))
return False
send_receive_cmd method in UARTHandler is as follows. In this method I use lots of helper methods as you can see, however they are just formatting and writing to UART or reading from UART. I also insert a timeout between UART-read and UART-write
def __generate_cmd(self, cmd, *args):
if len(args) != 0:
cmd += "="
for idx, each in enumerate(args):
cmd += str(each)
if idx != len(args)-1:
cmd += ","
cmd += "\r\n"
return cmd
def __send_cmd(self, cmd, *args):
sent_cmd = self.__generate_cmd(cmd, *args)
self.__uart.write(sent_cmd)
def __receive_response(self, cmd):
response = self.__uart.read()
try: return response.decode('utf-8')
except: return response
def send_receive_cmd(self, timeout, cmd, *args):
self.__send_cmd(cmd, *args)
utime.sleep_ms(timeout)
return self.__receive_response(self.__generate_cmd(cmd, *args))
Let me ask my question again. This codes are working properly in starting-restarting and sending data for (let me say) 3 connections. However, after some connect-disconnect later, TCP client is not able to make a connection with TCP server. Again after some failed connection attempt, WiFi module is restarted and TCP connection is made and working properly again.

Problem with midi setup on Raspberry Pi with midi board for RPi

I bought this one from osa electronics:
https://www.osaelectronics.com/product/midi-board-for-raspberry-pi/
I followed the instructions here on how to set it up:
https://www.osaelectronics.com/learn/setting-up-raspberry-pi-for-midi/
After following the setup and running this in command line:
python
import mido
mido.get_output_names()
It outputs this which seems to be correct:
['Midi Through:Midi Through Port-0 14:0', 'f_midi:f_midi 24:0']
as well as when I run this from command line:
amidi -l
outputs this:
Dir Device Name
IO hw:2,0 f_midi
However when I run some test applications from their webapge I get no input or output.
like this one:
import mido
from mido import MidiFile
from mido import MetaMessage
port = mido.open_output('f_midi')
mid = MidiFile('mymidifile.mid')
while True:
for msg in MidiFile('mymidifile.mid').play():
port.send(msg)
or from this one (I tried to print the msg but it wont print it even. So doesnt seem to step into the while loop but no errormessages)
import mido
import pigpio
from numpy import interp
pi1 = pigpio.pi()
port = mido.open_input('f_midi') # open USB port
while True:
try: # This filters out all non-note data
for msg in port.iter_pending(): # if there is a message pending
print(msg)
if(msg.type == 'note_on'): # if it is Note On message
out = interp(msg.velocity, [0, 127], [0, 255])
#scale velocity from 0-127 to 0-255
# filter the data by note number
if(msg.note == 53):
pi1.set_PWM_dutycycle(2, out)
elif(msg.note == 55):
pi1.set_PWM_dutycycle(3, out)
elif(msg.note == 57):
pi1.set_PWM_dutycycle(4, out)
else: # if the message is not Note On (e.g. Note Off)
if(msg.note == 53):
pi1.set_PWM_dutycycle(2, 0)
elif(msg.note == 55):
pi1.set_PWM_dutycycle(3, 0)
elif(msg.note == 57):
pi1.set_PWM_dutycycle(4, 0)
except AttributeError as error:
print("Error excepted")
pass
I noticed there is some problems with pigpio daemon
After I have been downloading and installed from this page:
http://abyz.me.uk/rpi/pigpio/download.html
And then try to start the daemon with:
sudo pigpiod
I get this errormessage:
bind to port 8888 failed (Address already in use) Can't initialise
pigpio library
However I have also been running through with this in command line:
aplaymidi -p f_midi myMidiTune.mid
No errormessage but no midioutput to my digital piano ...
How can I debug this?

python 3.5.2 UdpServer sendto() error: module 'socket' has no attribute 'sendto'

I've problem with python socket at s.sendto(data,addr)
and my code like this
import socket
def Main():
host = '127.0.0.1'
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
print("server started")
while True:
data, addr = s.recvfrom(1024)
print ("message from : "+ str(addr))
print ("from connected user : "+ str(data))
data = str(data.upper())
print ("sending : "+ str(data))
socket.sendto(data, addr)
and result
socket.sendto(data, addr)
AttributeError: module 'socket' has no attribute 'sendto'
s.close()
if __name__ == '__main__':
Main()
and at UdpClient s.sendto is working
It seems that you mistyped the socket.sendto(... statement: The AttributeError is raised since the method sendto() is to be called from instances of the class socket.socket (as you have in s), and not from the socketmodule itself. See here for more details about the meaning of that statement.
So you basically need to change socket.sendto(... to s.sendto(...
also, if you want to check the attributes of any x object,(apart from reading the docs) you can simply check its x.__dict__ field, as explained here
cheers

Python Socket Multiple Clients

So I am working on an iPhone app that requires a socket to handle multiple clients for online gaming. I have tried Twisted, and with much effort, I have failed to get a bunch of info to be sent at once, which is why I am now going to attempt socket.
My question is, using the code below, how would you be able to have multiple clients connected? I've tried lists, but I just can't figure out the format for that. How can this be accomplished where multiple clients are connected at once and I am able to send a message to a specific client?
Thank you!
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 50000 # Reserve a port for your service.
print 'Server started!'
print 'Waiting for clients...'
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
while True:
msg = c.recv(1024)
print addr, ' >> ', msg
msg = raw_input('SERVER >> ')
c.send(msg);
#c.close() # Close the connection
Based on your question:
My question is, using the code below, how would you be able to have multiple clients connected? I've tried lists, but I just can't figure out the format for that. How can this be accomplished where multiple clients are connected at once and I am able to send a message to a specific client?
Using the code you gave, you can do this:
#!/usr/bin/python # This is server.py file
import socket # Import socket module
import thread
def on_new_client(clientsocket,addr):
while True:
msg = clientsocket.recv(1024)
#do some checks and if msg == someWeirdSignal: break:
print addr, ' >> ', msg
msg = raw_input('SERVER >> ')
#Maybe some code to compute the last digit of PI, play game or anything else can go here and when you are done.
clientsocket.send(msg)
clientsocket.close()
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 50000 # Reserve a port for your service.
print 'Server started!'
print 'Waiting for clients...'
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print 'Got connection from', addr
while True:
c, addr = s.accept() # Establish connection with client.
thread.start_new_thread(on_new_client,(c,addr))
#Note it's (addr,) not (addr) because second parameter is a tuple
#Edit: (c,addr)
#that's how you pass arguments to functions when creating new threads using thread module.
s.close()
As Eli Bendersky mentioned, you can use processes instead of threads, you can also check python threading module or other async sockets framework. Note: checks are left for you to implement how you want and this is just a basic framework.
accept can continuously provide new client connections. However, note that it, and other socket calls are usually blocking. Therefore you have a few options at this point:
Open new threads to handle clients, while the main thread goes back to accepting new clients
As above but with processes, instead of threads
Use asynchronous socket frameworks like Twisted, or a plethora of others
Here is the example from the SocketServer documentation which would make an excellent starting point
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
It is instantiated once per connection to the server, and must
override the handle() method to implement communication to the
client.
"""
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
# Activate the server; this will keep running until you
# interrupt the program with Ctrl-C
server.serve_forever()
Try it from a terminal like this
$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello
HELLOConnection closed by foreign host.
$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Sausage
SAUSAGEConnection closed by foreign host.
You'll probably need to use A Forking or Threading Mixin too
This program will open 26 sockets where you would be able to connect a lot of TCP clients to it.
#!usr/bin/python
from thread import *
import socket
import sys
def clientthread(conn):
buffer=""
while True:
data = conn.recv(8192)
buffer+=data
print buffer
#conn.sendall(reply)
conn.close()
def main():
try:
host = '192.168.1.3'
port = 6666
tot_socket = 26
list_sock = []
for i in range(tot_socket):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host, port+i))
s.listen(10)
list_sock.append(s)
print "[*] Server listening on %s %d" %(host, (port+i))
while 1:
for j in range(len(list_sock)):
conn, addr = list_sock[j].accept()
print '[*] Connected with ' + addr[0] + ':' + str(addr[1])
start_new_thread(clientthread ,(conn,))
s.close()
except KeyboardInterrupt as msg:
sys.exit(0)
if __name__ == "__main__":
main()
def get_clients():
first_run = True
startMainMenu = False
while True:
if first_run:
global done
done = False
Thread(target=animate, args=("Waiting For Connection",)).start()
Client, address = objSocket.accept()
global menuIsOn
if menuIsOn:
menuIsOn = False # will stop main menu
startMainMenu = True
done = True
# Get Current Directory in Client Machine
current_client_directory = Client.recv(1024).decode("utf-8", errors="ignore")
# beep on connection
beep()
print(f"{bcolors.OKBLUE}\n***** Incoming Connection *****{bcolors.OKGREEN}")
print('* Connected to: ' + address[0] + ':' + str(address[1]))
try:
get_client_info(Client, first_run)
except Exception as e:
print("Error data received is not a json!")
print(e)
now = datetime.now()
current_time = now.strftime("%D %H:%M:%S")
print("* Current Time =", current_time)
print("* Current Folder in Client: " + current_client_directory + bcolors.WARNING)
connections.append(Client)
addresses.append(address)
if first_run:
Thread(target=threaded_main_menu, daemon=True).start()
first_run = False
else:
print(f"{bcolors.OKBLUE}* Hit Enter To Continue.{bcolors.WARNING}\n#>", end="")
if startMainMenu == True:
Thread(target=threaded_main_menu, daemon=True).start()
startMainMenu = False
#!/usr/bin/python
import sys
import os
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 50000
try:
s.bind((socket.gethostname() , port))
except socket.error as msg:
print(str(msg))
s.listen(10)
conn, addr = s.accept()
print 'Got connection from'+addr[0]+':'+str(addr[1]))
while 1:
msg = s.recv(1024)
print +addr[0]+, ' >> ', msg
msg = raw_input('SERVER >>'),host
s.send(msg)
s.close()