Пример #1
0
 def __init__(self, servicemanager):
     self.appname = ""
     self.lasttopic = ""
     self.servicemanager = servicemanager
     self.server = dde.CreateServer()
     self.server.Create("DDEPROXY")
     self.convers = dde.CreateConversation(self.server)
Пример #2
0
def main():
	machine ="Irrelevant_MachineName"
	tag ="Irrelevant_Tagname"
	server = dde.CreateServer()
	server.Create("Irrelevant_ServerName")
	t = Conversation(server,"Irrelevant_Name", machine, tag)
	t.start()
Пример #3
0
class IPCWin32DDE(IPC):
    def create(self):
        self.server = None

        # try to connect first
        self.client = Server(None, None, dde.CreateServer())
        self.client.Create(
            app_name, dde.CBF_FAIL_SELFCONNECTIONS | dde.APPCMD_CLIENTONLY)
        self.conversation = dde.CreateConversation(self.client)
        try:
            self.conversation.ConnectTo(app_name, "controlsocket")
            raise BTFailure(_("DDE Conversation connected."))
        except dde.error, e:
            # no one is listening
            pass

        # clean up
        self.client.stop()
        del self.client
        del self.conversation

        # start server
        self.server = Server(self.log, self.handle_command, dde.CreateServer())
        self.server.Create(
            app_name, dde.CBF_FAIL_SELFCONNECTIONS | dde.APPCLASS_STANDARD)
        self.server.AddTopic(
            Topic(self.handle_command, dde.CreateTopic("controlsocket")))
Пример #4
0
def dde_connect(svrnam, SERVER, TOPIC):
    #Create and connect to dde server
    svr = dde.CreateServer()
    svr.Create(svrnam)
    con = dde.CreateConversation(svr)
    con.ConnectTo(SERVER, TOPIC)
    return con
Пример #5
0
def StartAcrobatReader(filename):
    global dde_server
    import win32api
    import win32ui
    import dde

    filename = unicode(os.path.abspath(filename))
    path, name = os.path.split(filename)
    reader = win32api.FindExecutable(name, path)
    os.spawnl(os.P_NOWAIT, reader[1], " ")

    for t in range(10):
        time.sleep(1)
        for acrobat in DDE_ACROBAT_STRINGS:
            try:
                if not dde_server:
                    dde_server = dde.CreateServer()
                    dde_server.Create('Gertrude')
                c = dde.CreateConversation(dde_server)
                c.ConnectTo(acrobat, 'control')
                c.Exec('[DocOpen("%s")]' % (filename, ))
                return
            except Exception, e:
                pass
        print "Impossible de lancer acrobat reader ; prochain essai dans 1s ...", e
Пример #6
0
 def _setup_dde(self):
     self.serv = dde.CreateServer()
     self.serv.Create("TC")
     try:
         self.conversation = dde.CreateConversation(self.serv)
         self.conversation.ConnectTo(self.app, self.topic)
     except:
         print("Cannot connect to XMPlay")
Пример #7
0
    def PollRange(self):

        self.server = dde.CreateServer()
        self.server.Create('DAQ_GUI')
        self.tchat = dde.CreateConversation(self.server)
        self.tchat.ConnectTo("P7889", "7889")
        datarange = self.tchat.Request("RANGE")
        self.server.Destroy()

        return int(datarange)
Пример #8
0
    def StartStream(self):

        self.setFilename('PE_tmp_file')
        self.setTDCParameters()
        self.server = dde.CreateServer()
        self.server.Create('DAQ_GUI')
        self.tchat = dde.CreateConversation(self.server)
        self.tchat.ConnectTo("P7889", "7889")
        self.tchat.Exec("RUN TDCCMD.CTL")
        self.server.Destroy()
Пример #9
0
 def resetclient(self):
     # having our dde conversation fifrst
     try:
         self.ddeclient.Destroy()
     except:
         pass
     
     self.ddeclient = dde.CreateServer()
     self.ddeclient.Create("AutoClient")
     self.conversation = dde.CreateConversation(self.ddeclient)
 def __start__(self, path=None, suffix="", period=1.0):
     self.xmpPath = path
     self.xmpServer = dde.CreateServer()
     self.xmpConversation = None
     if suffix:
         self.observThread = ObservationThread(
             period,
             suffix,
         )
         self.observThread.start()
Пример #11
0
    def StopStream(self):

        try:
            self.server = dde.CreateServer()
            self.server.Create('DAQ_GUI')
            self.tchat = dde.CreateConversation(self.server)
            self.tchat.ConnectTo("P7889", "7889")
            self.tchat.Exec("halt")
            self.server.Destroy()
        except:
            return 0
Пример #12
0
    def RunStream(self):

        self.server = dde.CreateServer()
        self.server.Create('DAQ_GUI')
        self.tchat = dde.CreateConversation(self.server)
        self.tchat.ConnectTo("P7889", "7889")
        datastr = self.tchat.Request("DATA")
        self.server.Destroy()

        data = map(int, datastr.splitlines())

        return data
Пример #13
0
    def StopRecording(self):

        #self.server.Shutdown()
        try:
            self.server = dde.CreateServer()
            self.server.Create('DAQ_GUI')
            self.tchat = dde.CreateConversation(self.server)
            self.tchat.ConnectTo("P7889", "7889")
            self.tchat.Exec("halt")
            self.server.Destroy()
        except:
            return 0
Пример #14
0
 def __init__(self,server="",topic=""):
     # having our dde conversation fifrst
     self.ddeclient = dde.CreateServer()
     self.ddeclient.Create("AutoTrader")
     self.conversation = dde.CreateConversation(self.ddeclient)
     self.ddeserver = ""
     self.ddedata = ""
     self.configdict={}
     self.status = 0
     if server and topic:
         self.ddeserver = server
         self.ddedata = topic 
         self.connect()
Пример #15
0
    def __init__(self, server="FlowDDE", topic="C(1)", capacity=3.0):
        """
      server (srting): DDE server name (FlowDDE or FlowDDE2)
      topic (string): topic associated with the devece on flow bus. 

    """
        self.server = dde.CreateServer()
        self.server.Create("BFS_client")
        self.conversation = dde.CreateConversation(self.server)
        self.conversation.ConnectTo(server, topic)
        #This seems to be the parameter that defines full scale reading for fMeas
        self.capacity_max = float(self.conversation.Request("P(248)"))
        self.capacity = capacity
Пример #16
0
    def create(self):
        self.server = None

        # try to connect first
        self.client = Server(None, None, dde.CreateServer())
        self.client.Create(
            app_name, dde.CBF_FAIL_SELFCONNECTIONS | dde.APPCMD_CLIENTONLY)
        self.conversation = dde.CreateConversation(self.client)
        try:
            self.conversation.ConnectTo(app_name, "controlsocket")
            raise BTFailure(_("DDE Conversation connected."))
        except dde.error, e:
            # no one is listening
            pass
Пример #17
0
def _connectAcrobat():
    """ Create a DDE server and conversation with acroview """
    s = None
    try:
        import win32ui
        import dde
        s = dde.CreateServer()
        s.Create('')
        c = dde.CreateConversation(s)
        c.ConnectTo('acroview', 'control')
        return (s, c)
    except:
        if s:
            s.Destroy()
        raise Exception, 'DDE link failed'
Пример #18
0
    def __EnsureDymolaIsOpen(this):
        if(not Dymola.__dymolaIsOpen):
            import win32ui
            import dde
            import time
            from PySimLib import Platform

            Dymola.__ddeServer = dde.CreateServer()
            Dymola.__ddeServer.Create("TestClient")
            Dymola.__ddeConversation = dde.CreateConversation(Dymola.__ddeServer)
            Dymola.__dymolaIsOpen = True

            Platform.Execute([GetConfigValue("Dymola", "PathExe")], False)
            time.sleep(float(GetConfigValue("Dymola", "StartupDelay")))
            Dymola.__ddeConversation.ConnectTo("dymola", " ")
            Dymola.__ddeConversation.Exec("OutputCPUtime:=true;")
Пример #19
0
def main():
    """
      Call SumatraPDF View, try to synchronize line number
    """
    realpath = os.path.abspath(sys.argv[1])
    srcpath = os.path.abspath(sys.argv[2])
    (pdfpath, pdfnameext) = os.path.split(realpath)
    (pdfname, pdfext) = os.path.splitext(pdfnameext)
    (path, nameext) = os.path.split(srcpath)
    (name, ext) = os.path.splitext(nameext)
    srcpath = srcpath.replace('\\', '/')
    lineno = sys.argv[3]
    
    scmd = ''.join([r'C:\app\docstruct\pdfview\SumatraPDF.exe ',
                    ' -reuse-instance ',
                    ' -inverse-search ',
#                    r'"\"C:\app\docstruct\npp\notepad++.exe\" -n%l \"%f\"" ',
                    r'"\"C:\app\docstruct\python27\pythonw.exe\" \"C:\app\docstruct\python27\Lib\site-packages\docsassembler\showsources.py\"   \"%f\" %l "',
                    '"', realpath, '"'  ])
    
    p = subprocess.Popen(scmd, 
                        stdout=subprocess.PIPE, 
                        stderr=subprocess.STDOUT)
    
    print scmd
    time.sleep(1)    

    server = dde.CreateServer()
    server.Create("pdfviewproxy")
    
    conversation = dde.CreateConversation(server)

    srcfile = srcpath
    if pdfpath == path and pdfname == name:
        srcfile = nameext    
    
    print "Try to connect"
    conversation.ConnectTo("SUMATRA", "control")
    ddecmd = ''.join(['[ForwardSearch("', realpath, '", "',
                                          srcfile, '", ', lineno, ',0,0,1)]'])
    print "Try to exec", ddecmd
    conversation.Exec(ddecmd)

    print "PDFViewer connected..."
    server.Destroy()
Пример #20
0
 def start(self):
     #запуск сервера
     server = dde.CreateServer()
     server.AddTopic(QuikTopic(self))
     server.Create(self.topic_name)
     event = win32event.CreateEvent(None, 0, 0, None)
     while 1:
         win32ui.PumpWaitingMessages(0, -1)
         rc = win32event.MsgWaitForMultipleObjects((event, ), 0, 100,
                                                   win32event.QS_ALLEVENTS)
         if rc == win32event.WAIT_OBJECT_0:
             break
         #elif rc==win32event.WAIT_OBJECT_0+1:
         #    print "OK1"
         #if win32ui.PumpWaitingMessages(0,-1):
         #    raise RuntimeError("We got an unexpected WM_QUIT message!")
         elif rc == win32event.WAIT_TIMEOUT:
             pass
Пример #21
0
class IPCWin32DDE(IPC):
    def create(self):
        self.server = None

        if g_mutex.IsAnotherInstanceRunning():
            # test whether there is a program actually running that holds
            # the mutex.
            for i in xrange(10):
                # try to connect first
                self.client = Server(None, dde.CreateServer())
                self.client.Create(
                    app_name,
                    dde.CBF_FAIL_SELFCONNECTIONS | dde.APPCMD_CLIENTONLY)
                self.conversation = dde.CreateConversation(self.client)
                try:
                    self.conversation.ConnectTo(app_name, self.name)
                    raise BTFailure("DDE Conversation connected.")
                except dde.error, e:
                    # no one is listening
                    pass

                # clean up
                self.client.stop()
                del self.client
                del self.conversation
                ipc_logger.warning(
                    "No DDE Server is listening, but the global mutex exists. Retry %d!"
                    % i)
                time.sleep(1.0)

                # oh no you didn't!
                if i == 5:
                    pykill.kill_process(app_name)

            # continuing might be dangerous (two instances)
            raise Exception(
                "No DDE Server is listening, but the global mutex exists!")

        # start server
        self.server = Server(self.handle_command, dde.CreateServer())
        self.server.Create(
            app_name, dde.CBF_FAIL_SELFCONNECTIONS | dde.APPCLASS_STANDARD)
        self.server.AddTopic(
            Topic(self.handle_command, dde.CreateTopic(self.name)))
Пример #22
0
    def StartRecording(self):

        #            savestart= 0
        #            ChannelsMask = 0xF
        #            StartSample = 0

        #if self.dscanmode == 0:
        #self.setFilename('Spectrum')
        #else:
        #    self.setFilename('Spectrum_D%s'%(str(increment).zfill(4)))

        #self.setTDCParameters()

        self.server = dde.CreateServer()
        self.server.Create('DAQ_GUI')
        self.tchat = dde.CreateConversation(self.server)
        self.tchat.ConnectTo("P7889", "7889")
        self.tchat.Exec("RUN TDCCMD.CTL")
        self.server.Destroy()
Пример #23
0
def SendCommandToGame(command, ExpectedResult=False):
    """
    This function sends a CAOS command to a C1 or C2 game and returns the result
    You have to specify whether or not the executed command expects output to be returned, as both kinds of commands require different calls
    """
    server = dde.CreateServer()
    server.Create("TestClient")
    conversation = dde.CreateConversation(server)

    conversation.ConnectTo("Vivarium", "Anything")
    conversation.Poke("Macro", command + "\x00")

    if ExpectedResult == True:
        rep = conversation.Request("Macro")
    else:
        conversation.Exec(command + "\x00")
        rep = ""
    server.Destroy()

    return rep
Пример #24
0
 def connect(self):
     """
     Tries to create a connection to dymola
     
     """
     
     self._server = dde.CreateServer()
     self._server.Create('dym')
     self._conversation = dde.CreateConversation(self._server)
     
     # try to connect to dymola    
     try:
         self._conversation.ConnectTo('Dymola','cd("C://");')
     except:
         # dymola is probably not opened so try to open it first end wait some time before retrying
         subprocess.Popen(['dymola'])
         time.sleep(10)
         
         try:
             self._conversation.ConnectTo('Dymola','cd("C://");')
         except:
             raise Exception('Dymola could not be found')
    def __call__(self, ip, filename, lineno, columnno):
        filename = find_filename(filename)

        if not filename:
            return

        server = dde.CreateServer()
        server.Create("myddeserver")
        conversation = dde.CreateConversation(server)
        try:
            conversation.ConnectTo("uedit32", "System")
            conversation.Exec(r'[open("%s/%d"])' % (filename, lineno))

            sleep(self.wakeup_duration)
        except:
            run_command(self.path, 'uedit32', '"%s/%d"' % (filename, lineno))

            sleep(self.start_duration)

        server.Shutdown()

        restore_console_focus()
Пример #26
0
def SendCommandToGame(command, ExpectedResult=False):
    """
    This function sends a CAOS command to a C1 or C2 game and returns the result
    You have to specify whether or not the executed command expects output to be returned, as both kinds of commands require different calls
    """
    server = dde.CreateServer()
    server.Create("TestClient")  # This can be anything or even empty.
    conversation = dde.CreateConversation(server)

    conversation.ConnectTo("Vivarium", "Anything")
    conversation.Poke(
        "Macro", command + "\x00"
    )  # Rembember Creature expects C-style \0 terminated strings as DDE inputs
    if ExpectedResult == True:
        # If the command returns a result use the Request() method
        rep = conversation.Request("Macro")
    else:
        # If the command doesn't a result use the exec() method
        conversation.Exec(command + "\x00")
        rep = ""

    server.Destroy()
    return rep
Пример #27
0
    from sys import argv
    layout = "{%artist - }{%title }{[%album]}"
    if len(argv) > 1:
        layout = argv[1]
    layout = layout.replace('{', '{{').replace(
        '}',
        '}}')  # double curly brackets are not that likely to exist in tags
    optionals = []  # Elements in this list will be removed from the output
    open = -2
    while open == -2 or open > -1:
        open = layout.find('{{', open + 2)
        close = layout.find('}}', open + 2)
        if close > -1:
            optionals.append(layout[open:close + 2])

    server = dde.CreateServer()
    server.Create("xmplaynp")
    conversation = dde.CreateConversation(server)
    info = {}
    conversation.ConnectTo("xmplay", "info0")
    reply = conversation.Request("info0")
    for tuple in reply.split('\n'):
        parts = tuple.split('\t', 1)
        item = parts[0].strip()
        if item:
            info[item.lower()] = value
    conversation.ConnectTo("xmplay", "info1")
    reply = conversation.Request("info1")
    for tuple in reply.split('\n'):
        parts = tuple.split('\t', 1)
        item = parts[0].strip()
Пример #28
0
    def start(self, path):
        """
        @param path: 변환(분석)할 문서 파일의 경로
        @return: 프로세스 ID
        """
        # 확장자에 맞는 인쇄 명령을 찾음.
        # (ShellExecute에서 print 동사(verb) 사용 시 실행되는 명령어)
        file_path, file_ext = os.path.splitext(path)

        print_cmd = self.get_print_command(file_ext)
        if not print_cmd:
            raise CuckooPackageError('Not supported extension: ' + file_ext)

        # 인쇄 명령어에서 실행 프로그램의 경로와 각 파라미터를 분리 시킴.
        regex = re.compile(r'((?:(?:[^\s"]+)|"(?:""|[^"])*")+)(?:\s|$)')
        found = regex.findall(print_cmd['command'])
        if len(found) < 2:
            raise CuckooPackageError('Wrong print command: ' +
                                     print_cmd['command'])

        # 프로그램 실행 경로
        execute_path = found[0]
        if execute_path.startswith('"'):
            execute_path = execute_path[1:-1]  # 양 끝의 "(큰따옴표)를 제거함.

        # 프로그램 파라미터
        execute_param = []
        for param in found[1:]:
            if param.startswith('"') and param.endswith('"'):
                param = param[1:-1]  # 양 끝의 "(큰따옴표)를 제거함.
            execute_param.append(param.replace('%1', '{}'.format(path)))

        pid = self.execute(execute_path, args=execute_param)

        # 일부 프로그램(특히 MS 오피스)의 경우
        # 인쇄를 위해서는 DDE 통신이 필요함.
        if print_cmd['ddeexec']:
            log.debug('Need dde!!')
            if not print_cmd['application']:
                raise CuckooPackageError('No dde server name. dde info: ' +
                                         str(print_cmd))
            if not print_cmd['topic']:
                raise CuckooPackageError('No dde topic. dde info: ' +
                                         str(print_cmd))

            time.sleep(5)  # dde 서버가 실행되는 동안 기다림

            try:
                log.debug('dde start')
                server = dde.CreateServer()
                log.debug('dde server create1')
                server.Create('PrintClient')
                log.debug('dde server create2')
                conversation = dde.CreateConversation(server)
                log.debug('dde conversation created')
                conversation.ConnectTo(print_cmd['application'],
                                       print_cmd['topic'])
                log.debug('dde connected')
                conversation.Exec(print_cmd['ddeexec'].replace('%1', path))
                log.debug('dde exec.')
            except Exception as e:
                log.error(str(e))

        return pid
Пример #29
0
 def __init__(self, name, logger=logs.AbstractLogger(levelName='EMERG')):
     import win32ui, dde
     server = self.server = dde.CreateServer()
     self.name = name
     self.logger = logger
     server.Create(name)
Пример #30
0
    def show(self):
        """
        Shows the plot in active DPlot Window. Uses DDE interface - 
        see "Programmer's Reference" in DPlot help. Currently will plot 2D 
        curves. It will generate the data points for 3D contour curves but not
        display them -- this is because error handling must be done
        to ensure a valid triangular mesh can be generated. 

        Returns
        -------
        None.

        """
        #open the DDE channel
        self.server = None
        self.channel = None
        self.server = dde.CreateServer()
        self.server.Create("TestClient")
        self.channel = dde.CreateConversation(self.server)        
        try:
            self.channel.ConnectTo("DPlot","System")
        except:
            # DPlot isn't open or some other error occurred. 
            self.server.Shutdown()
            self.server = None
            self.channel = None
            return -1
        # open a new file
        num_dims = len(self.curves[0].data)
        if num_dims == 3:
            self.channel.Exec('[filenew(3)]')
        else:
            self.channel.Exec('[filenew()]')
        # Turn off min-max-mean check until writing is complete
        self.channel.Exec('[DeferMinMaxCheck(1)]')
        # Set File Array Sizes
        self.channel.Exec('[FileArrays(' + str(len(self.curves)) + ',' + str(self.curves[0].xdata.size) +')]')
        # plot the curves
        for curve_num,curve in enumerate(self.curves):
            # check to see if xy or xyz data
            num_dims = len(curve.data)
            # Create the output strings for data exchange
            sCurveNum = str(curve_num+1)
            #Select Curve Number
            self.channel.Exec('[SelectCurve('+sCurveNum+')]')
            Data = [None]*curve.xdata.size*num_dims
            Data[::num_dims] = curve.xdata.tolist()
            Data[1::num_dims] = curve.ydata.tolist()
            if num_dims == 3:
                Data[2::num_dims] = curve.zdata.tolist()
            sData = [str(data) for data in Data]
            if curve.xdata.size > 1000:
                for lst in self.chunks(sData,2000):
                    sOutput = ','.join([str(int(len(lst)/2))] + lst )
                    self.channel.Exec('[XYXY('+sOutput+')]')
            else:
                sOutput = ','.join(([str(curve.xdata.size)] + sData))
                # Write data
                if num_dims == 3:
                    self.channel.Exec('[XYZEx(0,'+sOutput+')]')
                else:
                    self.channel.Exec('[XYXY('+sOutput+')]')
            # Write attributes
            # Legend
            self.channel.Exec('[Legend('+ sCurveNum+',"'+curve.title +'")]')
            # Label
            self.channel.Exec('[CurveLabel('+ sCurveNum+',"'+ curve.label+'")]')
            # Linetype
            sCurveLT = str(curve.line)
            self.channel.Exec('[LineType('+sCurveNum+','+sCurveLT+')]')
            # Symbol
            sCurveSymbol = str(curve.symbol)
            self.channel.Exec('[SymbolType('+sCurveNum+','+sCurveSymbol+')]')
        '''
        TODO - XYZ plots. Note that XYZ plots must form a valid triangular
        mesh. So have to perform error handling to make sure x,y,z form a grid,etc.
        '''
        if num_dims == 3:
            pass
            #self.channel.Exec('[XYZRegen()]')
            #self.channel.Exec('[ViewRedraw()]')
        # Title, Subtitle, Axis Labels
        self.channel.Exec('[Title1("'+self.title+'")]')
        self.channel.Exec('[Title2("'+self.subtitle+'")]')
        self.channel.Exec('[XAxisLabel("'+self.xlabel+'")]')
        self.channel.Exec('[YAxisLabel("'+self.ylabel+'")]')
        
        # Turn back on functionality
        self.channel.Exec('[DeferMinMaxCheck(0)]')
        # shutdown the DDE server and cleanup
        self.server.Shutdown()
        self.server = None
        self.channel = None