Example #1
0
 def test_open_unicode(self):
     # Ensure passing unicode doesn't raise UnicodeEncodeError
     import posix
     try:
         posix.open(u"ą", posix.O_WRONLY)
     except OSError:
         pass
Example #2
0
 def test_rename_at_close_correct_read(self):
     firstFileFd = posix.open("mount/file1", posix.O_RDONLY)
     secondFileFd = posix.open("mount/file2", posix.O_RDONLY)
     for i in range(1000):
         position = random.randint(0, 10000)
         size = random.randint(1, 10000)
         posix.lseek(firstFileFd,position, 0)
         posix.lseek(secondFileFd, position, 0)
         posix.read(firstFileFd, size)
         posix.read(secondFileFd, size)
     posix.close(firstFileFd)
     posix.close(secondFileFd)
     posix.rename("mount/file2", "mount/file3")
     posix.rename("mount/file1","mount/file2")
     self.assertTrue(open("mount/file2").read()== open("src/file2").read())
Example #3
0
        def do_acquire(self, waitflag=False):
            locked = False

            if waitflag:
                blockflag = 0
            else:
                blockflag = fcntl.LOCK_NB

            self.fd = posix.open(self.fn, O_CREAT | O_RDWR, 0600)
            try:
                fcntl.flock(self.fd, fcntl.LOCK_EX|blockflag)
                # locked it
                try:
                    posix.ftruncate(self.fd, 0)
                    posix.write(self.fd, `os.getpid()` + '\n')
                    locked = True
                except:
                    self.do_release()
                    raise
            except IOError, x:
                if x.errno == errno.EWOULDBLOCK:
                    # failed to lock
                    posix.close(self.fd)
                    del self.fd
                else:
                    raise
Example #4
0
    def __init__(self, device = '/dev/spidev0.0', delay = 40, speed = 200000, bits = 8,Port=None,Server=None):
        """
        @param device Any SPI-Bus device in /dev, default /dev/spidev0.0
        @param delay SPI Bus delay between transactions in ms, default 0
        @param speed Set the Bus Speed (Obsolete)
        @param bits Number of bits in a data word, default = 8
        @param Port Default=None if set to an Integer this will be the TCP/IP port to listen on.
        @param Server Default=None if set to a string e.g. '192.168.200.137' the bus listening on that address/port combination will be connected to.

        If you Init an SPIBus like s = SPI(Port=50000) it wil listen to connections from a remote bw_library
        on any other computer a bw_library installation can make use of tcp communications like the SPI bus is connected to the local machine.

        Netbus = SPI(Server= '192.168.200.1',port=50000)
        In this case the device parameter is ignored.
        """
        self.Port = Port
        self.Server=Server
        if self.Server != None:
            self.Transaction=self._NetTransaction
        else:
            if self.Port != None: # Init Server Thread
                self.ServerThread = threading.Thread(target=self.ListenerTread)
                self.ServerThread.start()
            self.Bits = c_uint8(bits)
            self.Speed = self.WriteSpeed
            self.Delay = c_uint16(delay)
            self.Device = device
            self.File = posix.open(self.Device, posix.O_RDWR)
            self.SetBits()
            self.SetSpeed()
Example #5
0
 def test_randomAccessToFile(self):
     position = 0
     size = 0
     srcFileFd = posix.open("src/file1", posix.O_RDONLY)
     mountFileFd = posix.open("mount/file1", posix.O_RDONLY)
     for i in range(10000):
         position = random.randint(0, 10000)
         size = random.randint(1, 10000)
         posix.lseek(srcFileFd,position, 0)
         posix.lseek(mountFileFd, position, 0)
         if (posix.read(srcFileFd,size) !=  posix.read(mountFileFd, size)):
             posix.close(srcFileFd)
             posix.close(mountFileFd)
             self.assertTrue(False)
     posix.close(srcFileFd)
     posix.close(mountFileFd)
def init(init_board=True):
    """Initialises the PiFace Digital board"""
    global spidev_fd
    spidev_fd = posix.open(SPIDEV, posix.O_RDWR)

    if init_board:
         # set up each board
        ioconfig = BANK_OFF | INT_MIRROR_OFF | SEQOP_ON | DISSLW_OFF | \
            HAEN_ON | ODR_OFF | INTPOL_LOW

        pfd_detected = False

        for board_index in range(MAX_BOARDS):
            write(ioconfig, IOCON, board_index)  # configure

            if not pfd_detected and read(IOCON, board_index) == ioconfig:
                pfd_detected = True

            write(0, GPIOA, board_index)  # clear port A
            write(0, IODIRA, board_index)  # set port A as outputs
            write(0xff, IODIRB, board_index)  # set port B as inputs
            write(0xff, GPPUB, board_index)  # set port B pullups on

        if not pfd_detected:
            raise NoPiFaceDigitalDetectedError(
                "There was no PiFace Digital board detected!")
Example #7
0
def init(bus=0, chip_select=0):
    """Initialises the PiFace Digital board"""
    global spidev_fd
    spidev_fd = posix.open(
        "%s%d.%d" % (SPIDEV, bus, chip_select),
        posix.O_RDWR
    )
Example #8
0
 def open_fd(self, spi_device):
     try:
         self.fd = posix.open(spi_device, posix.O_RDWR)
     except OSError as e:
         raise SPIInitError(
             "I can't see %s. Have you enabled the SPI module? (%s)"
             % (spi_device, SPI_HELP_LINK)
         )  # from e  # from is only available in Python 3
 def open(self):
     """Opens the SPI device file descriptor."""
     try:
         self.fd = posix.open(self.spi_device_string, posix.O_RDWR)
     except OSError as e:
         raise SPIInitError(
             "I can't see %s. Have you enabled the SPI module? (%s)"
             % (spi_device_string, SPI_HELP)
         )  # from e  # from is only available in Python 3
Example #10
0
    def open(self, extra_open_flags=0):
        """Opens the bus device.

        Arguments:
        extra_open_flags -- extra flags passed to posix.open when
                            opening the I2C bus device file (default 0;
                            e.g. no extra flags).
        """
        self.fd = posix.open("/dev/i2c-{}".format(self.bus),
                             posix.O_RDWR | extra_open_flags)
Example #11
0
 def __init__(self, chip_select, bus=0):
     """Opens the SPI device.
     
     Arguments:
     chip_select -- the SPI chip select line to use. The Raspberry Pi
                    only has two chip select lines, numbered 0 and 1.
     bus         -- the number of the bus (default 0, the only SPI bus
                    on the Raspberry Pi).
     """
     self.fd = posix.open("/dev/spidev%i.%i"%(bus,chip_select), posix.O_RDWR)
Example #12
0
 def __init__(self, n=default_bus, extra_open_flags=0):
     """Opens the bus device.
     
     Arguments:
     n                -- the number of the bus (default is
                         the bus on the Raspberry Pi accessible
                         via the header pins).
     extra_open_flags -- extra flags passed to posix.open when 
                         opening the I2C bus device file (default 0; 
                         e.g. no extra flags).
     """
     self.fd = posix.open("/dev/i2c-%i"%n, posix.O_RDWR|extra_open_flags)
Example #13
0
    def test_rename_folder_correct_read(self):
        os.mkdir("src/folder1")
        os.mkdir("src/folder2")
        os.system("cp src/file1 src/folder1/file") 
        os.system("cp src/file2 src/folder2/file") 


        firstFileFd = posix.open("mount/folder1/file", posix.O_RDONLY)
        secondFileFd = posix.open("mount/folder2/file", posix.O_RDONLY)
        for i in range(1000):
            position = random.randint(0, 10000)
            size = random.randint(1, 10000)
            posix.lseek(firstFileFd,position, 0)
            posix.lseek(secondFileFd, position, 0)
            posix.read(firstFileFd, size)
            posix.read(secondFileFd, size)
        posix.rename("mount/folder2", "mount/folder3")
        posix.rename("mount/folder1","mount/folder2")
        posix.close(firstFileFd)
        posix.close(secondFileFd)
        self.assertTrue(open("mount/folder2/file").read()== open("src/folder2/file").read())
Example #14
0
    def make_tempfile(fn, pid):
        tfn = os.path.join(os.path.dirname(fn), 'shlock%d.tmp' % pid)

        errcount = 1000
        while 1:
            try:
                fd = posix.open(tfn, O_EXCL | O_CREAT | O_RDWR, 0600)
                posix.write(fd, '%d\n' % pid)
                posix.close(fd)

                return tfn
            except OSError, x:
                if (errcount > 0) and (x.errno == errno.EEXIST):
                    os.unlink(tfn)
                    errcount = errcount - 1
                else:
                    raise
def jog_i2c_write(addr, register, value, debug):
    import fcntl
    import posix

    n_i2c = 0
    f_i2c = posix.open("/dev/i2c-%i" % n_i2c, posix.O_RDWR)

    flags = I2C_M_WR
    buf = ctypes.create_string_buffer(2)
    buf[0] = chr(register)
    buf[1] = chr(value)
    msgs = I2cMsg(addr=addr, flags=flags, len=ctypes.sizeof(buf), buf=buf)
    msg_array, msg_count = i2c_ioctl_msg(msgs)
    io_i2c = I2cRdwrIoctlData(msgs=msg_array, nmsgs=msg_count)
    i2c_stat = fcntl.ioctl(f_i2c, I2C_RDWR, io_i2c)

    posix.close(f_i2c)
Example #16
0
def init(bus=0, chip_select=0):
    """Initialises the SPI device file descriptor.

    :param bus: The SPI device bus number
    :type bus: int
    :param chip_select: The SPI device chip_select number
    :param chip_select: int
    :raises: InitError
    """
    spi_device = "%s%d.%d" % (SPIDEV, bus, chip_select)
    global spidev_fd
    try:
        spidev_fd = posix.open(spi_device, posix.O_RDWR)
    except OSError as e:
        raise InitError(
            "I can't see %s. Have you enabled the SPI module? (%s)"
            % (spi_device, SPI_HELP_LINK)
        )  # from e  # from is only available in Python 3
Example #17
0
 def __init__(self, device = '/dev/spidev0.0', delay = 40, speed = 450000, bits = 8,Port=None,Server=None):
     """
         device = any SPI-Bus device in /dev, default /dev/spidev0.0
         delay  = SPI Bus delay between transactions in ms, default 0
         speed  = set the Bus Speed (Obsolete)
         bits   = Number of bits in a data word, default = 8
     """
     self.Port = Port
     self.Server=Server
     if self.Server != None:
         self.Transaction=self._NetTransaction
     else:
         if self.Port != None: # Init Server Thread
             self.ServerThread = threading.Thread(target=self.ListenerTread)
             self.ServerThread.start()
         self.Bits = c_uint8(bits)
         self.Speed = self.WriteSpeed
         self.Delay = c_uint16(delay)
         self.Device = device
         self.File = posix.open(self.Device, posix.O_RDWR)
         self.SetBits()
         self.SetSpeed()
Example #18
0
	def __init__(self,device,nleds):
		self.fd=None
		self.write_buffer=create_string_buffer(nleds*3*4)
		self.read_buffer=create_string_buffer(nleds*3*4)

			# speed_hz=5000000,
			# speed_hz=3500000,  # worked once
			# speed_hz=2550000,  # 1.6us @ 4bit per bit
			# speed_hz=3500000,    # 1.2us @ 4bit per bit
		self.ioctl_arg = spi_ioc_transfer(
			tx_buf=addressof(self.write_buffer),
			rx_buf=addressof(self.read_buffer),
			len=1,
			delay_usecs=0,
			speed_hz=3500000,
			bits_per_word=8,
			cs_change = 0,
		)

		self.fd = posix.open(device, posix.O_RDWR)
		ioctl(self.fd, SPI_IOC_RD_MODE, " ")
		ioctl(self.fd, SPI_IOC_WR_MODE, struct.pack('I',0))
def main():
    # stdin is dup'ed to make sure nothing unexpected is written or read from the
    # stream. CellAppMgr is informed of the appropriate file descriptor via its
    # command line arguments.
    fd = posix.dup(0)

    nullFD = posix.open("/dev/null", posix.O_RDWR)
    posix.dup2(nullFD, 0)
    posix.dup2(nullFD, 1)
    posix.dup2(nullFD, 2)

    connection = Connection(fd)

    peerString = connection.socket.getpeername()[0]

    syslog.syslog("Got connection from " + peerString)

    versionNumber, = connection.getStruct("=i")

    if versionNumber not in VERSION_NUMBERS:
        connection.sendMsg(
          "ERROR: Invalid local CellAppMgr version. " \
          "Expected versions %s. Got %d\n" % \
          (str( VERSION_NUMBERS ), versionNumber) )
        sys.exit(0)

    accountNameLen, = connection.getStruct("=i")
    accountName = connection.receive(accountNameLen)

    # Make a unique token that will be sent to the front-end, signed and then
    # returned.
    sentToken = str(time.time()) + str(random.random()) + peerString

    connection.socket.send(
        struct.pack("=Hi", MSG_INIT, len(sentToken)) + sentToken)

    signedTokenLen, = connection.getStruct("=i")
    signedToken = connection.receive(signedTokenLen)

    isVerified, receivedToken, decryptData = verifyToken(signedToken)

    if receivedToken != sentToken:
        syslog.syslog("Authentication failed '%s' at '%s')" %
                      (accountName, peerString))

    if not isVerified:
        connection.sendMsg("ERROR: Authentication failed for GPG key '%s'.\n" %
                           accountName)
        connection.sendMsg(
            "ERROR: Make sure the public GPG key is registered with BigWorld.\n"
        )
        connection.sendMsg(
            "ERROR: To register a key, please contact [email protected]\n"
        )
        syslog.syslog("Authentication failed for '%s' at '%s')" %
                      (accountName, peerString))
        sys.exit(0)

    remoteUID, remotePID, remoteViewerPort = \
     connection.getStruct( "=iiH" )

    syslogPrefix = "CellAppMgr:%s:%s:%d:%d" % \
      (accountName, connection.socket.getpeername()[0],
       remoteUID, remotePID )
    syslog.openlog(syslogPrefix)
    syslog.syslog("Started")
    for line in decryptData.split("\n"):
        syslog.syslog(line)

    # Read the command line arguments
    args = []
    argLen = 1
    while argLen:
        argLen, = connection.getStruct("=i")
        if argLen:
            arg = connection.receive(argLen)
            args.append(arg)

    try:
        # This affects where core files are created.
        os.chdir(os.path.dirname(EXE_PATH))
    except Exception, e:
        pass
Example #20
0
	def open(self, name, mode):
		self.fd = posix.open(name, mode)
		return self
Example #21
0
    def __init__(self, i2cbus=1):
        self._fd = posix.open("/dev/i2c-%d" % i2cbus, posix.O_RDWR)

        ioctl(self._fd, self.I2C_SLAVE, self.I2C_ADDR)
Example #22
0
import posix
import sys

# read the contents of this file
fd = posix.open(__file__, posix.O_RDONLY)
data = posix.read(fd, 1024)
posix.close(fd)
print('the file\'s read size is %d bytes' % len(data))

# check that the file's stat shows the correct size
st = posix.stat(__file__)
print('the file\'s stat size is %d bytes' % st.st_size)
def main():
    Raise=False
    try:
        fd=posix.open("/dev/serial0", posix.O_RDWR |\
                      posix.O_NOCTTY | posix.O_NDELAY)
    except:
        Raise=True

    if Raise:
        raise Exception("UART busy."
                        " Try /dev/serial1, /dev/ttyS0,"
                        " /dev/ttyAMA0.")

    options=termios.tcgetattr(fd)
    options[0]=termios.IGNPAR
    options[1]=0
    options[2]=termios.B9600 |\
               termios.CS8 |\
               termios.CLOCAL |\
               termios.CREAD
    options[3]=0
    
    termios.tcflush(fd,termios.TCIFLUSH)
    termios.tcsetattr(fd,termios.TCSANOW,options)

    while  True:
        message="Consumer :"
        print(message,end="\r"+message)

        data=None
        message=None
 
        while data is None:

            try:
                data=bytearray(posix.read(fd,128))
            except:
                data=None
                time.sleep(DELAY)
                continue
            
            if message is not None and data is None:
                break

            if message is None:
                message=data
            else:
                message+=data
                
            time.sleep(DELAY)


        new=""
        for i in message:
            new+=chr(i)
                    
        message=new
            
        print('"'+message+'"')

    posix.close(fd)
Example #24
0
 def __init__(self, device, cs):
     self._cs = Pin(cs, 'HIGH')
     self.fd = posix.open(device, posix.O_RDWR)
     ioctl(self.fd, SPI_IOC_RD_MODE, " ")
     ioctl(self.fd, SPI_IOC_WR_MODE, struct.pack('I',0))
Example #25
0
    def _ApplyRedirect(self, r, waiter):
        ok = True

        if r.tag == redirect_e.PathRedirect:
            if r.op_id in (Id.Redir_Great, Id.Redir_AndGreat):  # >   &>
                # NOTE: This is different than >| because it respects noclobber, but
                # that option is almost never used.  See test/wild.sh.
                mode = posix.O_CREAT | posix.O_WRONLY | posix.O_TRUNC
            elif r.op_id == Id.Redir_Clobber:  # >|
                mode = posix.O_CREAT | posix.O_WRONLY | posix.O_TRUNC
            elif r.op_id in (Id.Redir_DGreat, Id.Redir_AndDGreat):  # >>   &>>
                mode = posix.O_CREAT | posix.O_WRONLY | posix.O_APPEND
            elif r.op_id == Id.Redir_Less:  # <
                mode = posix.O_RDONLY
            else:
                raise NotImplementedError(r.op_id)

            # NOTE: 0666 is affected by umask, all shells use it.
            try:
                target_fd = posix.open(r.filename, mode, 0o666)
            except OSError as e:
                util.error("Can't open %r: %s", r.filename,
                           posix.strerror(e.errno))
                return False

            # Apply redirect
            if not self._PushDup(target_fd, r.fd):
                ok = False

            # Now handle the extra redirects for aliases &> and &>>.
            #
            # We can rewrite
            #   stdout_stderr.py &> out-err.txt
            # as
            #   stdout_stderr.py > out-err.txt 2>&1
            #
            # And rewrite
            #   stdout_stderr.py 3&> out-err.txt
            # as
            #   stdout_stderr.py 3> out-err.txt 2>&3
            if ok:
                if r.op_id == Id.Redir_AndGreat:
                    if not self._PushDup(r.fd, 2):
                        ok = False
                elif r.op_id == Id.Redir_AndDGreat:
                    if not self._PushDup(r.fd, 2):
                        ok = False

            posix.close(target_fd)  # We already made a copy of it.
            # I don't think we need to close(0) because it will be restored from its
            # saved position (10), which closes it.
            #self._PushClose(r.fd)

        elif r.tag == redirect_e.DescRedirect:  # e.g. echo hi 1>&2

            if r.op_id == Id.Redir_GreatAnd:  # 1>&2
                if not self._PushDup(r.target_fd, r.fd):
                    ok = False
            elif r.op_id == Id.Redir_LessAnd:  # 0<&5
                # The only difference between >& and <& is the default file
                # descriptor argument.
                if not self._PushDup(r.target_fd, r.fd):
                    ok = False
            else:
                raise NotImplementedError

        elif r.tag == redirect_e.HereRedirect:
            # NOTE: Do these descriptors have to be moved out of the range 0-9?
            read_fd, write_fd = posix.pipe()

            if not self._PushDup(read_fd, r.fd):  # stdin is now the pipe
                ok = False

            # We can't close like we do in the filename case above?  The writer can
            # get a "broken pipe".
            self._PushClose(read_fd)

            thunk = _HereDocWriterThunk(write_fd, r.body)

            # TODO: Use PIPE_SIZE to save a process in the case of small here docs,
            # which are the common case.  (dash does this.)
            start_process = True
            #start_process = False

            if start_process:
                here_proc = Process(thunk)

                # NOTE: we could close the read pipe here, but it doesn't really
                # matter because we control the code.
                # here_proc.StateChange()
                pid = here_proc.Start()
                # no-op callback
                waiter.Register(pid, here_proc.WhenDone)
                #log('Started %s as %d', here_proc, pid)
                self._PushWait(here_proc, waiter)

                # Now that we've started the child, close it in the parent.
                posix.close(write_fd)

            else:
                posix.write(write_fd, r.body)
                posix.close(write_fd)

        return ok
Example #26
0
 def __init__(self, n=0):
     self.fd = posix.open("/dev/i2c-%i"%n, posix.O_RDWR)
Example #27
0
        len = length,
        speed_hz = 500000,
        bits_per_word = 8
        );
    fcntl.ioctl(fd, 1075866368, transfer)

def calcOutput(val):
    spi_max_speed = 5 * 100000
    v_ref = 2200
    Bits = 2**16
    Resolution = (v_ref* 1000/ Bits)
    D_val16 = (val * 1000) / Resolution
    byte0 = 0x30 | (D_val16 & 0xF000) >> 12
    byte1 = (D_val16 & 0x0FF0) >> 4
    byte2 = (D_val16 & 0x000F) << 4
    return([byte0,byte1,byte2])

if __name__ == "__main__":
    try:
        while(True):
            output_set_mv = input('Enter set voltage 0-2200 (mV): ')
            spi_device = "%s%d.%d" % ('/dev/spidev', 0, 1)
            fd = posix.open(spi_device, posix.O_RDWR)
            write_to_ioctl([0x30, 0x0, 0x0])
            sleep(1)
            write_dac = calcOutput(output_set_mv)
            write_to_ioctl(write_dac)	
            print "done"
    
    except (KeyboardInterrupt, Exception) as e:
        print(e)
Example #28
0
def skip_test_alarm():
    # (tfel): this test is very brittle, because it is supposed to work with our
    # first, very primitive implementation of signal handlers, which does not
    # allow Python code to run in the handler. So we rely on a side-effect on an
    # open file descriptor instead.
    try:
        import _signal
    except ImportError:
        import signal as _signal
    import posix
    import time
    import sys

    # first, we start opening files until the fd is the same as SIGALRM
    fds = []
    dupd_fd = None
    fd = None

    try:
        fd = posix.open(__file__, posix.O_RDONLY)
        while fd < _signal.SIGALRM:
            fds.append(fd)
            fd = posix.open(__file__, posix.O_RDONLY)

        if fd > _signal.SIGALRM:
            dupd_fd = posix.dup(_signal.SIGALRM)
            posix.close(_signal.SIGALRM)
            fd = posix.open(__file__, posix.O_RDONLY)

        # close the unneeded fds
        for oldfd in fds:
            posix.close(oldfd)

        assert fd == _signal.SIGALRM, "fd not equal to SIGALRM"

        # temporary: graalpython doesn't check the argcount for the handler atm
        if sys.implementation.name == "graalpython":
            handler = posix.close
        else:
            handler = lambda s, f: posix.close(s)

        oldhandler = _signal.signal(_signal.SIGALRM, handler)
        assert oldhandler == _signal.SIG_DFL, "oldhandler != SIG_DFL"
        assert _signal.getsignal(
            _signal.SIGALRM) is handler, "getsignal handler != handler"

        # schedule the alarm signal, that will trigger the handler, which
        # will in turn close our file
        _signal.alarm(1)

        # wait for the signal to come in and be handled
        time.sleep(1.5)

        # check for the side-effect
        try:
            posix.read(fd, 1)
        except OSError:
            assert True
        else:
            assert False, "file is still open"
    finally:
        if dupd_fd is not None:
            try:
                posix.close(fd)
            except OSError:
                pass
            posix.dup(dupd_fd)  # duplicates back into just free'd fd
Example #29
0
 def __init__(self, i2cbus=1):
     self._i2cbus = i2cbus
     self.fd = posix.open('/dev/i2c-%d' % self._i2cbus, posix.O_RDWR)
Example #30
0
 def __init__(self, n=0):
     self.fd = posix.open("/dev/i2c-%i" % n, posix.O_RDWR)
Example #31
0
	def __init__(self,device):
		self.fd = posix.open(device, posix.O_RDWR)
		ioctl(self.fd, SPI_IOC_RD_MODE, " ")
		ioctl(self.fd, SPI_IOC_WR_MODE, struct.pack('I',0))
Example #32
0
read_buf = create_string_buffer(50)

ioctl_arg = spi_ioc_transfer(
    tx_buf=addressof(write_buf),
    rx_buf=addressof(read_buf),
    len=2,
    delay_usecs=0,
    speed_hz=5000000,
    bits_per_word=8,
    cs_change=0,
)

bits = spi_ioc_transfer(7)

device_name = "/dev/spidev32766.0"
adc_channel = 5
print "Read from %s on a/d channel %d" % (device_name, adc_channel)

fd = posix.open(device_name, posix.O_RDWR)
ioctl(fd, SPI_IOC_RD_MODE, " ")
ioctl(fd, SPI_IOC_WR_MODE, struct.pack('I', 0))

#Write the A/D channel address and read the value
write_buf[0] = chr(adc_channel * 8)
write_buf[1] = chr(0x00)

while True:
    ioctl(fd, SPI_IOC_MESSAGE(1), addressof(ioctl_arg))
    print "Value %d" % (ord(read_buf[1]) * 256 + ord(read_buf[0]))
    time.sleep(1)
Example #33
0
  def __init__(self, i2cbus = 1):
    self._i2cbus = i2cbus #atributo
    self._fd = posix.open("/dev/i2c-%d" % self._i2cbus, posix.O_RDWR) #i2c-1
    print ("fd:"+ str(self._fd))

    ioctl(self._fd, AM2320.I2C_SLAVE, AM2320.I2C_ADDR)
Example #34
0
 def open(self, name, mode):
     self.fd = posix.open(name, mode)
     return self
Example #35
0
    def start(self):
        if self._monitoring:
            if self._mode == MonitorService.MODE_FIFO:
                # publish fifo
                self._tmpdir = tempfile.mkdtemp()
                self._filename = os.path.join(self._tmpdir, 'siis.stream')

                try:
                    os.mkfifo(self._filename, 0o600)
                except OSError as e:
                    logger.error("Failed to create monitor write FIFO: %s" %
                                 repr(e))
                    os.rmdir(self._tmpdir)
                    self._filename = None
                else:
                    self._fifo = posix.open(self._filename, posix.O_NONBLOCK
                                            | posix.O_RDWR)  # posix.O_WRONLY

                # read command fifo
                self._filename_read = os.path.join(self._tmpdir, 'siis.rpc')

                try:
                    os.mkfifo(self._filename_read, 0o600)
                except OSError as e:
                    logger.error("Failed to create monitor read FIFO: %s" %
                                 repr(e))
                    os.rmdir(self._tmpdir)

                    # close the write fifo
                    os.remove(self._filename)
                    posix.close(self._fifo)
                    self._fifo = -1
                    self._filename = None
                    self._filename_read = None
                else:
                    self._fifo_read = posix.open(self._filename_read,
                                                 posix.O_NONBLOCK)

                if self._fifo and self._fifo_read:
                    self._running = True
                    self._thread = threading.Thread(name="monitor",
                                                    target=self.run_fifo)
                    self._thread.start()

            elif self._mode == MonitorService.MODE_HTTP_WEBSOCKET:
                # logger.startLogging(sys.stdout)

                self._factory = WebSocketServerFactory(
                    u"ws://%s:%i" % (self._host, self._port))
                self._factory.protocol = ServerProtocol
                # self._factory.setProtocolOptions(maxConnections=2)

                # self._loop = asyncio.get_event_loop()
                # coro = self._loop.create_server(self._factory, self._host, self._port)
                # self._server = self._loop.run_until_complete(coro)

                # reactor.listenTCP(self._port, self._factory)
                # if not reactor.running:
                #     reactor.run()

                self._running = True
                self._thread = threading.Thread(name="monitor",
                                                target=self.run_autobahn)
                self._thread.start()
Example #36
0
 def __init__(self, bus):
     self.fd = posix.open('/dev/i2c-%i' % bus, posix.O_RDWR)
Example #37
0
 def test_dont_close_fd_if_dir_check_fails_in_fdopen(self):
     import posix
     fd = posix.open('/', posix.O_RDONLY)
     raises(IOError, posix.fdopen, fd)
     posix.close(fd)
Example #38
0
 def __init__(self, name):
     if not name.startswith('sg:'):
         raise ValueError(f"Not a SG target: {name}")
     self.fd = posix.open(name[3:], posix.O_RDWR)
Example #39
0
    def __init__(self, file_path, addr):
        self.fd = posix.open(file_path, posix.O_RDWR)

        if ioctl(self.fd, I2C_SLAVE, addr) != 0:
            raise Exception() #TODO: add more exceptions.
Example #40
0
    def __init__(self, file_path, addr):
        self.fd = posix.open(file_path, posix.O_RDWR)

        if ioctl(self.fd, I2C_SLAVE, addr) != 0:
            raise Exception()  #TODO: add more exceptions.
Example #41
0
 def __init__(self, bus):
     self.fd = posix.open("/dev/i2c-{}".format(bus), posix.O_RDWR)
     self.addr = None
Example #42
0
def open_tty(path, flags, mode, speed=None):
    fd = posix.open(path, flags, mode)
    set_raw_tty(fd, speed)
    return fd
Example #43
0
import fcntl
Example #44
0
		tx_buf=addressof(write_buf),
		rx_buf=addressof(read_buf),
		len=2,
		delay_usecs=0,
		speed_hz=5000000,
		bits_per_word=8,
		cs_change = 0,
)

bits= spi_ioc_transfer(7)

device_name = "/dev/spidev32766.0"
adc_channel=5
print "Read from %s on a/d channel %d" % (device_name,adc_channel)


fd = posix.open(device_name, posix.O_RDWR)
ioctl(fd, SPI_IOC_RD_MODE, " ")
ioctl(fd, SPI_IOC_WR_MODE, struct.pack('I',0))

#Write the A/D channel address and read the value
write_buf[0]=chr(adc_channel*8)
write_buf[1]=chr(0x00)

while True:
	ioctl(fd, SPI_IOC_MESSAGE(1), addressof(ioctl_arg))
	print "Value %d" % (ord(read_buf[1])*256+ord(read_buf[0]))
	time.sleep(1)
	
	
Example #45
0
 def test_dont_close_fd_if_dir_check_fails_in_fdopen(self):
     import posix
     fd = posix.open('/', posix.O_RDONLY)
     raises(IOError, posix.fdopen, fd)
     posix.close(fd)
Example #46
0
def verify_file_accessibility():
    handle = posix.open("Alphabets", 2)
    if not handle > 0:
        assert "File not accessible"
    else:
        print("File accessibility validated")
Example #47
0
 def __init__(self, device):
     self.fd = posix.open(device, posix.O_RDWR)
     ioctl(self.fd, SPI_IOC_RD_MODE, " ")
     ioctl(self.fd, SPI_IOC_WR_MODE, struct.pack('I', 0))
Example #48
0
 def __init__(self, chip_select, bus):
     self.fd = posix.open("/dev/spidev%i.%i"%(bus,chip_select), posix.O_RDWR)