Beispiel #1
0
 def run(cls):
     """
     Main method, runs socket server with interpreter shell
     """
     cls.server_console(
         "[ socket server ] SERVER ADDR: telnet {} {}".format(
             cfgget("devip"), cls.__port))
     try:
         cfgput('version', cls.__socket_interpreter_version)
     except Exception as e:
         console_write(
             "Export system version to config failed: {}".format(e))
         errlog_add('socket run system version export error: {}'.format(e))
     cls.__init_socket()
     while True and cls.__isconn:
         try:
             # Evaluate incoming msg via InterpreterShell -> InterpreterCore "Console prompt"
             is_healthy = shell(cls.__wait_for_msg(), sso=cls)
             if not is_healthy:
                 console_write(
                     "[EXEC-WARNING] InterpreterShell internal error.")
                 cls.__recovery(is_critic=False)
         except OSError:
             # Broken pipe error handling
             cls.__reconnect()
         except Exception as e:
             console_write(
                 "[EXEC-ERROR] InterpreterShell error: {}".format(e))
             errlog_add("Socket-InterpreterShell error: {}".format(e))
             cls.__recovery(is_critic=True)
         # Memory dimensioning dump
         cls.server_console(
             '[X] AFTER INTERPRETER EXECUTION FREE MEM [byte]: {}'.format(
                 mem_free()))
Beispiel #2
0
def set_uid_macaddr_hex(interface):
    try:
        cfgput(
            'hwuid',
            'micr{}OS'.format(hexlify(interface.config('mac'), 'x').decode()))
    except Exception:
        pass
Beispiel #3
0
 def run(self):
     self.server_console(
         "[ socket server ] SERVER ADDR: telnet {} {}".format(
             cfgget("devip"), self.__port))
     try:
         cfgput('version', self.__socket_interpreter_version)
     except Exception as e:
         console_write(
             "Export system version to config failed: {}".format(e))
     self.__init_socket()
     self.__bind_and_accept()
     while True:
         try:
             # Evaluate incoming msg via InterpreterShell -> InterpreterCore "Console prompt"
             is_healthy = InterpreterShell_shell(self.__wait_for_message(),
                                                 SocketServerObj=self)
             if not is_healthy:
                 console_write(
                     "[EXEC-WARNING] InterpreterShell internal error.")
                 self.__recovery(is_critic=False)
         except OSError:
             # BrokenPipeError
             self.__reconnect()
         except Exception as e:
             console_write(
                 "[EXEC-ERROR] InterpreterShell error: {}".format(e))
             self.__recovery(is_critic=True)
         # Memory dimensioning dump
         self.server_console(
             '[X] AFTER INTERPRETER EXECUTION FREE MEM [byte]: {}'.format(
                 mem_free()))
Beispiel #4
0
def set_wifi(essid, pwd, timeout=60):
    console_write('[NW: STA] SET WIFI: {}'.format(essid))
    essid_found = False

    # Disable AP mode
    ap_if = WLAN(AP_IF)
    if ap_if.active():
        ap_if.active(False)
    del ap_if

    # Set STA and Connect
    sta_if = WLAN(STA_IF)
    sta_if.active(True)
    if not sta_if.isconnected():
        console_write('\t| [NW: STA] CONNECT TO NETWORK {}'.format(essid))
        # Scan wifi network - retry workaround
        for _ in range(0, 2):
            if essid in (wifispot[0].decode('utf-8')
                         for wifispot in sta_if.scan()):
                essid_found = True
                console_write(
                    '\t| - [NW: STA] ESSID WAS FOUND {}'.format(essid_found))
                break
            sleep(1)
        # Connect to the located wifi network
        if essid_found:
            # connect to network
            sta_if.connect(essid, pwd)
            # wait for connection, with timeout set
            while not sta_if.isconnected() and timeout > 0:
                console_write("\t| [NW: STA] Waiting for connection... " +
                              str(timeout) + "/60")
                timeout -= 1
                sleep(0.5)
            # Set static IP - here because some data comes from connection.
            if sta_if.isconnected() and __set_wifi_dev_static_ip(sta_if):
                sta_if.disconnect()
                del sta_if
                return set_wifi(essid, pwd)
        else:
            console_write(
                "\t| [NW: STA] Wifi network was NOT found: {}".format(essid))
            return False
        console_write("\t|\t| [NW: STA] network config: " +
                      str(sta_if.ifconfig()))
        console_write("\t|\t| [NW: STA] CONNECTED: " +
                      str(sta_if.isconnected()))
    else:
        console_write("\t| [NW: STA] ALREADY CONNECTED TO {}".format(essid))
    cfgput("devip", str(sta_if.ifconfig()[0]))
    set_uid_macaddr_hex(sta_if)
    return sta_if.isconnected()
Beispiel #5
0
def set_wifi(essid, pwd, timeout=60):
    console_write('[NW: STA] SET WIFI STA NW {}'.format(essid))

    # Disable AP mode
    ap_if = WLAN(AP_IF)
    if ap_if.active():
        ap_if.active(False)
    del ap_if

    # Set STA and Connect
    sta_if = WLAN(STA_IF)
    sta_if.active(True)
    # Set custom DHCP hostname
    sta_if.config(dhcp_hostname=cfgget('devfid'))
    # Check are we already connected
    if not sta_if.isconnected():
        # Multiple essid and pwd handling with retry mechanism
        essid, pwd = __select_available_wifi_nw(sta_if, essid, pwd)

        # Connect to the located wifi network
        if essid is not None:
            console_write('\t| [NW: STA] CONNECT TO NETWORK {}'.format(essid))
            # connect to network
            sta_if.connect(essid, pwd)
            # wait for connection, with timeout set
            while not sta_if.isconnected() and timeout > 0:
                console_write(
                    "\t| [NW: STA] Waiting for connection... {} sec".format(
                        timeout))
                timeout -= 1
                sleep_ms(500)
            # Set static IP - here because some data comes from connection. (subnet, etc.)
            if sta_if.isconnected() and __set_wifi_dev_static_ip(sta_if):
                sta_if.disconnect()
                del sta_if
                return set_wifi(essid, pwd)
        else:
            console_write(
                "\t| [NW: STA] Wifi network was NOT found: {}".format(essid))
            return False
        console_write("\t|\t| [NW: STA] network config: " +
                      str(sta_if.ifconfig()))
        console_write("\t|\t| [NW: STA] CONNECTED: " +
                      str(sta_if.isconnected()))
    else:
        console_write("\t| [NW: STA] ALREADY CONNECTED TO {}".format(essid))
    cfgput("devip", str(sta_if.ifconfig()[0]))
    set_dev_uid()
    return sta_if.isconnected()
Beispiel #6
0
def __configure(attributes, SocketServerObj):
    # [CONFIG] Get value
    if len(attributes) == 1:
        if attributes[0] == 'dump':
            # DUMP DATA
            for key, value in read_cfg_file().items():
                spcr = (10 - len(key))
                SocketServerObj.reply_message("  {}{}:{} {}".format(key, " " * spcr, " " * 7, value))
            return True
        # GET SINGLE PARAMETER VALUE
        SocketServerObj.reply_message(cfgget(attributes[0]))
        return True
    # [CONFIG] Set value
    if len(attributes) >= 2:
        # Deserialize params
        key = attributes[0]
        value = " ".join(attributes[1:])
        # Check irq required memory
        if 'irq' in key and attributes[1].lower() == 'true':
            isOK, avmem = __irq_mem_requirement_check(key)
            if not isOK:
                SocketServerObj.reply_message("Skip ... feature requires more memory then {} byte".format(avmem))
                return True
        # Set new parameter(s)
        try:
            output = cfgput(key, value, type_check=True)
        except Exception as e:
            SocketServerObj.reply_message("node_config write error: {}".format(e))
            output = False
        # Evaluation and reply
        issue_msg = 'Invalid key' if cfgget(key) is None else 'Failed to save'
        SocketServerObj.reply_message('Saved' if output else issue_msg)
    return True
Beispiel #7
0
def auto_network_configuration(retry=3):
    for _ in range(0, retry):
        # SET WIFI (STA) MODE
        state = set_wifi(cfgget("staessid"), cfgget("stapwd"))
        if state:
            # Save STA NW mode
            cfgput("nwmd", "STA")
            # Set NTP - RTC
            setNTP_RTC()
            # BREAK - STA mode successfully  configures
            break
        # SET AP MODE
        state = set_access_point(cfgget("devfid"), cfgget("appwd"))
        if state:
            # Save AP NW mode
            cfgput("nwmd", "AP")
            # BREAK - AP mode successfully  configures
            break
Beispiel #8
0
def set_access_point(_essid, _pwd, _authmode=3):
    console_write("[NW: AP] SET AP MODE: {} - {} - auth mode: {}".format(
        _essid, _pwd, _authmode))

    sta_if = WLAN(STA_IF)
    if sta_if.isconnected():
        sta_if.active(False)

    ap_if = WLAN(AP_IF)
    ap_if.active(True)
    # Set WiFi access point name (formally known as ESSID) and WiFi authmode (2): WPA2
    try:
        console_write("[NW: AP] Configure")
        ap_if.config(essid=_essid, password=_pwd, authmode=_authmode)
    except Exception as e:
        console_write("[NW: AP] Config Error: {}".format(e))
    if ap_if.active() and str(ap_if.config('essid')) == str(
            _essid) and ap_if.config('authmode') == _authmode:
        cfgput("devip", ap_if.ifconfig()[0])
    console_write("\t|\t| [NW: AP] network config: " + str(ap_if.ifconfig()))
    set_uid_macaddr_hex(ap_if)
    return ap_if.active()
    def run(self):
        if "esp" in platform:
            self.server_console("[ socket server ] SERVER ADDR: telnet " +
                                str(cfgget("devip")) + " " + str(self.port))
        else:
            self.server_console(
                "[ socket server ] SERVER ADDR: telnet 127.0.0.1 " +
                str(self.port))

        try:
            cfgput('version', self.__socket_interpreter_version)
        except Exception as e:
            console_write(
                "Export system version to config failed: {}".format(e))
        self.__init_socket()
        self.__bind_and_accept()
        while True:
            try:
                # Evaluate incoming msg via InterpreterShell -> InterpreterCore "Console prompt"
                is_healthy, msg = InterpreterShell_shell(
                    self.__wait_for_message(), SocketServerObj=self)
                if not is_healthy:
                    console_write(
                        "[EXEC-WARNING] InterpreterShell internal error: {}".
                        format(msg))
                    self.__recovery(errlvl=0)
            except OSError:
                # BrokenPipeError
                self.__reconnect()
            except Exception as e:
                console_write(
                    "[EXEC-ERROR] InterpreterShell error: {}".format(e))
                self.__recovery(errlvl=1)
            # Memory dimensioning dump
            if mem_free is not None:
                self.server_console(
                    '[X] AFTER INTERPRETER EXECUTION FREE MEM [byte]: {}'.
                    format(mem_free()))
Beispiel #10
0
def __configure(attributes, sso):
    """
    :param attributes: socket input param list
    :param sso: socket server object
    :return: execution status
    """
    # [CONFIG] Get value
    if len(attributes) == 1:
        if attributes[0] == 'dump':
            # DUMP DATA
            for key, value in cfgget().items():
                spcr = (10 - len(key))
                sso.reply_message("  {}{}:{} {}".format(
                    key, " " * spcr, " " * 7, value))
            return True
        # GET SINGLE PARAMETER VALUE
        sso.reply_message(cfgget(attributes[0]))
        return True
    # [CONFIG] Set value
    if len(attributes) >= 2:
        # Deserialize params
        key = attributes[0]
        value = " ".join(attributes[1:])
        # Check irq required memory
        if attributes[1].lower() == 'true':
            isOK, avmem = __irq_mem_req_check(key)
            if not isOK:
                sso.reply_message(
                    "Skip ... feature requires more memory then {} byte".
                    format(avmem))
                return True
        # Set the parameter value in config
        try:
            output = cfgput(key, value, type_check=True)
        except Exception as e:
            sso.reply_message("node_config write error: {}".format(e))
            output = False
        # Evaluation and reply
        issue_msg = 'Invalid key' if cfgget(key) is None else 'Failed to save'
        sso.reply_message('Saved' if output else issue_msg)
    return True
Beispiel #11
0
def set_uid_macaddr_hex(interface=None):
    uid = "n/a"
    if interface is not None:
        uid = ''.join([hex(ot) for ot in list(interface.config('mac'))])
    cfgput("hwuid", uid)
Beispiel #12
0
def set_dev_uid():
    try:
        cfgput('hwuid',
               'micr{}OS'.format(hexlify(unique_id()).decode('utf-8')))
    except Exception as e:
        errlog_add("set_dev_uid error: {}".format(e))