示例#1
0
 def _generate_object(self, app_name, func):
     app_name = app_name.lower()
     com_handle = func(self._prog_info[app_name]['id'])
     
     # Word Application does not have Hwnd property.
     if hasattr(com_handle, 'Hwnd'):
         for id_ in self:
             if hasattr(self[id_].com_handle, 'Hwnd') and self[id_].com_handle.Hwnd == com_handle.Hwnd:
                 return id_
     
     wrapper = self._prog_info[app_name]['class'](com_handle=com_handle)
     object_id = id(wrapper)
     self[object_id] = wrapper
     wrapper.show_window()
     
     if app_name == 'word':
         # The connection object should be stored, 
         # or it will be gabage collected, and consequently, 
         # event sink will not be notified any more. 
         connection = client.GetEvents(wrapper.com_handle, wrapper)
         wrapper._event_connection = connection
         # Set event handler for each document object.
         for idx in range(com_handle.Documents.Count):
             idx1 = idx + 1
             doc_wrapper = WordDocumentObject(
                     parent=wrapper, 
                     handle=com_handle.Documents.Item(idx1))
             doc_wrapper._event_connection = client.GetEvents(
                     doc_wrapper.com_handle, 
                     doc_wrapper)
             wrapper._doc_list.append(doc_wrapper)
             
     return object_id
示例#2
0
    def __init__(self):

        self.buttons = []
        self.rotation = None
        self.translation = None

        from comtypes import client
        device = client.CreateObject("TDxInput.Device")

        devnames = {
            6: "Space Navigator",
            4: "Space Explorer",
            25: "Space Traveler",
            29: "Space Pilot"
        }
        name = devnames.get(device.Type, 'unknown')

        status = device.Connect()
        if status:
            raise IOError, 'COM Connection to %s device failed.' % name

        # Setup button listener
        self.keyboard = device.Keyboard
        self.kev = client.GetEvents(self.keyboard, self)

        # Setup sensor listener
        self.sensor = device.Sensor
        self.sev = client.GetEvents(self.sensor, self)
示例#3
0
    def measure(self, sigramp):
        print('Opening Connection')
        ret = self.open_connection()
        self.pstat.SetIERange(8)

        print(ret)
        # push the signal ramp over
        print('Pushing')
        self.pstat.SetSignal(sigramp)

        self.pstat.SetCell(self.GamryCOM.CellOn)
        self.measurement_setup()
        self.connection = client.GetEvents(self.dtaqcpiv, self.dtaqsink)
        try:
            self.dtaqcpiv.Run(True)
        except Exception as e:
            raise gamry_error_decoder(e)
        self.data = collections.defaultdict(list)
        client.PumpEvents(0.001)
        sink_status = self.dtaqsink.status
        while sink_status != "done":
            client.PumpEvents(0.001)
            sink_status = self.dtaqsink.status
            dtaqarr = self.dtaqsink.acquired_points
            self.data = dtaqarr
        self.pstat.SetCell(self.GamryCOM.CellOff)
        self.close_connection()
示例#4
0
    def bind_all(self, func):
        if self._selected:

            #Create the event sink
            self._sink = EventSink(self._syndev, self._synpac)

            #Patch the handler with the callable func
            if callable(func):
                self._sink._onpac = func
            else:
                raise TypeError("func must be callable")

            #Redirect events of main message pump to the event sink
            self._connection = client.GetEvents(self._syndev, self._sink)

            #Connect ISynDeviceCtrl events to the main message pump
            if self._syndev.Activate() == SYNE_FAIL:
                raise RuntimeError(
                    "The Synaptics kernel-mode driver is not present on the target machine."
                )

        else:
            raise RuntimeError(
                "No device selected, call the method select with a valid device query handle before binding"
            )
示例#5
0
    def __init__(self,
                 connection_type=synctrl.SE_ConnectionAny,
                 device_type=synctrl.SE_DeviceAny):
        self._synapi = client.CreateObject("SynCtrl.SynAPICtrl")
        if self._synapi.Initialize() == synerror.SYNE_FAIL:
            raise RuntimeError(
                "The Synaptics kernel-mode driver is not present on "
                "the target machine, or the installed driver version "
                "is less than that necessary to support the Synaptics COM API."
            )
        self._syndev = client.CreateObject("SynCtrl.SynDeviceCtrl")
        self._synpac = client.CreateObject("SynCtrl.SynPacketCtrl")

        # TODO: catch COMError
        lHandle = self._synapi.FindDevice(connection_type, device_type, -1)
        if lHandle < 0:
            raise RuntimeError("No appropriate device found.")
        elif lHandle == synerror.SYNE_FAIL:
            raise RuntimeError(
                "The ISynAPICtrl object has not been initialized properly.")

        if self._syndev.Select(lHandle) == synerror.SYNE_HANDLE:
            raise ValueError(
                "The requested lHandle does not correspond to any known device."
            )

        self._connection = client.GetEvents(self._syndev, self)
        if self._syndev.Activate() == synerror.SYNE_FAIL:
            raise RuntimeError(
                "The Synaptics kernel-mode driver is not present on the target machine."
            )
示例#6
0
    def measure(self, sigramp, gsetup=None):
        print("Opening Connection")
        ret = self.open_connection()
        self.pstat.SetIERange(8)
        # IErange: 0=3 pA, 1=30pA, 2=300pA, 3=3nA, 4=30nA, 5=300nA, 6=3uA, ...
        #TODO: IERange is a parameter and should be placed somewhere else

        print(ret)
        # push the signal ramp over
        print("Pushing")
        self.pstat.SetSignal(sigramp)

        self.pstat.SetCell(self.GamryCOM.CellOn)
        if gsetup == None:
            self.measurement_setup()
        else:
            self.measurement_setup(gsetup)  #TODO: good to add gsetup?
        self.connection = client.GetEvents(self.dtaqcpiv, self.dtaqsink)
        try:
            self.dtaqcpiv.Run(True)
        except Exception as e:
            raise gamry_error_decoder(e)
        self.data = collections.defaultdict(list)
        client.PumpEvents(0.001)
        sink_status = self.dtaqsink.status
        while sink_status != "done":
            client.PumpEvents(0.001)
            sink_status = self.dtaqsink.status
            dtaqarr = self.dtaqsink.acquired_points
            self.data = dtaqarr
        self.pstat.SetCell(self.GamryCOM.CellOff)
        self.close_connection()
示例#7
0
    def startMeasurment(self):
        # Initialize the Pstat
        self.cominterface.Open()
        self.cominterface.SetCell(GamryCOM.CellOn)
        self.cominterface.SetCtrlMode(GamryCOM.PstatMode)

        # Initialize a Dtaq
        dtaqchrono = client.CreateObject('GamryCOM.GamryDtaqChrono')
        dtaqchrono.Init(self.cominterface, GamryCOM.ChronoAmp)
        dtaqsink = GamryDtaqEvents(dtaqchrono, self)
        client.ShowEvents(dtaqchrono)
        client.GetEvents(dtaqchrono, dtaqsink)

        # Initialize a two-step wavefrom Signal
        sigstep = client.CreateObject('GamryCOM.GamrySignalStep')
        sigstep.Init(self.cominterface, 0.5, 15, -0.1, 15, 0.01,
                     GamryCOM.PstatMode)

        # Set Signal
        self.cominterface.SetSignal(sigstep)

        # Acquire Data
        try:
            dtaqchrono.Run(True)
        except Exception as e:
            print("Big drama show")
示例#8
0
    def sk_init(self):
        import redis  #使用python来操作redis用法详解  https://www.jianshu.com/p/2639549bedc8 导入redis模块,通过python操作redis 也可以直接在redis主机的服务端操作缓存数据库
        #cache = redis.Redis(host='localhost', port=6379, decode_responses=True)   # host是redis主机,需要redis服务端和客户端都启动 redis默认端口是6379
        pool = redis.ConnectionPool(host=self.redis_host,
                                    port=6379,
                                    decode_responses=True,
                                    max_connections=50)
        self.cache = redis.Redis(connection_pool=pool)

        self.skC = cc.CreateObject(sk.SKCenterLib, interface=sk.ISKCenterLib)
        self.skQ = cc.CreateObject(sk.SKQuoteLib, interface=sk.ISKQuoteLib)
        self.skR = cc.CreateObject(sk.SKReplyLib, interface=sk.ISKReplyLib)
        #Configuration
        self.EventQ = self.skQ_events(self)
        self.EventR = self.skR_events(self)
        self.ConnectionQ = cc.GetEvents(self.skQ, self.EventQ)
        self.ConnectionR = cc.GetEvents(self.skR, self.EventR)
示例#9
0
 def __init__(self, mode="Potentiostat", which_one=0):
     pythoncom.CoInitializeEx(pythoncom.COINIT_MULTITHREADED)
     self.devices=client.CreateObject('GamryCOM.GamryDeviceList',clsctx=comtypes.CLSCTX_LOCAL_SERVER)
     # print self.devices.EnumSections()
     # Unfortunately it is necessary to sleep for 10 seconds after initializing the
     # device list.  Results with-out this sleep are somewhat unpredictable.
     time.sleep(10) # Another demonstration how immature this ugly interface is programmed
     self.pstat=client.CreateObject('GamryCOM.GamryPstat',clsctx=comtypes.CLSCTX_LOCAL_SERVER)
     self.pstat.Init(self.devices.EnumSections()[which_one]) # grab pstat selected
     time.sleep(10)
     self.pstat.Open()
     time.sleep(1)
     #self.pstat.SetCell(0) # 0=off 1=on
     #self.pstat.SetCell(GamryCOM.CellOff)
     #self.pstat.SetCtrlMode(1) # 0=Galvanostat (amp=const), 1=Potentiostat (volts=const), 2=Zero Resistance Ammeter 3=Frequency response analyser
     self.mode = mode
     if self.mode == "Potentiostat":
         self.pstat.SetCtrlMode(GamryCOM.PstatMode)
         print "Potentiostatic mode selected"
     elif self.mode == "Galvanostat":
         self.pstat.SetCtrlMode(GamryCOM.GstatMode)
         print "Galvanostatic mode selected"
     #self.pstat.SetStability(GamryCOM.StabilityFast) # 0=Fast 1=medfast 2=norm 3=slow
     #self.pstat.SetStability(2) # 0=Fast 1=medfast 2=norm 3=slow
     #self.pstat.SetCASpeed(GamryCOM.CASpeedMedFast) # use medfast ???
     self.pstat.SetSenseSpeedMode(1) # TRUE
     #self.pstat.SetConvention(1) # 0=cathodic 1=anodic
     self.pstat.SetGround(0) # 0=Float 1=Earth
     #self.pstat.SetIchRange(3.0)
     #self.pstat.SetIchRangeMode(0) # False
     #self.pstat.SetIchFilter(5.0)
     #self.pstat.SetVchRange(3.0)
     #self.pstat.SetVchRangeMode(0) # False
     #self.pstat.SetIchOffsetEnable(1) # True
     #self.pstat.SetVchOffsetEnable(1) # True
     #self.pstat.SetVchFilter(5.0)
     #self.pstat.SetAchRange(3.0)
     #self.pstat.SetIERangeLowerLimit() # NIL
     #self.pstat.SetIERange(0.03)
     #self.pstat.SetIERangeMode(0) # False
     #self.pstat.SetAnalogOut(0.0)
     #self.pstat.SetVoltage(0.0) # DCvoltage
     #self.pstat.SetPosFeedEnable(0) # False
     time.sleep(1)
     self.pstat.SetCell(GamryCOM.CellOn)
     time.sleep(1)
     self.readz=client.CreateObject('GamryCOM.GamryReadZ',clsctx=comtypes.CLSCTX_LOCAL_SERVER)
     self.readz.Init(self.pstat)
     self.readzsink = GamryReadZEvents(self.readz)
     self.connection = client.GetEvents(self.readz, self.readzsink)
     self.frequency_values = []
     self.wait_time_after_each_measurement = 5
     self.cycle_max = 10
     self.interrupt = False # Variable which makes it possible to stop a running measurement
     #self.setup_impedance_measurement()
     pythoncom.CoUninitialize() # Windows shit
     return
    def __start__(self):
        try:
            global cm15a
            cm15a = comcli.CreateObject("X10.ActiveHome")
        except msg:
            cm15a = None
            raise eg.Exception(msg)

        eventHandler = self.EventHandler()
        self.conn = comcli.GetEvents(cm15a, eventHandler)
        self.enabled = True
        print "X10_CM15A started..."
示例#11
0
    def ocv(self, start_freq, end_freq, points, pot_offset=0):
        Zreal, Zimag, Zsig, Zphz, Zfreq = [], [], [], [], []
        is_on = False
        self.pstat.Open()
        if offset != 0:
            self.pstat.SetVchOffsetEnable(True)
            if self.pstat.VchOffsetEnable():
                self.poti.pstat.SetVchOffset(pot_offset)
            else:
                print("Have offset but could not enable")
        for f in np.logspace(np.log10(start_freq), np.log10(end_freq), points):

            self.dtaqcpiv = client.CreateObject("GamryCOM.GamryDtaqEis")
            self.dtaqcpiv.Init(self.pstat, f, 0.1, 0.5, 20)
            self.dtaqcpiv.SetCycleMin(100)
            self.dtaqcpiv.SetCycleMax(50000)

            if not is_on:
                self.pstat.SetCell(self.GamryCOM.CellOn)
                is_on = True
            self.dtaqsink = GamryDtaqEvents(self.dtaqcpiv)

            connection = client.GetEvents(self.dtaqcpiv, self.dtaqsink)

            try:
                self.dtaqcpiv.Run(True)
            except Exception as e:
                raise gamry_error_decoder(e)
            if f < 10:
                client.PumpEvents(10)
            else:
                client.PumpEvents(1)

            Zreal.append(self.dtaqsink.dtaq.Zreal())
            Zimag.append(self.dtaqsink.dtaq.Zimag())
            Zsig.append(self.dtaqsink.dtaq.Zsig())
            Zphz.append(self.dtaqsink.dtaq.Zphz())
            Zfreq.append(self.dtaqsink.dtaq.Zfreq())
            print(self.dtaqsink.dtaq.Zfreq())
            del connection
        self.pstat.SetCell(self.GamryCOM.CellOff)
        self.pstat.Close()
        return {
            "measurement_type": "eis",
            "parameters": {
                "tart_freq": start_freq,
                "end_freq": end_freq,
                "points": points,
                "pot_offset": pot_offset,
            },
            "data": [Zreal, Zimag, Zfreq],
        }
示例#12
0
 def __init__(self):
     threading.Thread.__init__(self)
     cc.GetModule(
         os.path.split(os.path.realpath(__file__))[0] + r'\SKCOM.dll')
     from comtypes.gen import SKCOMLib as sk
     self.skC = cc.CreateObject(sk.SKCenterLib, interface=sk.ISKCenterLib)
     self.skQ = cc.CreateObject(sk.SKQuoteLib, interface=sk.ISKQuoteLib)
     self.EventQ = self.skQ_events(self)
     self.ConnectionQ = cc.GetEvents(self.skQ, self.EventQ)
     self.feature_list = []
     self.option_list = []
     self.feature_code = ""
     self.option_code = ""
     self.watchdog = 0
	def __init__(self,tid,tpw,log):
		threading.Thread.__init__(self)
		cc.GetModule(os.path.split(os.path.realpath(__file__))[0] + r'\lib\SKCOM.dll')
		from comtypes.gen import SKCOMLib as sk
		self.skC=cc.CreateObject(sk.SKCenterLib,interface=sk.ISKCenterLib)
		self.skQ=cc.CreateObject(sk.SKQuoteLib,interface=sk.ISKQuoteLib)
		self.skR=cc.CreateObject(sk.SKReplyLib,interface=sk.ISKReplyLib)
		#Configuration
		self.EventQ=self.skQ_events(self)
		self.ConnectionQ = cc.GetEvents(self.skQ, self.EventQ)
		self.EventR=self.skR_events(self)
		self.ConnectionR = cc.GetEvents(self.skR, self.EventR)
		self.feature_list=[]
		self.option_list=[]
		self.stock_list=[]
		self.feature_code=[]
		self.option_code=[]
		self.stock_code=[]
		self.status=[False,False,False,False]
		self.watchdog=0
		self.id=tid
		self.pw=tpw
		self.log=log
示例#14
0
 def ApplicationEvents4_NewDocument(self, this, doc):            
     for doc_idx in range(self.com_handle.Documents.Count):
         idx1 = doc_idx+1
         if self.com_handle.Documents.Item(idx1) == doc:
             doc = self.com_handle.Documents.Item(idx1)
             doc_wrapper = WordDocumentObject(parent=self, handle=doc)
             doc_wrapper._event_connection = client.GetEvents(doc, doc_wrapper)
             self._doc_list.append(doc_wrapper)          
     self.parent_node.notify_observers(Event(
         sender = this,
         name = "NewDocument",
         kwargs = dict(
             app='Word',
             source='Application',
             doc=doc)))
示例#15
0
    def eis(self, start_freq, end_freq, points, pot_offset=0):
        Zreal, Zimag, Zsig, Zphz, Zfreq = [], [], [], [], []
        is_on = False
        self.pstat.Open()
        for f in np.logspace(np.log10(start_freq), np.log10(end_freq), points):

            self.dtaqcpiv = client.CreateObject('GamryCOM.GamryDtaqEis')
            self.dtaqcpiv.Init(self.pstat, f, 0.05, 0.5, 20)
            self.dtaqcpiv.SetCycleMin(100)
            self.dtaqcpiv.SetCycleMax(50000)

            if not is_on:
                self.pstat.SetCell(self.GamryCOM.CellOn)
                is_on = True
            self.dtaqsink = GamryDtaqEvents(self.dtaqcpiv)

            connection = client.GetEvents(self.dtaqcpiv, self.dtaqsink)

            try:
                self.dtaqcpiv.Run(True)
            except Exception as e:
                raise gamry_error_decoder(e)
            if f < 10:
                client.PumpEvents(10)
            if f > 1000:
                client.PumpEvents(0.1)
            if f < 1000:
                client.PumpEvents(1)

            Zreal.append(self.dtaqsink.dtaq.Zreal())
            Zimag.append(self.dtaqsink.dtaq.Zimag())
            Zsig.append(self.dtaqsink.dtaq.Zsig())
            Zphz.append(self.dtaqsink.dtaq.Zphz())
            Zfreq.append(self.dtaqsink.dtaq.Zfreq())
            print(self.dtaqsink.dtaq.Zfreq())
            del connection
        self.pstat.SetCell(self.GamryCOM.CellOff)
        self.pstat.Close()
        return {
            'measurement_type': 'eis',
            'parameters': {
                'tart_freq': start_freq,
                'end_freq': end_freq,
                'points': points,
                'pot_offset': pot_offset
            },
            'data': [Zreal, Zimag, Zfreq]
        }
示例#16
0
 def set_sink(self, sink, wql_str):
     self.__com_sink = com_sink = client.CreateObject(
         'WbemScripting.SWbemSink')
     py_sink = sink
     self.__connection = client.GetEvents(com_sink, py_sink)
     self.__services.ExecNotificationQueryAsync(com_sink, wql_str)
示例#17
0
文件: api.py 项目: richard0521/-api-
        if Code == 0:
            if nKind == 3001:
                print("連線中, nKind = ", nKind)
            elif Code == 0 & (nKind == 3003):
                print("連線成功, nKind = ", nKind)

    def OnNotifyKlineData(self, bstrStockNo, bstrData):
        #
        self.KlineData.append(bstrData.split(','))


# Event sink, 事件實體
EventQ = skQ_events()

# make connnection to event sink
ConnectionQ = cc.GetEvents(skQ, EventQ)

# 登入,連線報價主機
print("Login,",
      skC.SKCenterlib_GetReturnCodeMessage(skC.SKCenterLib_Login(ID, PW)))
print("EnterMonitor,",
      skC.SKCenterLib_GetReturnCodeMassege(skQ.SKQuoteLib_EnterMonitor()))
pumpwait(8)

#讀取加權日k歷史報價
# bstrStockNo 放股票代碼
# sKineType,0 = 1分鐘線, 3 = 日線288天, 4 = 完整日線, 5 = 週線, 6 = 月線
# sQutType, 0 = 舊版輸出格式, 1 = 新版輸出格式。新版格式一分日期與分時資料是個一個欄位
# 將data 站存至 EventQ.KineData
EventQ.KlineData = []
示例#18
0
 def AddEventSink(self, sink, interface=None):
     """
     Add a new target to search for method names that match the COM
     Event names.
     """
     self._evt_connections.append(cc.GetEvents(self._ax, sink, interface))
            # see for price types in TrueDataFields of Truedata_Velocity_External type library
            price_type = price.id
            value = price.data
            print("RT Update:", symbol, price_type, str(date), value)
            if price_type == 4109:
                print(symbol, str(date), value)


# create object
truedata = cc.CreateObject("TrueDataExternal.1")

#  create sink class to receive events
sink = TrueDataExternalEventsSink()

#  advise the sink to make it receiving events
advise = cc.GetEvents(truedata, sink)

#  initialize API
truedata.VelocityInitialize()

#  wait while Velocity starts
truedata.VelocityWaitForReadyToProcess()
print("Velocity has been started", datetime.datetime.now())

datefrom = datetime2ole(datetime.datetime.utcnow() -
                        datetime.timedelta(minutes=deltamins))
dateto = datetime2ole(datetime.datetime.utcnow())
RequestIdTicks = truedata.RequestTicks(symbol_list[sindex], datefrom, dateto)

#  Tick  History Data
示例#20
0
 def hook_event(self, event):
     return cc.GetEvents(self._component, event)
示例#21
0
readz=client.CreateObject('GamryCOM.GamryReadZ')
readz.Init(pstat)


#sigramp=client.CreateObject('GamryCOM.GamrySignalRamp')
#sigramp.Init(pstat, -0.25, 0.25, 1, 0.01, GamryCOM.PstatMode)

#pstat.SetSignal(sigramp)
#pstat.SetCell(GamryCOM.CellOn)

readzsink = GamryReadZEvents(readz)

# Use the following code to discover events:
#client.ShowEvents(readz)
connection = client.GetEvents(readz, readzsink)

try:
    for i in range(10):
        readz.Measure(i,0.1)
except Exception as e:
    raise gamry_error_decoder(e)

client.PumpEvents(1)
print len(readzsink.acquired_points)
print readzsink.acquired_points

del connection

pstat.Close()
pstat.Init(devices.EnumSections()[0])  # grab first pstat

pstat.Open()

dtaqcpiv = client.CreateObject('GamryCOM.GamryDtaqCpiv')
dtaqcpiv.Init(pstat)

sigramp = client.CreateObject('GamryCOM.GamrySignalRamp')
sigramp.Init(pstat, -0.25, 0.25, 1, 0.01, GamryCOM.PstatMode)

pstat.SetSignal(sigramp)
pstat.SetCell(GamryCOM.CellOn)

dtaqsink = GamryDtaqEvents(dtaqcpiv)

# Use the following code to discover events:
#client.ShowEvents(dtaqcpiv)
connection = client.GetEvents(dtaqcpiv, dtaqsink)

try:
    dtaqcpiv.Run(True)
except Exception as e:
    raise gamry_error_decoder(e)

client.PumpEvents(1)
print len(dtaqsink.acquired_points)

del connection

pstat.Close()