import win32file, sys

hdevice = win32file.CreateFile(
    "\\\\.\\SendCallout", win32file.GENERIC_READ | win32file.GENERIC_WRITE,
    win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, 0, 0)
(resultCode, resultBuffer) = win32file.ReadFile(hdevice, 100000, None)

for i in range(len(resultBuffer)):
    b = resultBuffer[i]
    print(hex(b), "\t", end="")

if len(sys.argv) > 1:
    actionString = sys.argv[1]
else:
    actionString = "Block"

result = win32file.WriteFile(hdevice, bytearray(actionString,
                                                encoding="ascii"), None)
print(result)
Exemple #2
0
            print("symbolic link has already been created")

        # wait a bit to ensure that symbolic links have been created
        time.sleep(1)

        object_class = ROSMessagePublisher()

        rospy.init_node('ros_publisher', anonymous=True)
        pipe = create_pipe("ROS_messages")
        print("waiting for client from FarmSim19")
        win32pipe.ConnectNamedPipe(pipe, None)
        print("got client from game!!")

        while not rospy.is_shutdown():
            read_sz = 64 * 1024
            resp = win32file.ReadFile(pipe, read_sz)

            #  convert json data from lua to ros message (data read from the pipe is in bytes: need to convert to string)

            msg_list = resp[1].decode("utf-8").split("\n")
            if msg_list[0] == "rosgraph_msgs/Clock":
                sim_time_msg = json_message_converter.convert_json_to_ros_message(
                    'rosgraph_msgs/Clock', msg_list[1])
                object_class.pub_sim.publish(sim_time_msg)

            elif msg_list[0] == "nav_msgs/Odometry":
                odom_msg = json_message_converter.convert_json_to_ros_message(
                    'nav_msgs/Odometry', msg_list[1])
                object_class.pub_odom.publish(odom_msg)

            elif msg_list[0] == "sensor_msgs/LaserScan":
Exemple #3
0
 def recv(self, max_length):
     (err, data) = win32file.ReadFile(self.handle, max_length)
     if err:
         raise IOError(err)
     return data
Exemple #4
0
    def read(self, offset, length):
        win32file.SetFilePointer(self.fhandle, offset, 0)
        _, data = win32file.ReadFile(self.fhandle, length)

        return data
Exemple #5
0
##        subprocess.check_call('python waveopt_interface.py --slm_width 192 --slm_height 144 --plot True --pipe_in_handle \\\\.\\pipe\\LABVIEW_OUT --pipe_out_handle \\\\.\\pipe\\LABVIEW_IN', stderr=f)
####        df = Popen(["ls", "/home/non"], stdout=subprocess.PIPE)
##        p = subprocess.Popen('python waveopt_interface.py --slm_width 192 --slm_height 144 --plot True --pipe_in_handle \\\\.\\pipe\\LABVIEW_OUT --pipe_out_handle \\\\.\\pipe\\LABVIEW_IN',
##                     creationflags=CREATE_NEW_CONSOLE, stdout=subprocess.PIPE)
##
##        output, err = p.communicate()
##    except subprocess.CalledProcessError as e:
##        print(e)
##        exit(1)

print('...done')
for i in range(30000000):
    wp.ConnectNamedPipe(pipe_in, None)
    wp.ConnectNamedPipe(pipe_out, None)

    read_pipe = wf.ReadFile(pipe_in, get_buffer_size(pipe_in,
                                                     NUM_BYTES_BUFFER))
    read_array = list(read_pipe[1])
    print('pipe read...')

    ### Plot Masks after reading ####
    ##    plt.matshow(np.asarray(read_array).reshape(l,k))
    ##    plt.show()

    out_field = trans(I * np.exp(1j * phdist[read_array]), tmat)[:5]
    ##    print(out_field)
    ##    out_field = read_array
    data = bytearray(
        len(bytearray(out_field)).to_bytes(
            NUM_BYTES_BUFFER, byteorder='big')) + bytearray(out_field)
    wf.WriteFile(pipe_out, data)
Exemple #6
0
 def recv(self, buff_size):
     _, data = win32file.ReadFile(self.handle, buff_size)
     return data
 def get_buffer_size(self):
     """Return buffer size as int."""
     buffer_size = int.from_bytes(wf.ReadFile(self.pipe_handle_in, self.num_bytes_buffer)[1], byteorder='little', signed=False)
     return buffer_size
Exemple #8
0
 def read_pipe(self, size):
     return win32file.ReadFile(self.read_handle, size, None)[1]
# versione named pipe per VirtualBox
ser = win32file.CreateFile("\\\\.\\pipe\\planetario",
                           win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0,
                           None, win32file.OPEN_EXISTING, 0, None)
if ser == win32file.INVALID_HANDLE_VALUE:
    print "can't open named pipe"
    exit(-1)
#ser = serial.Serial(port='COM1', baudrate=4800, timeout=0)

# loop di aggiornamento
while True:
    rate(100)  # controllori girano a 32.768 ms (circa 30.5 Hz)
    # verifica che ci siano abbastanza dati nel buffer seriale
    (buffer, bytesToRead, result) = win32pipe.PeekNamedPipe(ser, 1000)
    if result and bytesToRead + len(_ser_buffer) >= 5:
        (result, data) = win32file.ReadFile(ser, bytesToRead)
        if not result and len(data):
            if dbg_verbose:
                for c in data:
                    print "%02X " % (ord(c), ),
            # appendi nuovi dati da seriale
            _ser_buffer += data

            # consuma tutti i dati disponibili
            isData = True
            while (isData):
                (isData, response) = simpla_msg()
                if isData:
                    if len(response):
                        # rispondi
                        #ser.write(response[1])
Exemple #10
0
 def _recv_into_py2(self, buf, nbytes):
     err, data = win32file.ReadFile(self._handle, nbytes or len(buf))
     n = len(data)
     buf[:n] = data
     return n
Exemple #11
0
    def _ReadRandom(self, offset, length):
        win32file.SetFilePointer(self.fd, offset, 0)

        _, data = win32file.ReadFile(self.fd, length)

        return data
Exemple #12
0
 def recv(self, bufsize, flags=0):
     err, data = win32file.ReadFile(self._handle, bufsize)
     return data
Exemple #13
0
    def communication_win(self, is_check):
        # event, overlapped struct for the pipe or tunnel
        hEvent_pipe = win32event.CreateEvent(None, 0, 0,
                                             None)  # for reading from the pipe
        overlapped_pipe = pywintypes.OVERLAPPED()
        overlapped_pipe.hEvent = hEvent_pipe

        # event, overlapped struct for the pipe or tunnel
        hEvent_rdp = win32event.CreateEvent(None, 0, 0,
                                            None)  # for reading from the pipe
        overlapped_rdp = pywintypes.OVERLAPPED()
        overlapped_rdp.hEvent = hEvent_rdp

        # buffer for the packets
        message_readfile_pipe = win32file.AllocateReadBuffer(4096)
        message_readfile_rdp = win32file.AllocateReadBuffer(4096)

        # showing if we already async reading or not
        read_pipe = True
        read_rdp = False
        first_run = True

        while not self._stop:
            try:
                if not self.tunnel_r:
                    # user is not authenticated yet, so there is no pipe
                    # only checking the socket for data
                    hr, _ = win32file.ReadFile(self.comms_socket,
                                               message_readfile_rdp,
                                               overlapped_rdp)
                    if (hr == winerror.ERROR_IO_PENDING):
                        rc = win32event.WaitForSingleObject(
                            hEvent_rdp, int(self.timeout * 1000))
                        read_rdp = True
                    else:
                        raise
                        rc = 0
                else:
                    # client mode so we have the socket and tunnel as well
                    # or the client authenticated and the pipe was created
                    if read_pipe or first_run:
                        # no ReadFile was called before or finished, so we
                        # are calling it again
                        first_run = False
                        hr, _ = win32file.ReadFile(self.tunnel_r,
                                                   message_readfile_pipe,
                                                   overlapped_pipe)

                    if read_rdp:
                        # no ReadFile was called before or finished, so we
                        # are calling it again
                        hr, _ = win32file.ReadFile(self.comms_socket,
                                                   message_readfile_rdp,
                                                   overlapped_rdp)

                    if (hr == winerror.ERROR_IO_PENDING):
                        # well, this was an async read, so we need to wait
                        # until it happens
                        rc = win32event.WaitForMultipleObjects(
                            [hEvent_rdp, hEvent_pipe], 0,
                            int(self.timeout * 1000))
                        if rc == winerror.WAIT_TIMEOUT:
                            # timed out, just rerun and wait
                            continue
                    else:
                        if hr != 0:
                            common.internal_print(
                                "RDP ReadFile failed: {0}".format(hr), -1)
                            raise

                if rc < 0x80:  # STATUS_ABANDONED_WAIT_0
                    if rc == 0:
                        read_rdp = True
                        read_pipe = False
                        # socket got signalled
                        # skipping header (8):length of read
                        messages = self.recv(
                            message_readfile_rdp[8:overlapped_rdp.
                                                 InternalHigh])  # SLOW?
                        for message in messages:
                            # looping through the messages from socket
                            if len(message) == 0:
                                # this could happen when the socket died or
                                # partial message was read.
                                continue

                            if common.is_control_channel(message[0:1]):
                                # parse control messages
                                if self.controlchannel.handle_control_messages(
                                        self,
                                        message[len(common.CONTROL_CHANNEL_BYTE
                                                    ):], None):
                                    continue
                                else:
                                    # If the module is stopped right away, then
                                    # the channel will be closing down as well.
                                    # Because of the buffering the message will
                                    # not be sent. That is why we need to sleep
                                    time.sleep(0.5)
                                    self.stop()
                                    break

                            if self.authenticated:
                                try:
                                    # write packet to the tunnel
                                    self.packet_writer(
                                        message[len(common.CONTROL_CHANNEL_BYTE
                                                    ):])
                                except OSError as e:
                                    print(e)  # wut?
                                except Exception as e:
                                    if e.args[0] == 995:
                                        common.internal_print(
                                            "Interface disappered, exiting thread: {0}"
                                            .format(e), -1)
                                        self.stop()
                                        continue
                                    print(e)
                    if rc == 1:
                        read_rdp = False
                        read_pipe = True
                        # pipe/tunnel got signalled
                        if (overlapped_pipe.InternalHigh <
                                4) or (message_readfile_pipe[0:1] !=
                                       "\x45"):  #Only care about IPv4
                            # too small which should not happen or not IPv4, so we just drop it.
                            continue

                        # reading out the packet from the buffer and discarding the rest
                        readytogo = message_readfile_pipe[0:overlapped_pipe.
                                                          InternalHigh]
                        self.send(common.DATA_CHANNEL_BYTE, readytogo, None)

            except win32api.error as e:
                if e.args[0] == 233:
                    # No process is on the other end of the pipe.
                    self._stop = True
                    common.internal_print("Client disconnected from the pipe.",
                                          -1)
                    continue
                common.internal_print("RDP Exception: {0}".format(e), -1)

        self.cleanup()

        return True
 def HandleData(self):
     """
     This runs once a connection to the named pipe is made.  It receives the ir data and passes it to the plugins IRDecoder.
     """
     #if self.sentMessageOnce:
     #    eg.PrintNotice("MCE_Vista: Connected to MceIr pipe, started handling IR events")
     #    self.plugin.TriggerEvent("Connected")
     nMax = 2048
     self.result = []
     self.freqs = [0]
     self.readOvlap = win32file.OVERLAPPED()
     self.readOvlap.hEvent = win32event.CreateEvent(None, 0, 0, None)
     handles = [self.plugin.hFinishedEvent, self.readOvlap.hEvent]
     self.timeout = win32event.INFINITE
     while self.keepRunning:
         try:
             (hr, data) = win32file.ReadFile(self.file, nMax,
                                             self.readOvlap)
         except:
             win32file.CloseHandle(self.file)
             self.file = None
             break
         self.receivingTimeout = eg.scheduler.AddTask(
             0.3, self.SetReceiving, False)
         rc = win32event.WaitForMultipleObjects(handles, False,
                                                self.timeout)
         self.SetReceiving(True)
         if rc == win32event.WAIT_OBJECT_0:  #Finished event
             self.keepRunning = False
             break
         elif rc == win32event.WAIT_TIMEOUT:  #Learn timeout
             #eg.PrintNotice("LearnTimeout: Sending ir code %s"%str(self.result))
             self.learnDialog.GotCode(self.freqs, self.result)
             self.result = []
             self.timeout = win32event.INFINITE
             rc = win32event.WaitForMultipleObjects(handles, False,
                                                    self.timeout)
             if rc == win32event.WAIT_OBJECT_0:  #Finished event
                 self.keepRunning = False
                 break
         try:
             nGot = self.readOvlap.InternalHigh
             if nGot == 0:
                 continue
             if nGot % ptr_len == 1:  #Query result, not ir code data
                 if data[0] == "b".encode("ascii"):
                     self.deviceInfo = unpack_from(6 * ptr_fmt,
                                                   data[1:nGot])
                     win32event.SetEvent(self.deviceInfoEvent)
                 elif data[0] == "t".encode("ascii"):
                     win32event.SetEvent(self.deviceTestEvent)
                 continue
             #pull of the header data
             while nGot > 0:
                 header = unpack_from(3 * ptr_fmt, data)
                 if header[0] == 1 and header[2] > 0:
                     self.freqs.append(header[2])
                 dataEnd = nGot
                 if nGot > 100 + 3 * ptr_len:
                     dataEnd = 100 + 3 * ptr_len
                 nGot -= dataEnd
                 val_data = data[3 * ptr_len:dataEnd]
                 dataEnd = dataEnd - 3 * ptr_len
                 vals = unpack_from((dataEnd / 4) * "i", val_data)
                 data = data[100 + 3 * ptr_len:]
                 for i, v in enumerate(vals):
                     a = abs(v)
                     self.result.append(a)
                     if self.learnDialog is None:  #normal mode
                         if a > 6500:  #button held?
                             if self.CodeValid(self.result):
                                 #eg.PrintNotice("Sending ir code %s"%str(self.result))
                                 self.plugin.irDecoder.Decode(
                                     self.result, len(self.result))
                             self.result = []
                 if not self.learnDialog is None:  #learn mode
                     if header[0] == 1:  #one "learn" chunk
                         self.timeout = self.learnTimeout
         except:
             pass
     self.SetReceiving(False)
Exemple #15
0
def ReadPipe(pp,size=1024*4+1):
    CloseHandle(pp[1])
    ret=win32file.ReadFile(pp[0],size)
    CloseHandle(pp[0])
    return ret[1][1:]
 def parse_pipe_data(self):
     left, data = win32file.ReadFile(fileHandle, 4096)
     # print("DATA: ", data)
     first_split = data.decode().strip().split(",")
     string_vector = [first_split[0].strip().split(" ")[1], first_split[1].strip(), first_split[2].strip()]
     return [float(i) for i in string_vector]
Exemple #17
0
 def recvfrom(self, buff_size):
     response_code, data = win32file.ReadFile(self.handle, buff_size)
     return data, response_code
Exemple #18
0
 def get(self):
     return win32file.ReadFile(self.handle, 64*1024)[1]
Exemple #19
0
def demo():
    """
    Definition of buffer used with FSCTL_TXFS_CREATE_MINIVERSION:
    typedef struct _TXFS_CREATE_MINIVERSION_INFO{
        USHORT StructureVersion;
        USHORT StructureLength;
        ULONG BaseVersion;
        USHORT MiniVersion;}
    """
    buf_fmt = 'HHLH0L'  ## buffer size must include struct padding
    buf_size = struct.calcsize(buf_fmt)

    tempdir = win32api.GetTempPath()
    tempfile = win32api.GetTempFileName(tempdir, 'cft')[0]
    print("Demonstrating transactions on tempfile", tempfile)
    f = open(tempfile, 'w')
    f.write('This is original file.\n')
    f.close()

    trans = win32transaction.CreateTransaction(
        Description='Test creating miniversions of a file')
    hfile = win32file.CreateFileW(
        tempfile,
        win32con.GENERIC_READ | win32con.GENERIC_WRITE,
        win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
        None,
        win32con.OPEN_EXISTING,
        0,
        None,
        Transaction=trans)

    win32file.WriteFile(hfile, str2bytes('This is first miniversion.\n'))
    buf = win32file.DeviceIoControl(hfile,
                                    winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION,
                                    None, buf_size, None)
    struct_ver, struct_len, base_ver, ver_1 = struct.unpack(buf_fmt, buf)

    win32file.SetFilePointer(hfile, 0, win32con.FILE_BEGIN)
    win32file.WriteFile(hfile, str2bytes('This is second miniversion!\n'))
    buf = win32file.DeviceIoControl(hfile,
                                    winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION,
                                    None, buf_size, None)
    struct_ver, struct_len, base_ver, ver_2 = struct.unpack(buf_fmt, buf)
    hfile.Close()

    ## miniversions can't be opened with write access
    hfile_0 = win32file.CreateFileW(tempfile,
                                    win32con.GENERIC_READ,
                                    win32con.FILE_SHARE_READ
                                    | win32con.FILE_SHARE_WRITE,
                                    None,
                                    win32con.OPEN_EXISTING,
                                    0,
                                    None,
                                    Transaction=trans,
                                    MiniVersion=base_ver)
    print('version:', base_ver, win32file.ReadFile(hfile_0, 100))
    hfile_0.Close()

    hfile_1 = win32file.CreateFileW(tempfile,
                                    win32con.GENERIC_READ,
                                    win32con.FILE_SHARE_READ
                                    | win32con.FILE_SHARE_WRITE,
                                    None,
                                    win32con.OPEN_EXISTING,
                                    0,
                                    None,
                                    Transaction=trans,
                                    MiniVersion=ver_1)
    print('version:', ver_1, win32file.ReadFile(hfile_1, 100))
    hfile_1.Close()

    hfile_2 = win32file.CreateFileW(tempfile,
                                    win32con.GENERIC_READ,
                                    win32con.FILE_SHARE_READ
                                    | win32con.FILE_SHARE_WRITE,
                                    None,
                                    win32con.OPEN_EXISTING,
                                    0,
                                    None,
                                    Transaction=trans,
                                    MiniVersion=ver_2)
    print('version:', ver_2, win32file.ReadFile(hfile_2, 100))
    hfile_2.Close()

    ## MiniVersions are destroyed when transaction is committed or rolled back
    win32transaction.CommitTransaction(trans)

    os.unlink(tempfile)
Exemple #20
0
 def read(self, bytesToRead=None):
     if bytesToRead is None:
         bytesToRead = self.file_size
     hr, data = win32file.ReadFile(self.handle, bytesToRead, None)
     return data.replace('\r', '')
TAP_IOCTL_CONFIG_POINT_TO_POINT = TAP_CONTROL_CODE(5, 0)
TAP_IOCTL_SET_MEDIA_STATUS = TAP_CONTROL_CODE(6, 0)
TAP_IOCTL_CONFIG_TUN = TAP_CONTROL_CODE(10, 0)

if __name__ == '__main__':
    guid = get_device_guid()
    handle = win32file.CreateFile(
        r'\\.\Global\%s.tap' % guid,
        win32file.GENERIC_READ | win32file.GENERIC_WRITE,
        win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE,
        None,
        win32file.OPEN_EXISTING,
        win32file.FILE_ATTRIBUTE_SYSTEM,  # | win32file.FILE_FLAG_OVERLAPPED,
        None)
    print(handle.handle)
    if False:
        win32file.DeviceIoControl(handle, TAP_IOCTL_CONFIG_POINT_TO_POINT,
                                  '\xc0\xa8\x11\x01\xc0\xa8\x11\x10', None)
    else:
        win32file.DeviceIoControl(handle, TAP_IOCTL_SET_MEDIA_STATUS,
                                  '\x01\x00\x00\x00', None)
        win32file.DeviceIoControl(
            handle, TAP_IOCTL_CONFIG_TUN,
            '\x0a\x03\x00\x01\x0a\x03\x00\x00\xff\xff\xff\x00', None)
    while True:
        l, p = win32file.ReadFile(handle, 2000)
        q = p[:12] + p[16:20] + p[12:16] + p[20:]
        win32file.WriteFile(handle, q)
        print(p, q)
    win32file.CloseHandle(handle)
Exemple #22
0
 def bpgdecode(self,filename):
     msg=None
     cmd=self.bpgpath+' -o '
     if self.img:
         del self.img
         self.img=None
     if len(filename)>4 and filename[-4:].lower()=='.bpg':
         try:
             if not(isfile(filename) and access(filename,R_OK)):
                 msg=_('Unable to open')+'\"%s\"!'%filename
         except: return False
         if not(msg):
             err=0
             try:
                 imbuffer=''
                 if osflag:
                     fifo=osopen(self.fifo,O_RDONLY|O_NONBLOCK)
                     cmd+=self.fifo+' "'+realpath(filename)+'"'+\
                         ' >/dev/null 2>&1'
                     f=Popen(cmd,shell=True,stdin=None,stdout=None,\
                         stderr=None)
                     if fifo:
                         while True:
                             if f.poll()!=None: break;
                             try: data=osread(fifo,16777216)
                             except OSError as e:
                                 if e.errno==errno.EAGAIN or\
                                     e.errno==errno.EWOULDBLOCK: data=''
                                 else: raise
                             if len(data): imbuffer+=data
                         osclose(fifo)
                 else:
                     si=STARTUPINFO()
                     si.dwFlags|=1
                     si.wShowWindow=0
                     pname='\\\\.\\pipe\\'+basename(self.fifo)
                     tpipe=win32pipe.CreateNamedPipe(
                         pname,
                         win32pipe.PIPE_ACCESS_DUPLEX,
                         win32pipe.PIPE_TYPE_BYTE|win32pipe.PIPE_WAIT,
                         1,16777216,16777216,2000,None)
                     cmd+=pname+' "'+realpath(filename)+'"'
                     f=Popen(cmd,shell=False,stdin=None,stdout=None,\
                         stderr=None,bufsize=0,startupinfo=si)
                     win32pipe.ConnectNamedPipe(tpipe,None)
                     imbuffer=''
                     if tpipe:
                         while True:
                             data=None
                             try: data=win32file.ReadFile(tpipe,16777216)
                             except: data=None
                             if not(data): break
                             if data[0]!=0: break
                             if len(data[1]): imbuffer+=data[1]
                     win32pipe.DisconnectNamedPipe(tpipe)
                     f.wait()
                 if len(imbuffer):
                     if imbuffer[0]=='a': mode='RGBA'
                     else: mode='RGB'
                     x,=unpack("i",imbuffer[1:5])
                     y,=unpack("i",imbuffer[5:9])
                     try: self.img=Image.fromstring(mode,(x,y),imbuffer[9:])
                     except: err=1
                     del imbuffer
                 else: err=1
             except: err=1
             if err: msg=_('BPG decoding error!\n')
     else: msg=_('File')+' \"%s\" '%filename+_('is not a BPG-File!')
     if msg:
         print msg
         errmsgbox(msg)
         if self.img:
             del self.img
             self.img=None
     else: return True
     return False
Exemple #23
0
    # For visualization
    #cv2.namedWindow('vis', cv2.WINDOW_NORMAL)
    #cv2.resizeWindow('vis', FRAME_WIDTH, FRAME_HEIGHT)

    frame_counter = 0

    displayText = ''

    while True:
        try:
            # Send request to pipe server
            request_msg = "Request depth image and ir image"
            win32file.WriteFile(fileHandle, request_msg.encode())
            # Read reply data, need to be in same order/size as how you write them in the pipe server in pipe_streaming_example/main.cpp
            depth_data = win32file.ReadFile(
                fileHandle, FRAME_WIDTH * FRAME_HEIGHT * BYTES_PER_PIXEL)
            ab_data = win32file.ReadFile(
                fileHandle, FRAME_WIDTH * FRAME_HEIGHT * BYTES_PER_PIXEL)
            # Reshape for image visualization
            depth_img_full = np.frombuffer(depth_data[1],
                                           dtype=np.uint16).reshape(
                                               FRAME_HEIGHT,
                                               FRAME_WIDTH).copy()
            ab_img_full = np.frombuffer(ab_data[1], dtype=np.uint16).reshape(
                FRAME_HEIGHT, FRAME_WIDTH).copy()

            depth_vis = (plt.get_cmap("gray")(
                depth_img_full / MAX_DEPTH_FOR_VIS)[..., :3] * 255.0).astype(
                    np.uint8)
            ab_vis = (
                plt.get_cmap("gray")(ab_img_full / MAX_AB_FOR_VIS)[..., :3] *
Exemple #24
0
        def read(self, size=0, full=False, timeout=None):
            """Read at most 'size' bytes from file; if 'size' <= 0,
            all data up to EOF is read and returned. If 'full' is
            True, exactly 'size' bytes are returned (unless EOF or
            timeout occur before). If EOF is encountered before any
            more data is available, empty buffer is returned.

            If no data has been read before timeout, then
            IOError('timedout') will be thrown.

            If timeout is given and full is True and timeout expires
            before all the data could be read, it returns partial data
            read before timeout if any data has been read.

            Must be used in a coroutine with 'yield' as
            'data = yield fd.read(1024)'
            """
            def _read(size, full, rc, n):
                if rc or n == 0:
                    if self._timeout:
                        self._notifier._del_timeout(self)
                    self._overlap.object = self._read_result = None
                    if rc != winerror.ERROR_OPERATION_ABORTED:
                        if (self._buflist or rc == winerror.ERROR_HANDLE_EOF
                                or rc == winerror.ERROR_BROKEN_PIPE):
                            buf, self._buflist = ''.join(self._buflist), []
                            self._read_coro._proceed_(buf)
                            return
                        self._read_coro.throw(IOError(rc, 'ReadFile', str(rc)))
                    self._overlap.object = self._read_coro = self._read_result = None
                    return

                buf = self._read_result[:n]
                if size > 0:
                    size -= len(buf)
                    assert size >= 0
                    if size == 0:
                        full = False
                self._buflist.append(buf)
                self._overlap.Offset += n
                if full:
                    self._overlap.object = partial_func(_read, size, full)
                    try:
                        rc, _ = win32file.ReadFile(self._handle,
                                                   self._read_result,
                                                   self._overlap)
                    except pywintypes.error as exc:
                        rc = exc.winerror
                    if rc and rc != winerror.ERROR_IO_PENDING:
                        buf, self._buflist = ''.join(self._buflist), []
                        self._overlap.object = self._read_result = None
                        if self._timeout:
                            self._notifier._del_timeout(self)
                        self._read_coro._proceed_(buf)
                        self._read_coro = None
                    return
                if self._buflist:
                    buf, self._buflist = ''.join(self._buflist), []
                if self._timeout:
                    self._notifier._del_timeout(self)
                self._overlap.object = self._read_result = None
                self._read_coro._proceed_(buf)
                self._read_coro = None

            if not self._asyncoro:
                self._asyncoro = AsynCoro.scheduler()
                self._notifier = self._asyncoro._notifier
                self._notifier.register(self._handle)
            if not size or size < 0:
                count = 16384
                full = True
            else:
                if self._buflist:
                    buf, self._buflist = ''.join(self._buflist), []
                    if len(buf) > size:
                        buf, self._buflist = buf[:size], [buf[size:]]
                    if (not full) or (len(buf) == size):
                        return buf
                    self._buflist = [buf]
                    size -= len(buf)
                count = size
            self._read_result = win32file.AllocateReadBuffer(count)
            self._overlap.object = partial_func(_read, size, full)
            self._read_coro = AsynCoro.cur_coro(self._asyncoro)
            self._read_coro._await_()
            try:
                rc, _ = win32file.ReadFile(self._handle, self._read_result,
                                           self._overlap)
            except pywintypes.error as exc:
                if exc.winerror == winerror.ERROR_BROKEN_PIPE:
                    buf, self._buflist = ''.join(self._buflist), []
                    self._read_coro._proceed_(buf)
                    self._read_result = self._read_coro = self._overlap.object = None
                    return
                else:
                    rc = exc.winerror
            if rc and rc != winerror.ERROR_IO_PENDING:
                self._overlap.object = self._read_result = self._read_coro = None
                self._read_coro.throw(IOError(rc, 'ReadFile', str(rc)))
            if timeout:
                self._timeout = timeout
                self._notifier._add_timeout(self)
Exemple #25
0
def get_buffer_size(pipe_handle, num_bytes):
    buffer_size = int.from_bytes(wf.ReadFile(pipe_handle, num_bytes)[1],
                                 byteorder='big')
    return buffer_size
Exemple #26
0
 def fread(self, length):
     length = int(length)
     _, data = win32file.ReadFile(self.fhandle, length)
     print "fread to read length:{0} actual readd {1}".format(
         length, len(data))
     return data
Exemple #27
0
            "\\\\.\\pipe\\mynamedpipe",
            win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None,
            win32file.OPEN_EXISTING, 0, None)

    OldStamp = -1.

    loss = 0
    acc = 0
    labelIndex = 0

    while True:

        if not runTest:
            request_msg = "Request bodyInfo"
            win32file.WriteFile(fileHandle, request_msg.encode())
            inputData = win32file.ReadFile(fileHandle,
                                           1168)  #(32*6+1) * 4bytes
            data = np.frombuffer(inputData[1],
                                 dtype="float32",
                                 count=-1,
                                 offset=0)
        else:
            data = testRun.GetNextValue()
            if data == None:
                break

        if (OldStamp != data[288]):
            OldStamp = data[288]
            if (len(buffer) == clipFrames):
                buffer.pop(0)
            elif not testRun:
                buffer.append(

inputData = []

quit = False
resp = []
while not quit:
    try:
        handle = win32file.CreateFile(
            r'\\.\pipe\pythonPipe',
            win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None,
            win32file.OPEN_EXISTING, 0, None)
        win32pipe.SetNamedPipeHandleState(handle,
                                          win32pipe.PIPE_READMODE_MESSAGE,
                                          None, None)
        resp = win32file.ReadFile(handle, 64 * 1024)[1].decode('utf-16')
    except pywintypes.error as e:
        if e.args[0] == 2:
            time.sleep(1)
        if resp != []:
            quit = True

inputData = json.loads(resp)

xSymbol, ySymbol = sympy.symbols('x y')

expression = parse_expr(inputData["Expression"].replace("^", "**").replace(
    "exp", "E**"))

x, y, z = makeData(inputData["XStart"], inputData["XEnd"], inputData["YStart"],
                   inputData["YEnd"], expression)
Exemple #29
0
gui='0'

#Make the Pipe Connections
#Define the pipe
p1 = win32pipe.CreateNamedPipe(r'\\.\pipe\netsim_sumo_pipe',
    win32pipe.PIPE_ACCESS_DUPLEX,
    win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT,
    1, 65536, 65536,300,None)

print("Waiting for netsim to connect...")
#Connect the Pipe
win32pipe.ConnectNamedPipe(p1, None)

#Read once
data = win32file.ReadFile(p1, 4096)  #Get whether GUI =1 or 0 from Netsim
gui=data[1][0]

#The value of 'gui' is read from: data = win32file.ReadFile(p1,4096)
#In Pyton-3, the value of 'gui' is an ASCII of the string char(48 for '0') i.e., an int type, whereas in Python-2 the value of 'gui' is directly of str type.
# So we are converting the ASCII to char only if it is of int type ---> We are using 'if' to also make the code compatable with Python-2
if isinstance(gui, int):
    gui = chr(gui)

#Lets check whether Sumo is present or not, and then go to the tools folder of Sumo
print("Checking Sumo...")
try:
    sys.path.append(os.path.join(SUMO_HOME, "tools")) 					#go to tools folder
    from sumolib import checkBinary										#A sumo back-end library to check if sumo is present or not
except ImportError:
    sys.exit("Please declare environment variable 'SUMO_HOME' as the root directory of your sumo installation (it should contain folders 'bin', 'tools' and 'docs')")
Exemple #30
0
 def Read(self):
     data = win32file.ReadFile(self._pipeHandle, 65536)
     return data[1]