def test_initialization(self):

        with self.assertRaises(TypeError):
            pyads.Connection()

        with self.assertRaises(AttributeError):
            pyads.Connection(None, None)
Beispiel #2
0
    def test_initialization(self):
        # type: () -> None
        """Test init process."""
        with self.assertRaises(TypeError):
            pyads.Connection()

        with self.assertRaises(TypeError):
            pyads.Connection(None, None)
Beispiel #3
0
    def run(self):
        """ Executed automatically when the thread starts. """
        # Create and open a connection.
        plc = pyads.Connection(AMS_NET_ID, AMS_NET_PORT)
        plc.open()

        @plc.notification(pyads.PLCTYPE_BOOL)
        def callback(handle, name, timestamp, value):
            """ Executed when the variable changes its state. """
            data = {'name': name, 'value': value}
            self.notification_signal.emit(data)  # send data

        # Create device notifications.
        attr = pyads.NotificationAttrib(1)
        plc.add_device_notification('MAIN.qCyl1toMinus', attr, callback)
        plc.add_device_notification('MAIN.qCyl1toPlus', attr, callback)
        plc.add_device_notification('MAIN.qCyl2toMinus', attr, callback)
        plc.add_device_notification('MAIN.qCyl2toPlus', attr, callback)
        plc.add_device_notification('MAIN.qCyl3toMinus', attr, callback)
        plc.add_device_notification('MAIN.qCyl3toPlus', attr, callback)
        plc.add_device_notification('MAIN.qCyl4toMinus', attr, callback)
        plc.add_device_notification('MAIN.qCyl4toPlus', attr, callback)
        plc.add_device_notification('MAIN.qMot1start', attr, callback)
        plc.add_device_notification('MAIN.qMot2start', attr, callback)
        plc.add_device_notification('MAIN.qMot3start', attr, callback)
        plc.add_device_notification('MAIN.qMot4start', attr, callback)
def thread_plc():
    global plot_new_data
    remote_ip = '192.168.20.157'
    remote_ads = '192.168.30.202.1.1'
    plc = pyads.Connection(remote_ads, pyads.PORT_TC3PLC1, remote_ip)
    plc.open()
    symbols_list = plc.get_all_symbols()
    plc.close()
    while True:
        if not plot_new_data:
            plc.open()
            namespace = "KrogstrupMBE2.temperatureController[4].znTuner"
            time_vector_temp = plc.read_by_name(
                namespace + ".FFT_IN", pyads.PLCTYPE_REAL * (1024 * 2))
            fft_vector_temp = plc.read_by_name(namespace + ".FFT_OUT",
                                               pyads.PLCTYPE_REAL * (1024 * 2))
            plc.close()
            time_vector[1] = format_complex_array(time_vector_temp)
            fft_plc_vector[1] = format_complex_array(fft_vector_temp)

            time_vector[0] = np.arange(0, time_duration, 1 / Fs)
            fft_plc_vector[0] = np.linspace(0,
                                            Fs,
                                            len(fft_plc_vector[1]),
                                            endpoint=False)
            fft_vector[1] = fft_nonRecursive.dif_fft4(time_vector[1])
            fft_vector[0] = np.linspace(0,
                                        Fs,
                                        len(fft_vector[1]),
                                        endpoint=False)
            plot_new_data = True
        else:
            time.sleep(0.1)
        pass
Beispiel #5
0
 def setUp(self):
     # type: () -> None
     """Establish connection to the testserver."""
     self.test_server.request_history = []
     self.plc = pyads.Connection(TEST_SERVER_AMS_NET_ID,
                                 TEST_SERVER_AMS_PORT,
                                 TEST_SERVER_IP_ADDRESS)
 def setUp(self):
     # Clear request history before each test
     self.test_server.request_history = []
     self.test_server.handler.reset()
     self.plc = pyads.Connection(TEST_SERVER_AMS_NET_ID,
                                 TEST_SERVER_AMS_PORT,
                                 TEST_SERVER_IP_ADDRESS)
Beispiel #7
0
    def test_methods_with_closed_port(self):
        # type: () -> None
        """Test pyads.Connection methods with no open port."""
        with self.plc:
            adr = self.plc.get_local_address()
            self.assertIsNotNone(adr)

        plc = pyads.Connection("127.0.0.1.1.1", 851)
        self.assertIsNone(plc.get_local_address())
        self.assertIsNone(plc.read_state())
        self.assertIsNone(plc.read_device_info())
        self.assertIsNone(plc.read_write(1, 2, pyads.PLCTYPE_INT, 1, pyads.PLCTYPE_INT))
        self.assertIsNone(plc.read(1, 2, pyads.PLCTYPE_INT))
        self.assertIsNone(plc.read_by_name("hello", pyads.PLCTYPE_INT))
        self.assertIsNone(plc.get_handle("hello"))
        self.assertIsNone(
            plc.read_structure_by_name(
                "hello", (("", pyads.PLCTYPE_BOOL, 1), ("", pyads.PLCTYPE_BOOL, 1))
            )
        )
        self.assertIsNone(
            plc.add_device_notification(
                "test", pyads.NotificationAttrib(4), lambda x: x
            )
        )
    def test_no_ip_address(self):
        """
        Autogenerate IP-address from AMS net id if no ip address is given 
        on initialization.

        """
        plc = pyads.Connection(TEST_SERVER_AMS_NET_ID, TEST_SERVER_AMS_PORT)
        self.assertEqual(TEST_SERVER_IP_ADDRESS, plc.ip_address)
Beispiel #9
0
 def conn_open(self):
     """Open a connection with the TwinCAT message router."""
     try:
         self.conn = pyads.Connection(self.net_id, self.net_port)
         self.conn.open()
     except pyads.pyads_ex.ADSError as err:
         print(err)
     else:
         self.textconn.setText("Yhteys: Auki")
Beispiel #10
0
 def __init__(self, thermocouples_count) -> None:
     super().__init__()
     self.twincat_info = TwinCatConnectionInfo.from_twincat_config()
     self.plc = pyads.Connection(self.twincat_info.ams_net_id,
                                 pyads.PORT_SPECIALTASK1)
     self.thermocouples_count = thermocouples_count
     self.status_datatype = pyads.PLCTYPE_USINT
     self.value_datatype = pyads.PLCTYPE_UINT
     self.channel_size = 3
Beispiel #11
0
def setup(hass, config):
    """Set up the ADS component."""
    import pyads
    conf = config[DOMAIN]

    # get ads connection parameters from config
    net_id = conf.get(CONF_DEVICE)
    ip_address = conf.get(CONF_IP_ADDRESS)
    port = conf.get(CONF_PORT)

    # create a new ads connection
    client = pyads.Connection(net_id, port, ip_address)

    # add some constants to AdsHub
    AdsHub.ADS_TYPEMAP = {
        ADSTYPE_BOOL: pyads.PLCTYPE_BOOL,
        ADSTYPE_BYTE: pyads.PLCTYPE_BYTE,
        ADSTYPE_INT: pyads.PLCTYPE_INT,
        ADSTYPE_UINT: pyads.PLCTYPE_UINT,
    }

    AdsHub.PLCTYPE_BOOL = pyads.PLCTYPE_BOOL
    AdsHub.PLCTYPE_BYTE = pyads.PLCTYPE_BYTE
    AdsHub.PLCTYPE_INT = pyads.PLCTYPE_INT
    AdsHub.PLCTYPE_UINT = pyads.PLCTYPE_UINT
    AdsHub.ADSError = pyads.ADSError

    # connect to ads client and try to connect
    try:
        ads = AdsHub(client)
    except pyads.pyads.ADSError:
        _LOGGER.error('Could not connect to ADS host (netid=%s, port=%s)',
                      net_id, port)
        return False

    # add ads hub to hass data collection, listen to shutdown
    hass.data[DATA_ADS] = ads
    hass.bus.listen(EVENT_HOMEASSISTANT_STOP, ads.shutdown)

    def handle_write_data_by_name(call):
        """Write a value to the connected ADS device."""
        ads_var = call.data.get(CONF_ADS_VAR)
        ads_type = call.data.get(CONF_ADS_TYPE)
        value = call.data.get(CONF_ADS_VALUE)

        try:
            ads.write_by_name(ads_var, value, ads.ADS_TYPEMAP[ads_type])
        except pyads.ADSError as err:
            _LOGGER.error(err)

    hass.services.register(DOMAIN,
                           SERVICE_WRITE_DATA_BY_NAME,
                           handle_write_data_by_name,
                           schema=SCHEMA_SERVICE_WRITE_DATA_BY_NAME)

    return True
Beispiel #12
0
def connect_to_plc():
    #import pyads
    # connect to plc and open connection
    #plc = pyads.Connection("192.9.66.203.1.1", 851)     # my twincat
    plc = pyads.Connection("192.9.45.134.1.1", 851)  # lab twincat

    print("Connecting..")
    plc.open()
    print("Connected!")
    plc.read_device_info()
    return plc
Beispiel #13
0
    def test_decorated_device_notification(self):

        plc = pyads.Connection(TEST_SERVER_AMS_NET_ID, TEST_SERVER_AMS_PORT)

        @plc.notification(pyads.PLCTYPE_INT)
        def callback(handle, name, timestamp, value):
            print (handle, name, timestamp, value)

        with plc:
            plc.add_device_notification("a", pyads.NotificationAttrib(20), callback)
            plc.write_by_name("a", 1, pyads.PLCTYPE_INT)
Beispiel #14
0
 def __init__(self, ip_address, ams_id, port):
     self.running = True
     self.ip_address = ip_address
     self.ams_id = ams_id
     self.port = port
     self.symbols = {}
     self.ads = pyads.Connection(ams_id, port, ip_address=ip_address)
     self.queue = queue.Queue()
     self.thread = threading.Thread(target=self._thread, daemon=True)
     self.thread.start()
     self.poll_threads = {}
Beispiel #15
0
    def __init__(self, config):
        self.config = config

        self.plc = pyads.Connection(config['PLC_ID'], 851)
        self.lcr = bkp891.connect(config['LCR_SERIAL'])

        self.queue = Queue()
        self.worker = MeasurementWorker(self.queue, self.start_measure)

        self.callback = self.plc.notification(pyads.PLCTYPE_BOOL)(
            self._callback)

        logger.debug("Bridge created")
Beispiel #16
0
    def test_context(self):
        handler = BasicHandler()
        test_server = AdsTestServer(handler=handler, logging=False)

        with test_server:

            time.sleep(0.1)  # Give server a moment to spin up

            plc = pyads.Connection(TEST_SERVER_AMS_NET_ID,
                                   TEST_SERVER_AMS_PORT)
            with plc:
                byte = plc.read(12345, 1000, pyads.PLCTYPE_BYTE)
                self.assertEqual(byte, 0)

        time.sleep(0.1)  # Give server a moment to spin down
Beispiel #17
0
    def __init__(self,
                 ams_net_id: str,
                 ams_net_port: str,
                 plc_ip_address=None,
                 callback=None):
        self.notification_handles = []
        self.cb = callback

        try:
            print("Connecting to plc...")
            self.plc = pyads.Connection(ams_net_id, ams_net_port,
                                        plc_ip_address)
            self.plc.open()
        except pyads.ADSError as e:
            print("Ads Error: ", e)
Beispiel #18
0
    def setUp(self):
        # type: () -> None
        """Establish connection to the test server."""

        # Clear test server and handler
        self.test_server.request_history = []
        self.handler.reset()

        # Create PLC variable that is added by default
        self.test_var = PLCVariable("TestDouble",
                                    ads_type=constants.ADST_REAL64,
                                    symbol_type="LREAL")
        self.test_var.comment = "Some variable of type double"
        self.handler.add_variable(self.test_var)

        self.plc = pyads.Connection(TEST_SERVER_AMS_NET_ID,
                                    TEST_SERVER_AMS_PORT,
                                    TEST_SERVER_IP_ADDRESS)
def setup(hass: HomeAssistant, config: ConfigType) -> bool:
    """Set up the ADS component."""

    conf = config[DOMAIN]

    net_id = conf[CONF_DEVICE]
    ip_address = conf.get(CONF_IP_ADDRESS)
    port = conf[CONF_PORT]

    client = pyads.Connection(net_id, port, ip_address)

    try:
        ads = AdsHub(client)
    except pyads.ADSError:
        _LOGGER.error(
            "Could not connect to ADS host (netid=%s, ip=%s, port=%s)",
            net_id,
            ip_address,
            port,
        )
        return False

    hass.data[DATA_ADS] = ads
    hass.bus.listen(EVENT_HOMEASSISTANT_STOP, ads.shutdown)

    def handle_write_data_by_name(call: ServiceCall) -> None:
        """Write a value to the connected ADS device."""
        ads_var = call.data[CONF_ADS_VAR]
        ads_type = call.data[CONF_ADS_TYPE]
        value = call.data[CONF_ADS_VALUE]

        try:
            ads.write_by_name(ads_var, value, ADS_TYPEMAP[ads_type])
        except pyads.ADSError as err:
            _LOGGER.error(err)

    hass.services.register(
        DOMAIN,
        SERVICE_WRITE_DATA_BY_NAME,
        handle_write_data_by_name,
        schema=SCHEMA_SERVICE_WRITE_DATA_BY_NAME,
    )

    return True
Beispiel #20
0
async def initializeADS(request):
    global PLC
    if request.body_exists:
        data = await request.read()
        data = json.loads(data.decode("utf-8"))
        AMSNetID = data["target"]

        if AMSNetID != None:
            PLC = pyads.Connection(AMSNetID, 851)
            PLC.open()
            return web.json_response(
                {
                    "target": AMSNetID,
                    "description": "Service initialized"
                },
                status=200)
        else:
            return web.json_response({"description": "Wrong init information"},
                                     status=400)
Beispiel #21
0
 def check_connection_with_twincat(self):
     """ Check the connection with the TwinCAT message router. """
     try:
         self.connection = pyads.Connection(AMS_NET_ID, AMS_NET_PORT)
         self.connection.open()
         self.state = self.connection.read_state(
         )  # (adsState, deviceState)
     except pyads.pyads_ex.ADSError as error:
         # No connection.
         self.connection.close()
         self.open_messagebox_critical(error)  # open a popup window
     else:
         if self.state[0] == 5:
             # Successfull connection.
             self.open_messagebox_information()
             self.start_threading()
             self.create_mover_instances()
         else:
             # Wrong port.
             self.connection.close()
             self.open_messagebox_critical('Wrong port number.')
    def connect(self) -> bool:
        """ Connect driver.
        
        : returns: True if connection stablished False if not
        """
        # Create connection
        try:
            import pyads
            self._connection = pyads.Connection(self.net_id, self.port)
            self._connection.open()
        except Exception as e:
            self.sendDebugInfo(
                f"Connection with {self.net_id} cannot be stablished.")
            return False

        # Check connection status.
        state = self._connection.read_state()
        if state[0] == 5:
            return True
        else:
            self.sendDebugInfo(f"Driver not connected, ADS state = {state[0]}")
            return False
Beispiel #23
0
    def __init__(self, config):

        self.config = config

        self.is_error = False

        try:
            self._plc = pyads.Connection(config['PLC_ID'], 851)
        except pyads.ADSError as e:
            logger.exception(e)
            self.is_error = True
            exit(1)

        self.queue = queue.Queue()

        try:
            self._t = SeleniumWorker(self.queue, config)
        except ValueError as e:
            self.handle_error('Error during setup. Check the logs.', e)
            exit(1)

        self.callback = self._plc.notification(pyads.PLCTYPE_BOOL)(
            self._callback)
Beispiel #24
0
 def connect(self):
     import pyads
     self.contr_sys = pyads.Connection(self.ads_id, self.ads_port)
     self.contr_sys.open()
Beispiel #25
0
def setup(hass, config):
    """Set up the ADS component."""

    conf = config[DOMAIN]

    net_id = conf.get(CONF_DEVICE)
    ip_address = conf.get(CONF_IP_ADDRESS)
    port = conf.get(CONF_PORT)

    client = pyads.Connection(net_id, port, ip_address)

    AdsHub.ADS_TYPEMAP = {
        ADSTYPE_BOOL: pyads.PLCTYPE_BOOL,
        ADSTYPE_BYTE: pyads.PLCTYPE_BYTE,
        ADSTYPE_DINT: pyads.PLCTYPE_DINT,
        ADSTYPE_INT: pyads.PLCTYPE_INT,
        ADSTYPE_UDINT: pyads.PLCTYPE_UDINT,
        ADSTYPE_UINT: pyads.PLCTYPE_UINT,
    }

    AdsHub.ADSError = pyads.ADSError
    AdsHub.PLCTYPE_BOOL = pyads.PLCTYPE_BOOL
    AdsHub.PLCTYPE_BYTE = pyads.PLCTYPE_BYTE
    AdsHub.PLCTYPE_DINT = pyads.PLCTYPE_DINT
    AdsHub.PLCTYPE_INT = pyads.PLCTYPE_INT
    AdsHub.PLCTYPE_UDINT = pyads.PLCTYPE_UDINT
    AdsHub.PLCTYPE_UINT = pyads.PLCTYPE_UINT

    try:
        ads = AdsHub(client)
    except pyads.ADSError:
        _LOGGER.error(
            "Could not connect to ADS host (netid=%s, ip=%s, port=%s)",
            net_id,
            ip_address,
            port,
        )
        return False

    hass.data[DATA_ADS] = ads
    hass.bus.listen(EVENT_HOMEASSISTANT_STOP, ads.shutdown)

    def handle_write_data_by_name(call):
        """Write a value to the connected ADS device."""
        ads_var = call.data.get(CONF_ADS_VAR)
        ads_type = call.data.get(CONF_ADS_TYPE)
        value = call.data.get(CONF_ADS_VALUE)

        try:
            ads.write_by_name(ads_var, value, ads.ADS_TYPEMAP[ads_type])
        except pyads.ADSError as err:
            _LOGGER.error(err)

    hass.services.register(
        DOMAIN,
        SERVICE_WRITE_DATA_BY_NAME,
        handle_write_data_by_name,
        schema=SCHEMA_SERVICE_WRITE_DATA_BY_NAME,
    )

    return True
Beispiel #26
0
class Plc():
    __plc = pyads.Connection('127.0.0.1.1.1', 851) #local connection

    def __init__(self):
        pass

    def prepare(self):
        '''opens connection'''
        self.__plc.open()
    
    def close(self):
        ''' closes connection'''
        self.__plc.close()
    
    def __writeValue(self,variable):

        if self.__plc.is_open:
            #Writes
            
            self.__plc.write_by_name(variable.name,variable.writeValue, variable.datatype)
            variable.isDirty = False


    def __readValue(self, variable):
        
        if self.__plc.is_open:
            
            #reads
             return self.__plc.read_by_name(variable.name, variable.datatype)
 
      
    def __updateValues(self, variable):
        
        if self.__plc.is_open:

            newValue = self.__readValue(variable)
            variable.updateValue(newValue)



    def blockWriteValues(self, varList):

        if self.__plc.is_open:

            #for loop through list with variable entries
            for x in varList:

                #checks if there are unsaved changes
                if varList[x].isDirty:
                    self.__writeValue(varList[x])


       
    def blockUpdateValues(self, varList):

        if self.__plc.is_open:

            #for loop through list with variable entries
            for x in varList:

                self.__updateValues(varList[x])
Beispiel #27
0
import pyads
from time import sleep

plc = pyads.Connection('5.46.12.154.1.1',pyads.PORT_TC3PLC1)
plc.open()
print('open')
sleep(1)
print(plc.read_state())
# input('Enter to continue..')
################################################################
# Setup symbols
DRIVETIME   :float  = 2 
WAITTIME    :float  = 0.5
################################################################
# Horizontal Axis 
hEnable      = plc.get_symbol('HAVL.enable')
hForward     = plc.get_symbol('HAVL.forward')
hBackward    = plc.get_symbol('HAVL.backwards')
hResetError  = plc.get_symbol('HAVL.resetError')
################################################################
# Rotational Axis 
rEnable      = plc.get_symbol('RAVL.enable')
rForward     = plc.get_symbol('RAVL.forward')
rBackward    = plc.get_symbol('RAVL.backwards')
rResetError  = plc.get_symbol('RAVL.resetError')

################################################################
# Testing symbols
hEnable.write(False)
hForward.write(False)
hBackward.write(False)
Beispiel #28
0
    PLC_IP = '141.33.59.208'
    USERNAME = '******'
    PASSWORD = '******'
    ROUTE_NAME = '141.33.59.7'
    HOSTNAME = '141.33.59.7'
    PLC_AMS_ID = '5.34.116.124.1.1'
    pyads.add_route_to_plc(SENDER_AMS,
                           HOSTNAME,
                           PLC_IP,
                           USERNAME,
                           PASSWORD,
                           route_name=ROUTE_NAME)

    adsport = pyads.PORT_TC3PLC1
    print('using port {}'.format(adsport))
    plc = pyads.Connection(PLC_AMS_ID, adsport, PLC_IP)
    plc.set_timeout(3000)
    print('Connecting ...')
    plc.open()
    print('Connected')
    print(plc.read_device_info())
    print(plc.read_state())
    q = plc.read_by_name('MAIN.Dust5.Q', pyads.PLCTYPE_BOOL)
    print(q)
    plc.write_by_name('MAIN.Dust5.PV', 8192, pyads.PLCTYPE_WORD)
    # plc.read_by_name('global.bool_value', pyads.PLCTYPE_BOOL)
    cv = plc.read_by_name('MAIN.Dust5.CV', pyads.PLCTYPE_WORD)
    print(cv)
    print('Closing ...')
    plc.close()
    print('Closed')
#%%
import pyads

#%%
plc = pyads.Connection('127.0.0.1.1.1', pyads.PORT_TC3PLC1)

plc.open()

#%%
state = plc.read_state()

print("state: {}".format(state))

#%%
i = plc.read_by_name('POU_LD.INPUT')

print("i: {}".format(i))

#%%
i = not i

print("i: {}".format(i))

plc.write_by_name('POU_LD.INPUT', i)

#%%
plc.close()
Beispiel #30
0
import pyads
import os

# clear the screen
os.system('cls')

# title
print("PYADS Quick Demo")
print("-------------------")

# connection
plc = pyads.Connection('127.0.0.1.1.1', 851)
plc.open()

# read test
readResult = plc.read_by_name('global.bool_value', pyads.PLCTYPE_BOOL)
print('global.bool_value = ' + str(readResult))

# read and write true test
plc.write_by_name('global.bool_value', True, pyads.PLCTYPE_BOOL)
readResult = plc.read_by_name('global.bool_value', pyads.PLCTYPE_BOOL)
print('global.bool_value = ' + str(readResult))

plc.close()