is there a problem on this simple code

jrlen balane nbbalane at gmail.com
Wed Mar 30 16:39:11 EST 2005


a simple question regarding threading and timer:

if i put my timer control inside the thread, will the thread be exited
every time there is a timer event???

please help...

def someThreadHere()
     ...
     someTimer.start(3000)
     ....

def someTimerEvent()
     .....


 
On Wed, 16 Mar 2005 07:38:09 GMT, Dennis Lee Bieber
<wlfraed at ix.netcom.com> wrote:
> On Wed, 16 Mar 2005 09:47:01 +0800, jrlen balane <nbbalane at gmail.com>
> declaimed the following in comp.lang.python:
> 
> > please post your suggestions? please ...
> >
>        Since we don't have your hardware, nor have you been able supply
> the formal documentation of the protocol in use, all we can do is
> comment on coding styles and obvious errors in the code... If there is
> an flaw in the implementation of the protocol, we have no way to tell.
> 
> >
> 
> > > import sys
> > > import serial
> > > import sys, os
> > > import serial
> 
>        How about cleaning that up... You've imported serial twice, and
> sys twice.
> 
> > > data_file = open('C:/Documents and Settings/nyer/Desktop/IRRADIANCE.txt', 'r')
> > > data = data_file.readlines()
> > >
> > > def process(list_of_lines):
> > >     data_points = []
> > >     for line in list_of_lines:
> > >         data_points.append(int(line))
> > >     return data_points
> > >
> > > irradiance = process(data)
> 
>        Well, this is legal, though confusing to stuff a function
> definition between lines of the main program. Common is to put the
> "def"s after the "imports" (though defining "constants" may be okay in
> there)
> 
>        If "process" is only used once, it might not even be worth the
> "def"...
> 
> > >
> > > ser = serial.Serial()
> > > ser.baudrate = 9600
> > > ser.port = 0
> > > ser
>        Delete that -- you've been told that it is meaningless for days
> now... If you don't want to take advice, why ask?
> 
> > >
> > > ser.open()
> > > tx_command = 67
> > > tx_no_databyte = 2
> > > tx_message_no = 1
> > > tx_len = len (irradiance)
> > >
> > > for j in range (tx_len)  :
> > >     start_time = time.time()
> > >
> > >     temp1 = []
> > >     temp2 = []
> > >     pyra1 = []
> > >     pyra2 = []
> > >     voltage = []
> > >     current = []
> > >
> > >     current_time = time.time()
> > >
> > >     while( current_time >= start_time + 300):
> > >
>        If current time is < start+300, the entire loop will be skipped
> -- a condition that is quite likely to happen unless you have a /very/
> slow machine.
> 
> > >         data_hi, data_lo = divmod(irradiance[j], 0x100)
> > >         tx_checksum = -(data_hi + data_lo + tx_command + tx_message_no
> > > + tx_no_databyte) & 0xff
> > >         ser.write(pack('6B', tx_command, tx_message_no,
> > > tx_no_databyte, data_lo, data_hi, tx_checksum))
> > >
> > >         rx_data = ser.read(19)
> > >         rx_len = len(rx_data)
> > >         byte = [ord(x) for x in rx_data]
> > >
> > >         if rx_len < 10:
> > >             #print 'it is not pumping data out as fast as we assumed'
> > >             sys.exit(1)
> > >
> > >         for k in range (rx_len-9):
> > >             if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10])
> > > & 0xff == 0:
> > >                 #print byte[k:k+10]
> > >
> > >                 temp1.append(byte[k+3])
> > >                 temp2.append(byte[k+4])
> > >                 pyra1.append(byte[k+5])
> > >                 pyra2.append(byte[k+6])
> > >                 voltage.append(byte[k+7])
> > >                 current.append(byte[k+8])
> > >                 print temp1, temp2, pyra1, pyra2, voltage, current
> > >
>        All these are lists, do you really mean to print the entire list
> each time, or only the most recent data value?
> 
> > >         current_time = time.time()
> > >
> > > while theres no error in the output, there is also no response from
> > > the hardware or maybe communication is off.
> > >
> > > could somebody out there help me.
> > >
> 
> > > by the way, here is a working code: though here the data to be
> > > transmitted is just incrementing and not read from a text file:
> > >
> > > import serial
> > > import string
> > > import time
> > > from struct import *
> > > import os
> > >
> > > ser = serial.Serial()
> > >
> > > ser.baudrate = 9600
> > > ser.port = 0
> > > ser.timeout = 1
> > > ser
> > >
> > > ser.open()
> > > tx_command = 67
> > > tx_message_no = 1
> > > tx_no_databyte = 2
> > > item=10000
> > > for item in range(10000, 30001, 10):
> > >
> > >     data_hi, data_lo = divmod(item, 0x100)
> > >     tx_checksum = -(data_hi + data_lo + tx_command + tx_message_no +
> > > tx_no_databyte) & 0xff
> > >     ser.write(pack('6B', tx_command, tx_message_no, tx_no_databyte,
> > > data_lo, data_hi, tx_checksum))
> > >     #print tx_command, tx_message_no, tx_total_data, data_lo, data_hi,
> > > tx_checksum
> > >
> > >
> > >     rx_data = ser.read(19)
> > >     rx_len = len(rx_data)
> > >     #print 'rx_len', rx_len
> > >     byte = [ord(x) for x in rx_data]
> > >     #print 'received', byte
> > >
> > >     if rx_len < 10:
> > >         print 'it is not pumping data out as fast as we assumed'
> > >         sys.exit(1)
> > >
> > >     for k in range (rx_len-9):
> > >         if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10]) & 0xff == 0:
> > >             print byte[k:k+10]
> > > ===================================
> > > outputs:
> > > [70, 2, 6, 54, 197, 253, 230, 231, 211, 26]
> > > [70, 3, 6, 54, 197, 253, 230, 231, 211, 25]
> > > [70, 3, 6, 54, 197, 253, 230, 231, 210, 26]
> > > [70, 3, 6, 54, 197, 253, 230, 231, 210, 26]
> > > [70, 3, 6, 54, 197, 253, 230, 231, 211, 25]
> > > [70, 3, 6, 54, 197, 253, 230, 231, 210, 26]
> > > [70, 3, 6, 54, 197, 253, 230, 231, 211, 25]
> > > [70, 3, 6, 54, 197, 253, 230, 231, 210, 26]
> > > [70, 3, 6, 54, 197, 253, 230, 231, 211, 25]
> > > ...
> > > ...
> > >
> 
>        And please trim... You don't need to quote the same text over
> and over... We've all seen it by now, or can retrieve it using the
> message headers.
> 
> -=-=-=-=-=-=-=-=-=-=-=-=-
> """
>    EVERYTHING THAT FOLLOWS IS THE RESULT OF "FREE ASSOCIATION"
>    THINKING. NONE OF IT HAS BEEN TESTED FOR CORRECTNESS OF
>    SYNTAX OR SEMANTICS -- IT SHOULD BEST BE CONSIDERED PSEUDO-
>    CODE, GIVING A GUIDELINE FROM WHICH TO PROCEED WITH REAL
>    DEVELOPMENT
> """
> 
> import serial   #I don't have this, and don't have your hardware,
>                #so this is all guesswork, and untested
> import os
> import sys
> import time
> import threading
> import Queue
> 
> DATA_FID = r"C:\\Documents and Settings\\nyer\\Desktop\\IRRADIANCE.txt"
>            #I definitely don't have a "nyer" user <G>
> 
> class DeviceHandler(object):
>    def _checksum(packet):
>        #   compute checksum from packet (which should be a list)
>        return -sum(packet) & 0xFF
> 
>    def _Reader(self):
>        #   worker code for the reader /thread/, continuous
>        #   loop, reading response packets and putting them
>        #   (or some error message string) onto the queue
>        while 1:
>            #   accept first three as response code, message count
>            #   and data length
>            response = ord(self._ser.read(1))
>            count = ord(self._ser.read(1))
>            length = ord(self._ser.read(1))
>            #   get the data bytes
>            data = []
>            for x in range(length):
>                data.append(ord(self._ser.read(1)))
>            #   get the message checksum
>            check = ord(self._ser.read(1))
>            #   format it all as a packet list
>            packet = [response, count, length] + data
>            packet = packet.append(check)
>            #   check for out of sequence packet
>            if count != self._RX_count:
>                #   notify via queue, then reset expected counter
>                self._queue.put("Receive packet number is out of
> sequence")
>                self._RX_count = count
>            #   confirm checksome and notify if needed
>            if _checksum(packet) != 0:
>                self._queue.put("Receive packet checksum is invalid")
>            #   put the packet, regardless of validity, onto queu
>            self._queue.put(packet)
>            self._RX_count += 1 & 0xFF   #quick & dirty modulo 256
> 
>    def __init__(self, port, rate, queue):
>        #   initialize handler instance
>        self._TX_count = 0
>        self._RX_count = 0
>        self._ser = serial.Serial()
>        self._ser.port = port
>        self._ser.baudrate = rate
>        self._ser.open()
>        self._queue = queue
>        self._reader = threading.Thread(target=self._Reader())
>        #   make the reading thread a daemon, so it won't block
>        #   main program from exiting
>        self._reader.setDaemon(True)
>        self._reader.start()
> 
>    def close(self):
>        self.ser.close()
> 
>    def sendPacket(self, Command=0x00, Data = None):
>        #   format a packet list from input data
>        packet = [Command, self._TX_count, len(Data)] + Data
>        #   append checksum
>        packet.append(self._checksum(packet))
>        #   convert to string format -- all data better be
>        #   0x00 - 0xFF
>        output = "".join([chr(x) for x in packet])
>        self._ser.write(output)
>        #   increment output counter
>        self._TX_count += 1 & 0xFF
> 
> #   MAIN PROGRAM STARTS HERE
> fdata = open(DATA_FID, "r")
> 
> #   create response transfer queue, and serial port handler instance
> myQ = Queue.Queue()
> myDevice = DeviceHandler(port = 0, rate = 9600, queue = myQ)
> 
> for ln in fdata:
>    #   NOTE: no TIMING of command output is performed, they
>    #   go out as fast as the response queue can be emptied
>    #   reset response data array
>    temp1 = []
>    temp2 = []
>    pyra1 = []
>    pyra2 = []
>    voltage = []
>    current = []
> 
>    #   extract all responses that have been received up to now
>    #   note: this is NOT a loop until empty, only for whatever
>    #   was available at the start of this pass
>    for i in range(myQ.qsize()):
>        resp = myQ.get_nowait()
>        if type(resp) is types.StringType:
>            print "Bad response packet: %s" % resp
>        elif resp[2] != 6 or resp[0] != 0x70:
>            print "Unexpected response:"
>            print "    Code = %s\tCount = %s\tLength = %s" % (resp[0],
>                                                              resp[1],
>                                                              resp[2])
>            print "    Data = ",
>            for j in range(resp[2]):
>                print resp[j + 3],
>            print "\tChecksum = %s" % resp[resp[2] +3]
>        else:
>            #   capture data field
>            temp1.append(resp[3])
>            temp2.append(resp[4])
>            pyra1.append(resp[5])
>            pyra2.append(resp[6])
>            voltage.append(resp[7])
>            current.append(resp[8])
>            #   display current data
>            print "Code = %s\tcount = %s\tLength = %s" % (resp[0],
>                                                          resp[1],
>                                                          resp[2])
>            print "temp1 = %s\ttemp2 = %s" % (resp[3], resp[4])
>            print "pyra1 = %s\tpyra2 = %s" % (resp[5], resp[6])
>            print "voltage =  %s\tcurrent = %s" % (resp[7], resp[8])
>            print "\tchecksum = %s" % resp[9]
> 
>    #   process one input data value
>    dvalue = int(ln)
>    (d_high, d_low) = divmod(dvalue, 0x100)
> 
>    #   send the packet
>    myDevice.sendPacket(Command = 0x67, Data = [d_high, d_low])
> 
>    #what do you want to do with the arrays that built up, as they get
>    #reset on the next loop pass
>    print "temp1", temp1
>    print "temp2", temp2
>    print "pyra1", pyra1
>    print "pyra2", pyra2
>    print "voltage", voltage
>    print "current", current
> 
> #   end of input file, close file and exit
> #   NOTE: does not wait for response data to catch up
> fdata.close()
> myDevice.close()
> 
> -=-=-=-=-=-=-=-=-=-=-
> 
>        Explore that and see if you can understand the modularization
> (minimal) and processing logic.
> 
> --
> > ============================================================== <
> >   wlfraed at ix.netcom.com  | Wulfraed  Dennis Lee Bieber  KD6MOG <
> >      wulfraed at dm.net     |       Bestiaria Support Staff       <
> > ============================================================== <
> >           Home Page: <http://www.dm.net/~wulfraed/>            <
> >        Overflow Page: <http://wlfraed.home.netcom.com/>        <
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list