def __init__(self, device_name='/dev/ttyUSB0', all_attached_device_names=[],
                 baud_rate='9600', chatscript_file=None):

        super(PPP, self).__init__(device_name=device_name, baud_rate=baud_rate,
                                  chatscript_file=chatscript_file)

        self.route = Route()
        self.all_attached_device_names = all_attached_device_names
        self._ppp = PPPConnection(self.device_name, self.baud_rate, 'noipdefault',
                                  'usepeerdns', 'persist', 'noauth',
                                  #added by Jianwei Liu
                                  'debug',
                                  connect=self.connect_script)
Beispiel #2
0
    def __init__(self,
                 device_name='/dev/ttyUSB0',
                 baud_rate='9600',
                 chatscript_file=None):

        super(PPP, self).__init__(device_name=device_name,
                                  baud_rate=baud_rate,
                                  chatscript_file=chatscript_file)

        try:
            self.__enforce_no_existing_ppp_session()
        except PPPError as e:
            self.logger.error(repr(e))
            sys.exit(1)

        self._ppp = PPPConnection(self.device_name,
                                  self.baud_rate,
                                  'noipdefault',
                                  'usepeerdns',
                                  'defaultroute',
                                  'persist',
                                  'noauth',
                                  connect=self.connect_script)
Beispiel #3
0
               0, True)
        msgs.append(msg)

    # print("Messages :", msgs)  # FIXME: DEBUG

    publish.multiple(msgs,
                     hostname="io.adafruit.com",
                     port=1883,
                     auth={
                         "username": adafruit_username,
                         "password": adafruit_key
                     })

    logging.info("Published to adafruit")  # FIXME: DEBUG

    return True


# Publish data
logging.info("Connecting")
ppp = PPPConnection(sudo=False, call='claro')  # activate PPP connection
if ppp.connected():
    logging.info("Connected")
    publish_adafruit()
    time.sleep(5)
    ppp.disconnect()
    logging.info("Disconnected")

# debug
#publish_adafruit()
class PPP(IPPP):

    def __init__(self, device_name='/dev/ttyUSB0', all_attached_device_names=[],
                 baud_rate='9600', chatscript_file=None):

        super(PPP, self).__init__(device_name=device_name, baud_rate=baud_rate,
                                  chatscript_file=chatscript_file)

        self.route = Route()
        self.all_attached_device_names = all_attached_device_names
        self._ppp = PPPConnection(self.device_name, self.baud_rate, 'noipdefault',
                                  'usepeerdns', 'persist', 'noauth',
                                  #added by Jianwei Liu
                                  'debug',
                                  connect=self.connect_script)

    def isConnected(self):
        return self._ppp.connected()

    # EFFECTS: Establishes a PPP connection. If this is successful, it will also
    #          reroute packets to ppp0 interface.
    def connect(self, timeout=DEFAULT_PPP_TIMEOUT):

        self.__enforce_no_existing_ppp_session()

        result = self._ppp.connect(timeout=timeout)

        if result == True:
            if not self.route.wait_for_interface(DEFAULT_PPP_INTERFACE,
                                   MAX_PPP_INTERFACE_UP_RETRIES):
                self.logger.error('Unable to find interface %s. Disconnecting',
                        DEFAULT_PPP_INTERFACE)
                self._ppp.disconnect()
                return False
            return True
        else:
            return False


    def disconnect(self):
        self._ppp.disconnect()
        self.__shut_down_existing_ppp_session()
        return True

    # EFFECTS: Makes sure that there are no existing PPP instances on the same
    #          device interface.
    def __enforce_no_existing_ppp_session(self):

        pid_list = self.__check_for_existing_ppp_sessions()

        if len(pid_list) > 0:
            raise PPPError('Existing PPP session(s) are established by pid(s) %s. Please close/kill these processes first'
                             % pid_list)

    def __shut_down_existing_ppp_session(self):
        pid_list = self.__check_for_existing_ppp_sessions()

        # Process this only if it is a valid PID integer.
        for pid in pid_list:
            self.logger.info('Killing pid %s that currently have an active PPP session',
                             pid)
            psutil.Process(pid).terminate()

    def __check_for_existing_ppp_sessions(self):

        existing_ppp_pids = []
        self.logger.info('Checking for existing PPP sessions')

        for proc in psutil.process_iter():
            try:
                pinfo = proc.as_dict(attrs=['pid', 'name'])
            except:
                raise PPPError('Failed to check for existing PPP sessions')

            if 'pppd' in pinfo['name']:
                self.logger.info('Found existing PPP session on pid: %s', pinfo['pid'])
                existing_ppp_pids.append(pinfo['pid'])

        return existing_ppp_pids

    @property
    def localIPAddress(self):
        return self._ppp.raddr

    @property
    def remoteIPAddress(self):
        return self._ppp.laddr
Beispiel #5
0
    def _loop(self, config, status):
        """Overloaded method: Main loop taking care of link connection.
        """
        log = logging.getLogger(__name__)
        self._status['status'] = 'NOT_CONNECTED'
        self._modem = None
        pppdconn = None
        error_status = None

        while True:
            if self._status['status'] != 'CONNECTED':

                self._status['ifname'] = None
                modem = None
                try:
                    modem = self._get_modem()
                except Exception:
                    pass

                if modem is not None and self._at_modem.registered(modem['port_control']) is True:

                    # create neccessary files and connect
                    lte_cfg = config['lte']
                    self._status['status'] = 'CONNECTING'

                    if 'wwan' in modem:
                        error = None
                        connected = False
                        try:
                            self._at_modem.ndis_connect(lte_cfg['apn'], modem['port_control'])
                        except Exception as e:
                            error = 'Cannot connect: ' + str(e)

                        time.sleep(5)  # wait for connected
                        if error is None:
                            try:
                                connected = self._at_modem.ndis_connected(modem['port_control'])
                            except Exception as e:
                                error = 'Cannot get connection status: ' + str(e)

                        if connected:
                            if tools.gen_systemd_networkd(self.__class__.__name__, {'dhcp': True},
                                                          ifname=modem['wwan']):
                                os.system('/bin/ip link set dev %s up' % modem['wwan'])
                                tools.systemd_restart('systemd-networkd')
                                log.info('Created systemd-networkd configuration for %s' % modem['wwan'])


                            log.info('Link layer of LTE connected')
                            log.info('Network info: %s' % str(self._at_modem.network_info(modem['port_control'])))
                            log.info('Signal: %s' % str(self._at_modem.signal(modem['port_control'])))
                            self._status['status'] = 'CONNECTED'
                            self._status['error'] = None
                            self._ev_conn.set()  # update online status
                            self._status['ifname'] = modem['wwan']
                            #self._status['dns'] = pppdconn.dns()

                        else:
                            self._status['error'] = 'Cannot connect (NDIS)'

                    else:
                        # ppp connection
                        pppd_params = self._pppd_params(lte_cfg['apn'],
                                                        lte_cfg['number'],
                                                        lte_cfg['user'],
                                                        lte_cfg['password'])

                        pppd_params = shlex.split(pppd_params)

                        self._terminate_pppd()
                        time.sleep(1)
                        try:
                            pppdconn = PPPConnection(*pppd_params)
                        except Exception as e:
                            self._status['error'] = 'Cannot connect: ' + str(e)
                            if hasattr(e, 'output') and e.output is not None:
                                self._status['error'] += ' pppd output: ' + e.output[-500:]
                        else:
                            log.info('Link layer of LTE connected')
                            log.info('Network info: %s' % str(self._at_modem.network_info(modem['port_control'])))
                            log.info('Signal: %s' % str(self._at_modem.signal(modem['port_control'])))
                            self._status['status'] = 'CONNECTED'
                            self._status['error'] = None
                            self._ev_conn.set()  # update online status
                            self._status['ifname'] = 'ppp0'
                            self._status['dns'] = pppdconn.dns()

                else:
                    self._status['error'] = 'NO_DEVICE_DETECTED'

            if self._status['status'] == 'CONNECTED':

                if 'wwan' in modem:
                    try:
                        if not self._at_modem.ndis_connected(modem['port_control']):
                            self._status['error'] = 'Connection interrupted'
                            self._status['status'] = 'NOT_CONNECTED'
                    except Exception as e:
                        self._status['error'] = 'Connection interrupted: ' + str(e)
                        self._status['status'] = 'NOT_CONNECTED'
                else:
                    try:
                        ret = pppdconn.connected()
                    except Exception as e:
                        self._status['error'] = 'Connection interrupted: ' + str(e)
                        if hasattr(e, 'output') and e.output is not None:
                            self._status['error'] += ' pppd output: ' + e.output[-500:]
                        self._status['status'] = 'NOT_CONNECTED'
                    else:
                        self._status['error'] = None
                        if ret is False:
                            self._status['error'] = 'Connection interrupted'
                            self._status['status'] = 'NOT_CONNECTED'

            if error_status != self._status['error']:
                if self._status['error'] is not None:
                    log.info('Error: %s' % (self._status['error']))
                    self._ev_conn.set()  # update online status
                error_status = self._status['error']
                if modem is not None:
                    log.info('Network info: %s' % str(self._at_modem.network_info(modem['port_control'])))
                    log.info('Signal: %s' % str(self._at_modem.signal(modem['port_control'])))

            time.sleep(10)

# Enable USB port
usb_enable()
time.sleep(5)

# Connect using PPP (3 attempts with 5 minutes interval)
for i in range(1, 4):
    connected = False
    logging.info("Connecting...")
    print "Connecting"
    while True:
        try:
            logging.info("Attempt n. " + str(i))
            print "Attempt n. " + str(i)
            ppp = PPPConnection(sudo=False, call='claro')
        except:
            logging.error("Failed to connect")
            print "Failed to connect"
            usb_disable()
            if i is 3:
                logging.error("!!! Unable to connect after 3 attempts, exiting")
                sys.exit("Unable to connect, exiting")
            else:
                time.sleep(30)
                # time.sleep(300)  # 5 min
                usb_enable()
                break
        else:
            logging.info("Success")
            print "Success"
Beispiel #7
0
class PPP(IPPP):
    def __init__(self,
                 device_name='/dev/ttyUSB0',
                 baud_rate='9600',
                 chatscript_file=None):

        super(PPP, self).__init__(device_name=device_name,
                                  baud_rate=baud_rate,
                                  chatscript_file=chatscript_file)

        try:
            self.__enforce_no_existing_ppp_session()
        except PPPError as e:
            self.logger.error(repr(e))
            sys.exit(1)

        self._ppp = PPPConnection(self.device_name,
                                  self.baud_rate,
                                  'noipdefault',
                                  'usepeerdns',
                                  'defaultroute',
                                  'persist',
                                  'noauth',
                                  connect=self.connect_script)

    def isConnected(self):
        return self._ppp.connected()

    # EFFECTS: Establishes a PPP connection. If this is successful, it will also
    #          reroute packets to ppp0 interface.
    def connect(self, timeout=DEFAULT_PPP_TIMEOUT):

        try:
            self.__enforce_no_existing_ppp_session()
        except PPPError as e:
            self.logger.error(repr(e))
            sys.exit(1)

        result = self._ppp.connect(timeout=timeout)

        if result == True:
            self.__reroute_packets()
        return result

    def disconnect(self):
        self.__shut_down_existing_ppp_session()
        return self._ppp.disconnect()

    # EFFECTS: Makes sure that there are no existing PPP instances on the same
    #          device interface.
    def __enforce_no_existing_ppp_session(self):

        process = self.__check_for_existing_ppp_sessions()

        if process is None:
            return

        pid = process.split(' ')[1]
        raise PPPError(
            'An existing PPP session established by pid %s is currently using the %s device interface. Please close/kill that process first'
            % (pid, self.device_name))

    def __shut_down_existing_ppp_session(self):
        process = self.__check_for_existing_ppp_sessions()

        if process is None:
            return

        pid = process.split(' ')[1]

        if pid is not None:
            kill_command = 'kill ' + str(pid)
            self.logger.info(
                'Killing pid %s that currently have an active PPP session',
                pid)
            subprocess.call(kill_command, shell=True)

    def __check_for_existing_ppp_sessions(self):
        self.logger.info('Checking for existing PPP sessions')
        out_list = subprocess.check_output(
            ['ps', '--no-headers', '-axo', 'pid,user,tty,args']).split('\n')

        # Get the end device name, ie. /dev/ttyUSB0 becomes ttyUSB0
        temp_device_name = self.device_name.split('/')[-1]

        # Iterate over all processes and find pppd with the specific device name we're using.
        for process in out_list:
            if 'pppd' in process and temp_device_name in process:
                self.logger.info('Found existing PPP session on %s',
                                 temp_device_name)
                return process

        return None

    def __reroute_packets(self):
        self.logger.info('Rerouting packets to ppp0 interface')
        subprocess.call('ip route add 10.176.0.0/16 dev ppp0', shell=True)
        subprocess.call('ip route add 10.254.0.0/16 dev ppp0', shell=True)
        subprocess.call('ip route add default dev ppp0', shell=True)

    @property
    def localIPAddress(self):
        return self._ppp.raddr

    @property
    def remoteIPAddress(self):
        return self._ppp.laddr