473,811 Members | 2,979 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

serial and threads

Hi all!

I'm trying to write a program in python using the modules
'serialwin32' and 'thread' to create one thread that writes to a
serial port and another one that reads from it at 'the same time'. My
definitions are

def NetworkToSerial (input):
s.write(binasci i.unhexlify(inp ut))
print "SENT: %s" % input

def SerialToNetwork ():
result = s.read(1)
print "RECEIVED:"
print binascii.hexlif y(result)

and I call them with

thread.start_ne w_thread(Networ kToSerial, (command,))
thread.start_ne w_thread(Serial ToNetwork, ())

The first one seems to run fine, but for the second one I get the
error message 'ClearCommError ', 'the handle is invalid'.

Does anyone have a clue whether maybe serialwin32 is not
thread-compatible?

Thanks for your help in advance!

Silke
Jul 18 '05 #1
5 5927
Silke wrote:
Hi all!

I'm trying to write a program in python using the modules
'serialwin32 ' and 'thread' to create one thread that writes to a

<snip>
Hello,

I've done a similar implementation, I always assume that -
unless the documentation for a class specifically states that it is
thread-safe then I assume it isn't. The way I get around the issue you
have is to lock access to the serial object (s in your case). The way I
get around this is to use the InWaiting method (or whatever the
equivalent will be in your serial module) which will return how many
bytes are waiting, then I can read that number of bytes from the serial
port, store the information and release the lock on that port. :

self.__objLock. acquire()
try:
intNoChars = self.__objSeria lPort.inWaiting ()
if (intNoChars > 0):
strReceivedStri ng = self.__objSeria lPort.read(intN oChars)
self.newMessage (strReceivedStr ing)
self.__objLock. release()
except:
self.__objLock. release()
raise

Obviously you will also want to lock on all other access to the
port, close, open, write, etc.

P.S. Please don't start ranting about my use of Hungarian!!

Cheers,

Neil

--

Neil Benn
Senior Automation Engineer
Cenix BioScience
BioInnovations Zentrum
Tatzberg 47
D-01307
Dresden
Germany

Tel : +49 (0)351 4173 154
e-mail : be**@cenix-bioscience.com
Cenix Website : http://www.cenix-bioscience.com

Jul 18 '05 #2
Hi again,

I already found a solution using 'threading' instead of 'thread' :-)

Ciao,

Silke
na******@gmx.de (Silke) wrote in message news:<39******* *************** ****@posting.go ogle.com>...
Hi all!

I'm trying to write a program in python using the modules
'serialwin32' and 'thread' to create one thread that writes to a
serial port and another one that reads from it at 'the same time'. My
definitions are

def NetworkToSerial (input):
s.write(binasci i.unhexlify(inp ut))
print "SENT: %s" % input

def SerialToNetwork ():
result = s.read(1)
print "RECEIVED:"
print binascii.hexlif y(result)

and I call them with

thread.start_ne w_thread(Networ kToSerial, (command,))
thread.start_ne w_thread(Serial ToNetwork, ())

The first one seems to run fine, but for the second one I get the
error message 'ClearCommError ', 'the handle is invalid'.

Does anyone have a clue whether maybe serialwin32 is not
thread-compatible?

Thanks for your help in advance!

Silke

Jul 18 '05 #3
Silke wrote:
I already found a solution using 'threading' instead of 'thread' :-)


Are you positive that is really a solution? If the original
problem was truly because of a thread-safety issue, then it's
most likely, I think, that it was a race condition and that
it could very well re-appear in the future.

The "threading" module is mostly just a higher level API on
top of the "thread" module, so that change alone seems unlikely
to solve the issue, unless there is code in serialwin32 specifically
to do the proper locking when the threading module is used...

-Peter
Jul 18 '05 #4
na******@gmx.de (Silke) wrote in
news:39******** *************** ***@posting.goo gle.com:
I'm trying to write a program in python using the modules
'serialwin32' and 'thread' to create one thread that writes to a


if you mean that serialwin32 from pyserial, then there is an example of a
tcp<->serial gateway:
http://cvs.sf.net/viewcvs.py/pyseria...erial_redirect
..py?rev=1.2&vi ew=auto
(one line URL)

i'd sugest to import "serial" and not the platform modules. that way you
have protablity to other OS for free, and you speak in the same terms as
the others do.

chris

--
Chris <cl******@gmx.n et>

Jul 18 '05 #5
Hi Peter,

I only verified this by checking it out. Here is the code

import sys
sys.path.append ('c:\\python23\ \lib\\site-packages\\seria l')
import thread #This module provides low-level primitives for
working with multiple threads
import threading #This module constructs higher-level threading
interfaces on top of the lower level thread module.
import serialwin32 #Python Serial Port Extension for Win32,
Linux, BSD, Jython; serial driver for win32; see __init__.py
import socket #Low-level networking interface
import binascii #Convert between binary and ASCII

def NetworkToSerial (input):
s.write(binasci i.unhexlify(inp ut))
print "SENT: %s" % input # %s: if command is
not string format to string

def SerialToNetwork ():
result = s.read(12)
print "RECEIVED:"
print binascii.hexlif y(result)

s = serialwin32.Ser ial ()
s.port = 0 #COM1
s.baudrate = 115200
s.databits = 8
s.timeout = None #None=wait forever; 0=return
immediately on read; x = x seconds
s.open()

command = "0b02ff05123400 00000255aa"

sthread = threading.Threa d(target=Networ kToSerial(comma nd))
rthread = threading.Threa d(target=Serial ToNetwork)

sthread.start()
rthread.start()
sthread.join(5)
rthread.join(5)

s.close()

and it does exactly what I want it to do, so I guess it's ok...

Thank you for your help!

Bye

Silke
Peter Hansen <pe***@engcorp. com> wrote in message news:<U9******* *************@p owergate.ca>...
Silke wrote:
I already found a solution using 'threading' instead of 'thread' :-)


Are you positive that is really a solution? If the original
problem was truly because of a thread-safety issue, then it's
most likely, I think, that it was a race condition and that
it could very well re-appear in the future.

The "threading" module is mostly just a higher level API on
top of the "thread" module, so that change alone seems unlikely
to solve the issue, unless there is code in serialwin32 specifically
to do the proper locking when the threading module is used...

-Peter

Jul 18 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2153
by: Greg Pedder | last post by:
Hello. I have an application that uses the Java Communications API to use a modem. At startup, the application checks to see what serial devices are connected. For each serial device, the app tries to write some "AT" commands to make sure it gets back "OK" from the modem. At this point all the ports are closed and the application goes into a serversocket accept blocking call and waits for any connections.
1
393
by: Silke | last post by:
Hi all! I'm trying to write a program in python using the modules 'serialwin32' and 'thread' to create one thread that writes to a serial port and another one that reads from it at 'the same time'. My definitions are def NetworkToSerial(input): s.write(binascii.unhexlify(input)) print "SENT: %s" % input
3
2998
by: Tom Brown | last post by:
Hey people, I've written a python app that r/w eight serial ports to control eight devices using eight threads. This all works very nicely in Linux. I even put a GUI on it using PyQt4. Still works nicely. Then I put the app on on a virtual Windows machine running inside of vmware on the same Linux box. Vmware only lets me have four serial ports so I run the app against four serial ports using four threads. The app did not respond...
38
9674
by: shussai2 | last post by:
Hi, I am trying to access Serial Port in XP. I am using Dev-C++ IDE that uses Mingw as a compiler. I just want to know how I can open up serial port on COM1 and write some data. I have searched quite a bit over the web and could not find anything useful. I don't want to use Visual C++ or Cygwin, linux, etc. If any of you guys have some little tid bit of code that would be great to look at.
7
5400
by: davetelling | last post by:
I'm a newbie that is still struggling with OOP concepts & how to make things work they way I want. Using Visual C# Express, I have a form in which I added a user control to display a graph, based upon data received via the serial port. If I run the serial port in the main form code, I can get data and, using public properties of the user control, transfer the data to be shown on the graph. However, I am trying to add a feature that will...
4
5559
by: Jamie Risk | last post by:
I'm trying to implement a protocol that has a concept of a GAP timer in the serial stream; if two properly framed characters are spaced in time by so many milliseconds or longer, there is an error. So far I'm looking at using the SerialPort.DataReceived event. It's nice because I can suck in bytes filter it through a state machine to see if packets are properly framed than raise an event. The problem as I understand it, the...
9
14404
by: Hal Vaughan | last post by:
I've done a fair amount of Googling for information on reading the serial port in C++ (and in Linux). Unfortunately, out of every 4 hits, 1 seems to be an unanswered question, 1 is someone saying, "That's easy, there's a lot out there, Google it,", 1 is a discussion on it without examples and the other is who knows what. I did find some info on it and have been experimenting. The one example that I liked the best in terms of...
5
5633
by: kkadrese | last post by:
hello group, how to get ttyS0 serial port for exclusive access? I have a python script that uses this device with AT commands. I need that two instances can call simultaneosuly this python script but only one of them gets the device. I tried fcntl.flock, it was just ignored, put writtable file LCK..ttyS0 in /var/lock, tried ioctl (but I may not know what are appropriate arguments), googled half a day for various phrases, error messages...
1
1352
by: LukeJ | last post by:
Hi, I built a VB.NET application that bridges the communication between a Fanuc Robot and a Plasma cutting unit. The way the application works is to wait for the robot to turn on a signal and fire an event in the main form (which is an MDI form BTW). This in turn opens a dialog from which then does the serial port write to the plasma and then reads to make sure the commands were accepted. The problem I had was that there is another screen...
0
10379
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10394
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10127
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9201
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7665
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6882
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4336
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3863
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.