accessing a device with python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Pierpaolo
    New Member
    • Mar 2007
    • 5

    accessing a device with python

    Hi everybody,
    first of all I'd like to say that I am a beginner with python so please be patience. I googled a lot before posting the following question.

    I am trying to port a small C code of mine which "talks" to a real-time kernel module to python.
    I need an easy way to set up a graphic interface therefore I am using tkinter.

    I need to send a C struct to /dev/rtf0:

    typedef struct {
    enum etype command;
    int command_num; /* comando n. */
    int freq; /* frequenza fase rampa costante */
    unsigned int steps_x; /* step da fare */
    unsigned int steps_y;
    unsigned int steps_z;
    unsigned int steps_a;
    unsigned char dir; /* byte con le direzioni x y z a */
    } COMMAND_STRUCT;

    Could anyone please provide a way or a link to somewhere where I could find some example code for doing such thing (ie defining a python equivalent for struct)?

    I would also be grateful for links to sites with practical example of tkinter classes use.

    Thanks a lot for any help,
    Pier
  • dshimer
    Recognized Expert New Member
    • Dec 2006
    • 136

    #2
    This just hints around the edges of what you are asking, but I work with a program that relies heavily on Cstructures for it's data types. I have examples of reading and writing those structures which I need to obfuscate because I didn't develop them and don't own them, but for example given the following generic structure whose variable names have been change to protect the innocent.
    Code:
    typedef struct {
    int	  i1;
    int	  i2;
    int	  i3;
    int	  i4;
    int	  i5;
    int	  i6;
    int	  i7;
    int	  i8;
    int	  i9;
    double   d1, d2, d3;
    double   d4, d5, d6;
    double   d7;
    int	  i10;
    int	  i11;
    double   d8;
    char	 s[260];
    } StructName;
    I use a format string that looks like
    Code:
     format='iiiiiiiiidddddddiid260s'
    Then use struct.pack() to convert it to binary which is written to an open file.
    Code:
     RawData=struct.pack(format,self.__i1,self.__i2,self.__i3,self.__i4,self.__i5,self.__i6,self.__i7,self.__i8,self.__i9,self.__d1,self.__d2,self.__d3,self.__d4,self.__d5,self.__d6,self.__d7,self.__i10,self.__i11,self.__d8,self.__s)
    OpenFile.write(RawData)
    OpenFile.flush()

    Comment

    • dshimer
      Recognized Expert New Member
      • Dec 2006
      • 136

      #3
      I should also probably mention that the whole "self.__" set of characters is because those parameters are in a object of the class defined to hold them. I have done the exact same thing without writing a class but using the same method. For example in one program I grab the filename of a file specified on the command line and pass it along with 4 integers for a structure that is defined as
      Code:
         typedef struct {
      	  char s[81];
      	  int  i1, i2;
      	  int  i3, i4;
         } StructName;
      using
      Code:
      format='81siiii'
      struct.pack(format,sys.argv[1]+'.ext',Int1,Int2,Int3,Int4)

      Comment

      • Pierpaolo
        New Member
        • Mar 2007
        • 5

        #4
        dshimer
        thank you very much.
        I'll try and see if I can make something with all the infos you kindly provided.
        I'll pop in again if I get to somewhere.
        Regards,
        Pier

        Comment

        • Pierpaolo
          New Member
          • Mar 2007
          • 5

          #5
          No dice,
          I think I am hopeless with this language. I can't see how to make the entry widget work.
          I am not able to experiment the struct stuff yet as I cannot get data read and updated from the entry widget. Nonetheless I have found some good examples on how to access date in an entry widget and treat them as strings as well as transform them in integers (or e.g. floats) using the int method.
          Any link to a basic tutorials with practical examples would be greatly appreciated.
          For those of good will here below is the link to the c... code I have written so far.

          Thanks again for any hint.
          Regards,
          Pier

          http://www.pastebin.ca/392463

          Comment

          • bartonc
            Recognized Expert Expert
            • Sep 2006
            • 6478

            #6
            Originally posted by Pierpaolo
            Hi everybody,
            first of all I'd like to say that I am a beginner with python so please be patience. I googled a lot before posting the following question.

            I am trying to port a small C code of mine which "talks" to a real-time kernel module to python.
            I need an easy way to set up a graphic interface therefore I am using tkinter.

            I need to send a C struct to /dev/rtf0:
            Code:
            typedef struct {
              enum etype command;
              int command_num;		/* comando n.            	               */
              int freq;			          /* frequenza fase rampa costante  */
              unsigned int steps_x;		/* step da fare		                        */
              unsigned int steps_y;
              unsigned int steps_z;
              unsigned int steps_a;
              unsigned char dir;	          /* byte con le direzioni x y z a         */
            } COMMAND_STRUCT;
            Could anyone please provide a way or a link to somewhere where I could find some example code for doing such thing (ie defining a python equivalent for struct)?

            I would also be grateful for links to sites with practical example of tkinter classes use.

            Thanks a lot for any help,
            Pier
            You can use the ctypes library to treat a dll just like any other module and conver py type to c types:
            For example, for a C library function that returns an error code:
            Code:
            import ctypes
            from ctypes import byref
            import numpy
            
            cbw = ctypes.windll.cbw32 # open CBW32.DLL
            
            def CHK(UDStat):
                """raise appropriate exception if error occurred"""
                if UDStat != NOERRORS:
                    raise UniversalLibraryError(UDStat)
            
            
            
            def cbAInScan(BoardNum, LowChan, HighChan, Count,
                          Rate, Gain, ADData,
                          Options):
                """Scan range of A/D channels and store samples in an array
            
                Inputs
                ------
            
                BoardNum
                LowChan
                HighChan
                Count
                Rate
                Gain
                ADData -- modified to contain the sampled data
                Options
            
                Outputs
                -------
            
                Rate
            
                """
                Rate = ctypes.c_long(Rate)
                CHK_ARRAY( ADData, Count, numpy.int16 )
                ## here is the library (DLL) call ##
                CHK(cbw.cbAInScan(BoardNum, LowChan, HighChan, Count,
                                  byref(Rate), Gain, ADData.ctypes.data, Options))
                return Rate.value
            
            class PMD_Model(object):
                def __init__(self, master, BoardNum, Gain):
            
                    self.master = master
                    self.BoardNum = BoardNum
                    self.Gain = Gain
                    self.Rate = Rate
                    self.error = None
                    # this may look better as a module scope variable
            ##        self.Options = UL.BACKGROUND + UL.BLOCKIO + UL.CONTINUOUS
                    # after coresponding with Robert at Measurement Computing
                    self.Options = UL.BACKGROUND + UL.CONTINUOUS
            
                    self.ADData = numpy.zeros((Count,), dtype=numpy.int16)
            
            
                def StartScan(self):
                    try:
                        Rate = UL.cbAInScan(self.BoardNum, LowChan, HighChan, Count,
                                            self.Rate, self.Gain, self.ADData, self.Options)
                        self.master.write("Scan Rate = %d, Count = %d" % (Rate, Count))
                        self.error = None
                    except UL.UniversalLibraryError:
                        self.error = self.Errors()
            Note that these are snippets and NOT working code!

            Comment

            • Pierpaolo
              New Member
              • Mar 2007
              • 5

              #7
              bartonc:
              thanks for the reply. Alas I get the:
              ImportError: No module named ctypes
              message when I try and import ctypes module.
              I noticed references to win.dll.... As I am on a linux box could this be the problem?

              dshimer:
              the module that is supposed to receive the struct packed is whether deaf to python data or nothing is dispatched. I am not sure though about the format structure I provided to the struct.pack method.
              http://www.pastebin.ca/396387

              Thanks a lot for any help,
              Pier

              Comment

              Working...