Initialize a proxy for a slave and a type of operation
 Read single or multiple values from a modbus slave depending on whether a Fixnum or a Range was given.
 Note that in the case of multiples, a pluralized version of the method is sent to the slave
511587
def [](key)
      if key.instance_of?(0.class)
        @slave.send("read_#{@type}", key, 1)
      elsif key.instance_of?(Range)
        @slave.send("read_#{@type}s", key.first, key.count)
      else
        raise ModBus::Errors::ProxyException, "Invalid argument, must be integer or range. Was #{key.class}"
      end
    end
1258508
def prepare(self):
        '''
        
        '''
        super(ProxyMinion, self).prepare()

        if not self.values.proxyid:
            self.error('salt-proxy requires --proxyid')

        # Proxies get their ID from the command line.  This may need to change in
        # the future.
        # We used to set this here.  Now it is set in ProxyMinionOptionParser
        # by passing it via setup_config to config.minion_config
        # self.config['id'] = self.values.proxyid

        try:
            if self.config['verify_env']:
                confd = self.config.get('default_include')
                if confd:
                    # If 'default_include' is specified in config, then use it
                    if '*' in confd:
                        # Value is of the form "minion.d/*.conf"
                        confd = os.path.dirname(confd)
                    if not os.path.isabs(confd):
                        # If configured 'default_include' is not an absolute
                        # path, consider it relative to folder of 'conf_file'
                        # (/etc/salt by default)
                        confd = os.path.join(
                            os.path.dirname(self.config['conf_file']), confd
                        )
                else:
                    confd = os.path.join(
                        os.path.dirname(self.config['conf_file']), 'proxy.d'
                    )

                v_dirs = [
                    self.config['pki_dir'],
                    self.config['cachedir'],
                    self.config['sock_dir'],
                    self.config['extension_modules'],
                    confd,
                ]

                verify_env(
                    v_dirs,
                    self.config['user'],
                    permissive=self.config['permissive_pki_access'],
                    root_dir=self.config['root_dir'],
                    pki_dir=self.config['pki_dir'],
                )
        except OSError as error:
            self.environment_failure(error)

        self.setup_logfile_logger()
        verify_log(self.config)
        self.action_log_info('Setting up "{0}"'.format(self.config['id']))

        migrations.migrate_paths(self.config)

        # Bail out if we find a process running and it matches out pidfile
        if self.check_running():
            self.action_log_info('An instance is already running. Exiting')
            self.shutdown(1)

        # TODO: AIO core is separate from transport
        # Late import so logging works correctly
        import salt.minion
        # If the minion key has not been accepted, then Salt enters a loop
        # waiting for it, if we daemonize later then the minion could halt
        # the boot process waiting for a key to be accepted on the master.
        # This is the latest safe place to daemonize
        self.daemonize_if_required()
        self.set_pidfile()
        if self.config.get('master_type') == 'func':
            salt.minion.eval_master_func(self.config)
        self.minion = salt.minion.ProxyMinionManager(self.config)
230280
def init(opts):
    '''
    
    '''
    proxy_dict = opts.get('proxy', {})
    opts['multiprocessing'] = proxy_dict.get('multiprocessing', False)
    netmiko_connection_args = proxy_dict.copy()
    netmiko_connection_args.pop('proxytype', None)
    netmiko_device['always_alive'] = netmiko_connection_args.pop('always_alive',
                                                                 opts.get('proxy_always_alive', True))
    try:
        connection = ConnectHandler(**netmiko_connection_args)
        netmiko_device['connection'] = connection
        netmiko_device['initialized'] = True
        netmiko_device['args'] = netmiko_connection_args
        netmiko_device['up'] = True
        if not netmiko_device['always_alive']:
            netmiko_device['connection'].disconnect()
    except NetMikoTimeoutException as t_err:
        log.error('Unable to setup the netmiko connection', exc_info=True)
    except NetMikoAuthenticationException as au_err:
        log.error('Unable to setup the netmiko connection', exc_info=True)
    return True
1122421
def read_raw_range(start_address, count)
      cl = ::ModBus::RTUClient.new(tty, baudrate)
      cl.with_slave(slave_id) do |slave|
        slave.read_holding_registers(start_address, count)
      end
    end
464778
def ftp_proxy(self, value):
        
        self._verify_proxy_type_compatibility(ProxyType.MANUAL)
        self.proxyType = ProxyType.MANUAL
        self.ftpProxy = value
831523
def serve_once(self):
        
        # 256 is the maximum size of a Modbus RTU frame.
        request_adu = self.serial_port.read(256)
        log.debug('<-- {0}'.format(hexlify(request_adu)))

        if len(request_adu) == 0:
            raise ValueError

        response_adu = self.process(request_adu)
        self.respond(response_adu)
224972
def write_multiple_registers(slave_id, starting_address, values):
    
    function = WriteMultipleRegisters()
    function.starting_address = starting_address
    function.values = values

    return _create_request_adu(slave_id, function.request_pdu)
1373355
def proxyInit(self):
        
        # Call init() with local XML RPC config and interface_id (the name of
        # the receiver) to receive events. XML RPC server has to be running.
        for interface_id, proxy in self.proxies.items():
            if proxy._skipinit:
                continue
            if proxy._callbackip and proxy._callbackport:
                callbackip = proxy._callbackip
                callbackport = proxy._callbackport
            else:
                callbackip = proxy._localip
                callbackport = self._localport
            LOG.debug("ServerThread.proxyInit: init('http://%s:%i', '%s')" %
                      (callbackip, callbackport, interface_id))
            try:
                proxy.init("http://%s:%i" %
                           (callbackip, callbackport), interface_id)
                LOG.info("Proxy initialized")
            except Exception as err:
                LOG.debug("proxyInit: Exception: %s" % str(err))
                LOG.warning("Failed to initialize proxy")
                self.failed_inits.append(interface_id)
154502
function(vector, options) {
    var modbus = this;
    options = options || {};
    var recvBuffer = Buffer.from([]);

    // create a tcp server
    modbus._server = net.createServer();
    modbus._server.listen(options.port || MODBUS_PORT, options.host || HOST);

    // create a server unit id
    var serverUnitID = options.unitID || UNIT_ID;

    // remember open sockets
    modbus.socks = new Map();

    modbus._server.on("connection", function(sock) {
        modbus.socks.set(sock, 0);

        modbusSerialDebug({
            action: "connected",
            address: sock.address(),
            remoteAddress: sock.remoteAddress,
            localPort: sock.localPort
        });

        sock.once("close", function() {
            modbusSerialDebug({
                action: "closed"
            });
            modbus.socks.delete(sock);
        });

        sock.on("data", function(data) {
            modbusSerialDebug({ action: "socket data", data: data });
            recvBuffer = Buffer.concat([recvBuffer, data], recvBuffer.length + data.length);

            while(recvBuffer.length > MBAP_LEN) {
                const transactionsId = recvBuffer.readUInt16BE(0);
                var pduLen = recvBuffer.readUInt16BE(4);

                // Check the presence of the full request (MBAP + PDU)
                if(recvBuffer.length - MBAP_LEN < pduLen)
                    break;

                // remove mbap and add crc16
                var requestBuffer = Buffer.alloc(pduLen + 2);
                recvBuffer.copy(requestBuffer, 0, MBAP_LEN, MBAP_LEN + pduLen);

                // Move receive buffer on
                recvBuffer = recvBuffer.slice(MBAP_LEN + pduLen);

                var crc = crc16(requestBuffer.slice(0, -2));
                requestBuffer.writeUInt16LE(crc, requestBuffer.length - 2);

                modbusSerialDebug({ action: "receive", data: requestBuffer, requestBufferLength: requestBuffer.length });
                modbusSerialDebug(JSON.stringify({ action: "receive", data: requestBuffer }));

                var sockWriter = function(err, responseBuffer) {
                    if (err) {
                        modbus.emit("error", err);
                        return;
                    }

                    // send data back
                    if (responseBuffer) {
                        // remove crc and add mbap
                        var outTcp = Buffer.alloc(responseBuffer.length + 6 - 2);
                        outTcp.writeUInt16BE(transactionsId, 0);
                        outTcp.writeUInt16BE(0, 2);
                        outTcp.writeUInt16BE(responseBuffer.length - 2, 4);
                        responseBuffer.copy(outTcp, 6);

                        modbusSerialDebug({ action: "send", data: responseBuffer });
                        modbusSerialDebug(JSON.stringify({ action: "send string", data: responseBuffer }));

                        // write to port
                        sock.write(outTcp);
                    }
                };

                // parse the modbusRTU buffer
                setTimeout(
                    _parseModbusBuffer.bind(this,
                        requestBuffer,
                        vector,
                        serverUnitID,
                        sockWriter
                    ),
                    0
                );
            }
        });

        sock.on("error", function(err) {
            modbusSerialDebug(JSON.stringify({ action: "socket error", data: err }));

            modbus.emit("socketError", err);
        });
    });
    EventEmitter.call(this);
}
1177886
def write_data(self, variable_id, value, task):
        
        if variable_id not in self.variables:
            return False

        if not self.variables[variable_id].writeable:
            return False

        if self.variables[variable_id].modbusvariable.function_code_read == 3:
            # write register
            if 0 <= self.variables[variable_id].modbusvariable.address <= 65535:

                if self._connect():
                    if self.variables[variable_id].get_bits_by_class() / 16 == 1:
                        # just write the value to one register
                        self.slave.write_register(self.variables[variable_id].modbusvariable.address, int(value),
                                                  unit=self._unit_id)
                    else:
                        # encode it first
                        self.slave.write_registers(self.variables[variable_id].modbusvariable.address,
                                                   list(self.variables[variable_id].encode_value(value)),
                                                   unit=self._unit_id)
                    self._disconnect()
                    return True
                else:
                    logger.info("device with id: %d is now accessible" % self.device.pk)
                    return False
            else:
                logger.error('Modbus Address %d out of range' % self.variables[variable_id].modbusvariable.address)
                return False
        elif self.variables[variable_id].modbusvariable.function_code_read == 1:
            # write coil
            if 0 <= self.variables[variable_id].modbusvariable.address <= 65535:
                if self._connect():
                    self.slave.write_coil(self.variables[variable_id].modbusvariable.address, bool(value),
                                          unit=self._unit_id)
                    self._disconnect()
                    return True
                else:
                    logger.info("device with id: %d is now accessible" % self.device.pk)
                    return False
            else:
                logger.error('Modbus Address %d out of range' % self.variables[variable_id].modbusvariable.address)
        else:
            logger.error('wrong type of function code %d' %
                         self.variables[variable_id].modbusvariable.function_code_read)
            return False
594654
def ssl_proxy(self, value):
        
        self._verify_proxy_type_compatibility(ProxyType.MANUAL)
        self.proxyType = ProxyType.MANUAL
        self.sslProxy = value
1178815
def __init(self):
        
        params = {
            "f" : "json"
        }
        json_dict = self._get(url=self._url, param_dict=params,
                                 securityHandler=self._securityHandler,
                                 proxy_url=self._proxy_url,
                                 proxy_port=self._proxy_port)
        attributes = [attr for attr in dir(self)
                      if not attr.startswith('__') and \
                      not attr.startswith('_')]
        for k,v in json_dict.items():
            if k in attributes:
                setattr(self, "_"+ k, json_dict[k])
            else:
                print( k, " - attribute not implemented in RouteNetworkLayer.")
            del k,v
317357
def srandmember(self, name, number=None):
        
        with self.pipe as pipe:
            f = Future()
            res = pipe.srandmember(self.redis_key(name), number=number)

            def cb():
                if number is None:
                    f.set(self.valueparse.decode(res.result))
                else:
                    f.set([self.valueparse.decode(v) for v in res.result])

            pipe.on_execute(cb)
            return f
1093805
def init(*args, **kwargs):
    
    global _initial_client
    client = Client(*args, **kwargs)
    Hub.current.bind_client(client)
    rv = _InitGuard(client)
    if client is not None:
        _initial_client = weakref.ref(client)
    return rv
977151
def _init_redis_shards(self):
        
        self._shards = {}
        if self._sentinels is not None:
            self.init_shards_from_sentinel()
        elif self._masters is not None:
            self.init_shards_from_masters()
        else:
            raise Exception("You must either specify sentinels or masters")
512400
def init(opts=None):
    '''
    
    '''
    if opts is None:
        opts = __opts__
    try:
        DETAILS[_worker_name()] = SSHConnection(
            host=opts['proxy']['host'],
            username=opts['proxy']['username'],
            password=opts['proxy']['password'],
            key_accept=opts['proxy'].get('key_accept', False),
            ssh_args=opts['proxy'].get('ssh_args', ''),
            prompt='{0}.*(#|>) '.format(opts['proxy']['prompt_name']))
        DETAILS[_worker_name()].sendline('no cli session paging enable')

    except TerminalException as e:
        log.error(e)
        return False
    DETAILS['initialized'] = True
1197554
private void setProxy(String proxyStr) {
    String[] strs = proxyStr.split(":", 2);
    if (strs.length != 2)
      throw new RuntimeException("Bad SOCKS proxy parameter: " + proxyStr);
    String host = strs[0];
    int port = Integer.parseInt(strs[1]);
    this.proxy =
        new Proxy(Proxy.Type.SOCKS, InetSocketAddress.createUnresolved(host,
            port));
  }