A cellular router automatic apn selection method and device
Patent Information
- Application Number
- CN202610875552.X
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-06-17
- Publication Date
- 2026-10-20
AI Technical Summary
[0007]本发明实施例提供了一种蜂窝路由器自动APN选择方法及装置,可以解决现有蜂窝路由器APN自动选择方法中试错时间长、无成功记忆、MNC长度歧义、协议错配、无法自适应运营商策略变更的技术问题
同SIM卡秒级重连:通过以IMSI为主键的持久化缓存,同一SIM卡在重启、重插或重新上电时可直接命中上次成功APN,拨号时间从分钟级降至2秒以内,加速超过300倍。
Smart Images

Figure FT_1 
Figure FT_2 
Figure FT_3
Abstract
Description
Technical Field
[0001] This invention relates to the field of cellular Internet of Things (IoT) communication technology, and in particular to a method and apparatus for automatic APN selection in cellular routers. Background Technology
[0002] In scenarios involving international roaming, cross-border transportation, or mass deployment, cellular routers need to automatically select the correct APN (Access Point Name) to establish a data connection. Existing technologies have the following drawbacks: Static APN list sequential traversal (such as OpenWrt netifd): The order is hard-coded and fixed. Each attempt starts from the beginning. When there are many candidate APNs and the successful ones are at the end of the list, a single dialing failure requires waiting for about 75 seconds. The cumulative time can reach several minutes to tens of minutes. Furthermore, successful experiences cannot be remembered, and repeated trial and error are required after restarting.
[0003] Static mapping based on IMSI (such as mbpi.db in ModemManager): It only maps the default APN to the MCC+MNC in a one-way manner, and cannot record the last successful APN of the same SIM card. The same card will still start trying from the wrong APN every time it restarts, wasting a fixed 75 seconds; and the MNC length (2 or 3 digits) is not handled uniformly, which can easily lead to query failure.
[0004] Cloud-based APN distribution relies on existing network channels, creating a deadlock when there is no network during the initial activation, and does not meet offline compliance requirements.
[0005] In addition, existing solutions lack filtering for PDP protocol types (IPv4 / IPv6), resulting in wasted trial and error cycles for APNs with mismatched protocols; and without state records, it is impossible to guarantee that each APN will only be tried once in a closed cycle, and it is also impossible to automatically recover after operator policy changes.
[0006] Therefore, how to achieve localized, adaptive automatic APN selection for cellular routers, and avoid connection delays and maintenance difficulties caused by long trial-and-error times, lack of success memory, MNC length ambiguity, protocol mismatch, and inability to adapt to changes in operator policies, is a technical problem that needs to be solved by those skilled in the art. Summary of the Invention
[0007] This invention provides a method and apparatus for automatic APN selection in cellular routers, which can solve the technical problems of long trial and error time, lack of success memory, ambiguity of MNC length, protocol mismatch, and inability to adapt to changes in operator policies in existing automatic APN selection methods for cellular routers.
[0008] The first aspect of this invention provides a method for automatic APN selection in a cellular router, comprising: Read the SIM card's IMSI, and based on the mobile country code in the IMSI and the two-digit mobile network code and three-digit mobile network code used simultaneously, query the local APN database to construct a candidate APN list; The local cache is queried using IMSI as the primary key. If the corresponding APN identifier exists in the local cache and the corresponding APN is in an unused state in the candidate APN list, then the corresponding APN is selected as the APN to be dialed. If the local cache misses or the corresponding APN is already in use, the candidate APN list is traversed based on the three-state machine. Each APN maintains an unused state, a used state, and a used state in memory. The APN in the unused state is selected as the APN to be dialed in turn. The APN to be dialed is sent to the cellular module for dialing; When the dialing is successful, the identifier of the currently used APN is written to the local cache with IMSI as the primary key, and the status of the currently used APN is kept as "in use". When dialing fails, a status advancement flag is triggered, updating the status of the currently used APN to "used" and advancing to the next unused APN on the next selection. When the process reaches the end of the candidate APN list and all APNs in the candidate APN list are in a used state, the state of all APNs is reset to an unused state, forming a loop.
[0009] Optionally, the query in the local APN database based on the mobile country code in the IMSI and using both a two-digit mobile network code and a three-digit mobile network code includes: Extract a three-digit mobile country code, a two-digit mobile network code candidate, and a three-digit mobile network code candidate from the IMSI; Execute a query in the local APN database. The query conditions include a mobile country code equal to a three-digit mobile country code and a mobile network code equal to a two-digit mobile network code candidate or equal to a three-digit mobile network code candidate.
[0010] Optionally, before traversing the candidate APN list based on the three-state machine, the following steps are also included: The candidate APN list is filtered based on the PDP protocol type configured on the cellular router, and APNs whose PDP protocol type does not match the configured PDP protocol type are skipped.
[0011] Optionally, querying the local cache using IMSI as the primary key includes: Query the cache table in the local database. The cache table stores the row identifier of the APN used each time a dial-up call is successful, with IMSI as the primary key. If the query finds a match, the APN corresponding to the row identifier is retrieved.
[0012] Optionally, writing the identifier of the currently used APN to the local cache using the IMSI as the primary key includes: The INSERT OR REPLACE statement is used to write the row identifier of the currently used APN to the cache table, so that only the latest record of the same IMSI is retained in the cache table.
[0013] Optionally, the trigger state advancement flag includes: Set a global atomic flag, which is used to indicate that the next selection should advance to the next APN; When the global atom flag is set, the APN currently in use is marked as used during the next traversal, and the search continues for the next unused APN.
[0014] Optionally, resetting the status of all APNs to unused includes: The function to clear the list of candidate APNs is called to clear the used status flag of all APNs to the unused status, so that the list of candidate APNs becomes available again in the next round of dialing attempts.
[0015] A second aspect of the present invention provides an automatic APN selection device for a cellular router, comprising: The candidate pool construction module is used to read the IMSI of the SIM card, query the local APN database based on the mobile country code in the IMSI and the two-digit mobile network code and the three-digit mobile network code, and construct a candidate APN list. The cache query module is used to query the local cache using IMSI as the primary key. If the corresponding APN identifier exists in the local cache and the corresponding APN is in an unused state in the candidate APN list, then the corresponding APN is selected as the APN to be dialed. The tri-state machine traversal module is used to traverse the candidate APN list based on the tri-state machine when the local cache misses or the corresponding APN is already in use. Each APN maintains an unused state, a used state, and a used state in memory. The APN in the unused state is selected as the APN to be dialed in turn. The dialing execution module is used to send the APN to be dialed to the cellular module for dialing; The success caching module is used to write the identifier of the currently used APN to the local cache with IMSI as the primary key when the dialing is successful, and to keep the status of the currently used APN as "in use". The failure push module is used to trigger the status push flag when dialing fails, update the status of the currently used APN to "used", and push to the next unused APN on the next selection. The last loop module is used to reset the state of all APNs to unused state when the end of the candidate APN list is reached and all APNs in the candidate APN list are in a used state, thus forming a loop.
[0016] A third aspect of the present invention provides a cellular router automatic APN selection device, comprising: One or more processors; A memory on which one or more programs are stored; When the one or more programs are executed by the one or more processors, the one or more processors implement the cellular router automatic APN selection method as described in any of the above.
[0017] A fourth aspect of the present invention provides a computer storage medium for storing a program, which, when executed, is used to implement the automatic APN selection method for cellular routers as described in any of the preceding claims.
[0018] Compared with the prior art, the present invention has the following beneficial effects: Instant reconnection with the same SIM card: Through persistent caching with IMSI as the primary key, the same SIM card can directly hit the last successful APN when restarted, reinserted, or powered on again, reducing dialing time from minutes to less than 2 seconds, a speedup of over 300 times.
[0019] Tri-state single consumption and last-digit loopback: Each candidate APN is tried at most once in a closed cycle to avoid repeated trial and error; after traversing to the end, the state is automatically cleared so that the candidate pool can be used again in the new cycle, and can adapt to changes in operator APN policy without firmware upgrade.
[0020] Dual MNC Compatibility Query: Simultaneously matches 2-digit and 3-digit mobile network codes, eliminating MNC length ambiguity and ensuring that any SIM card can correctly match the operator's record.
[0021] PDP protocol family filtering: During the traversal phase, IPv4 / IPv6 APNs that do not match the device configuration are filtered, eliminating invalid trial and error and saving 75 seconds of network registration waste each time.
[0022] Fully localized and available offline: All decisions are made locally on the device, without relying on cloud networks, meeting the offline compliance requirements of industries such as power and transportation. Attached Figure Description
[0023] To more clearly illustrate the technical solutions in the embodiments of the present invention or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are only some embodiments recorded in the present invention. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.
[0024] Figure 1 A flowchart illustrating an automatic APN selection method for a cellular router provided in an embodiment of the present invention; Figure 2 A timing diagram of an automatic APN selection method for a cellular router provided in an embodiment of the present invention; Figure 3 A flowchart illustrating a method for constructing a candidate APN pool according to an embodiment of the present invention; Figure 4 A flowchart illustrating a cache hit priority method provided in an embodiment of the present invention; Figure 5 A flowchart illustrating a three-state machine last-position loop traversal method provided in an embodiment of the present invention; Figure 6 A timing diagram of a method for advancing the state of dialing failure and caching the state of dialing success provided in an embodiment of the present invention; Figure 7 This is a schematic diagram of the structure of an automatic APN selection device for a cellular router provided in an embodiment of the present invention; Figure 8 This is a schematic diagram of the structure of a device provided in an embodiment of the present invention. Detailed Implementation
[0025] This invention provides a method and apparatus for automatic APN selection in cellular routers, specifically a method for automatic APN selection in cellular routers for multi-SIM card cross-border / roaming scenarios. When the user has not pre-configured or cannot know the Access Point Name (APN) parameters of the operator to which the SIM card belongs, the router automatically completes APN matching and establishes a PDP context (Packet Data Protocol Context) within a few seconds to complete the first dial-up Internet access.
[0026] To facilitate understanding, the application scenarios of the embodiments of the present invention will be introduced first.
[0027] Before establishing a PDP context, cellular modules (such as Quectel EC25 / EG95 and Fibocom L850-GL) must be configured with APN strings, authentication credentials (user / password / auth_type), and PDP type (IPv4 / IPv6 / IPv4v6) by AT commands such as +CGDCONT / +QICSGP from the upper layer. APNs are issued by operators, with each operator having 1 to N APNs (e.g., China Mobile cmnet / cmwap, Verizon vzwinternet / vzwadmin / vzwapp / vzwclass6, AT&T nxtgenphone / broadband), and even within the same operator, they are differentiated according to service packages. If the issued APN is not in the list of networks identified by the SIM card, the module returns a +CME ERROR or a network registration timeout (typically 75 seconds), and retrying the APN still takes approximately minutes.
[0028] In international roaming scenarios, the ownership of a SIM card can be uniquely determined by the first 5 to 6 digits of the IMSI (three digits of the MCC + two or three digits of the MNC). However, when users transport their devices across borders and insert a local SIM card, or when integrators ship in bulk and do not know the final SIM card origin in advance, the cloud cannot pre-deliver the correct APN, and the router needs to make a local decision.
[0029] Existing solution A uses a static APN list with sequential hard-coded traversal. Representative implementations include the OpenWrt mainline netifd, ModemManager mm-plugin-quectel.c, and some commercial cellular router firmware (early versions of SierraAirLink and Teltonika RUT series). Its principle is to hard-code the APNs of several mainstream operators into a sequential list in the source code or configuration file. After a dialing failure, it tries the next APN in turn until any succeeds or exhaustive attempts fail. A specific example of solution A failing in a cross-border scenario: When the equipment was deployed in country A, it used a local SIM card X (IMSI starting with 460) and successfully dialed. After the customer shipped the equipment to country B, they inserted a local SIM card Y (IMSI starting with 234). Solution A still traversed the hard-coded list in the order of "China Mobile → China Unicom → AT&T → Verizon →...". If the operator in country B is ranked lower in the list (e.g., SingTel in Singapore is ranked 17th), the router needs to experience 16 incorrect APNs × approximately 75 seconds per attempt = 20 minutes to complete the first dial-up. During large-scale deployment and on-site debugging, workers cannot determine whether the equipment is "faulty" or "still in trial and error," leading to significant work delays and rework. Furthermore, list updates rely on firmware upgrades; a new version must be released after a new operator is added or the APN changes.
[0030] Existing Solution B is a "one-time" static mapping of operator → APN based on IMSI. A representative implementation includes the mobile-broadband-provider-info database in ModemManager and a plugin for Linux NetworkManager. When the device boots up, it reads the IMSI, extracts only the MCC+MNC key, queries the local database mbpi.db, and if a match is found, it issues the specified "default" APN; otherwise, it prompts the user to enter it manually. In this solution, the database uses a one-way mapping of "operator → APN" and does not record the "previous successful APN". A specific example of Solution B failing in a multi-SIM, multi-operator scenario is as follows: Some operators offer multiple APNs for the same IMSI segment. For example, Verizon's IMSI 311480 segment supports vzwinternet (consumer class), vzwadmin (administrative class), vzwapp (application class), and vzwclass6 (private network class). Which APN the SIM card is actually registered with depends on the customer's contract with the operator. Solution B's static mapping only records the "default" APN (usually vzwinternet). However, if the SIM card is actually registered with vzwclass6, it will attempt to use the wrong APN once each time it boots up (approximately 75 seconds) before the user can manually change it. This solution lacks "success memory"—repeatedly restarting or re-inserting the same SIM card starts with the same incorrect APN each time, wasting a fixed 75 seconds; in scenarios with frequent insertions and removals, such as in-vehicle / engineering devices, this can accumulate to tens of minutes of invalid network registration per day.
[0031] Existing solution C uses cloud-based APN distribution. A typical implementation involves some private cellular routers (such as certain SD-WAN vendors) using an IoT platform with pre-configured APNs. The device first reads the IMSI and reports it to the cloud, which then queries the vendor's APN database and distributes the APN to the device before dialing. A specific example of solution C failing during initial activation in weak / no network conditions is as follows: The cloud-based distribution of APNs relies on an existing available network channel on the router. However, during initial activation, if cellular dialing has not yet succeeded and the device lacks an Ethernet backup link, the cloud channel cannot be established—creating a deadlock. Furthermore, some industries (power, rail transportation) require devices to operate completely offline, prohibiting interaction with third-party clouds before dialing is established.
[0032] Therefore, this invention proposes an automatic APN selection method for cellular routers, comprising three mechanisms: A "successful call memory" cache table with IMSI as the primary key (Mechanism 1) – After a successful router dial-up connection, the "APN row ID used for this successful dial-up" is written to a local persistent cache (sqlite3) with IMSI as the primary key. The next time the device boots up or the same SIM card is reinserted, the traversal is skipped, resulting in a hit within seconds. Solution B, "no successful call memory," causes repeated trial and error with each reboot.
[0033] The UNUSED / USING / USED tri-state machine, combined with a last-bit loopback mechanism (Mechanism 2), marks the APN candidate list in memory with three states: "unused / in use / used." Each APN is tried at most once within a single closed cycle to avoid duplication. When the last bit is reached, all USED flags are automatically cleared to form a closed loop, ensuring the solution remains usable even with long-term changes in the network environment. This addresses the issues of "exhaustive search fails" and "list updates require firmware upgrades" in Solution A.
[0034] Candidate pool selection using MCC + dual MNC (2 / 3-digit compatible) query + PDP protocol filtering (Mechanism 3) – When querying sqlite3, both 2-digit and 3-digit MNCs are used for dual queries to match all legitimate operator records; and APNs with mismatched protocol families are filtered out according to the device's configured PDP protocol (IPv4 / IPv6 / dual-stack), avoiding the issuance of IPv6-only APNs on links that only support IPv4. This addresses the secondary failures caused by MNC length ambiguity and PDP type mismatch in Solutions A / B.
[0035] The three mechanisms mentioned above are an inseparable whole. Mechanism 1 alone cannot handle the "card replacement" scenario (IMSI cache does not expire simultaneously, so it still needs to be traversed); Mechanism 2 alone cannot avoid "repeated trial and error starting from scratch"; Mechanism 3 alone cannot solve the fundamental problem of "too many trial and error attempts". Only by combining the three can optimal results be achieved in seconds or minutes in the three scenarios of cross-border transactions, card replacement, and batch first activation.
[0036] See Figure 1 This figure is a schematic flowchart of an automatic APN selection method for a cellular router provided by an embodiment of the present invention. The automatic APN selection method for a cellular router provided by this embodiment of the present invention can be implemented, for example, through the following steps S101-105.
[0037] Combination Figure 2 To explain, Figure 2 This is a timing diagram of an automatic APN selection method for a cellular router provided in an embodiment of the present invention. Figure 2 As shown, this process involves five interacting entities: the user / integrator, the router main controller, the auto_apn module, the cellular module, and the sqlite3 imsi_cache. The specific timing steps are as follows: When a user / integrator triggers a cross-domain routing access to a new country's SIM card, the router's main controller performs an IMSI query operation and obtains the IMSI number 234150123456789 (United States).
[0038] The router master controller calls query_by_imsi(234150...) to send a query request to the auto_apn module.
[0039] The auto_apn module executes the query in sqlite3 imsi_cache: SELECT FROM apn WHERE mcc='234'AND mnc IN ('15', '150'), which hits three APN records: [APN_esauto, APN_eveop, APN_mobileweb].
[0040] The auto_apn module queries cellular modules: SELECT id FROM imsi_cache WHERE imsi=234150..., returning apn_list_count=3, cache_id=0 (indicating no cache hit).
[0041] The auto_apn module enters the tri-state machine test phase (find_next_apn_flag=true), calls get_unused_apn_info(IPv4) to obtain the next unused APN, returns APN_esauto, and sets the status to USING.
[0042] The router master controller sends an AT command to the cellular module: AT+CGDCONT="esauto".
[0043] After waiting 75 seconds for the dialing timeout (timeout 75s), call set_find_next_apn_flag(true) to set the status advancement flag.
[0044] Call get_unused_apn_info(IPv4) again, mark the APN_esauto of the previous USING state as USED, return the next APN_eveop and set it to USING.
[0045] The router master controller issues the AT command: AT+CGDCONT="eveop".
[0046] Upon successful dialing, a pop-up event is triggered, which calls imsi_cache_set(IMSI, apn_list) to write a success record to the cellular module.
[0047] The cellular module executes INSERT OR REPLACE imsi_cache(234150...), id_of_eveop, writing the row identifier of the currently successful APN to the sqlite3 imsi_cache table.
[0048] A week later, the user restarted the router, and the router's main controller queried the IMSI again (it was still the same card, 234150123456789), calling query_by_imsi(...).
[0049] The auto_apn module queries the cache. The cache_id in apn_list records the last successful eveop (i.e., a cache hit). Calling get_unused_apn_info(IPv4) directly hits the APN_eveop, and its status is "awaiting use".
[0050] The router master controller sends the AT command: AT+CGDCONT="eveop", and the dial-up connection is successful.
[0051] Boundary scenario: When the cached APN becomes invalid due to operator policy changes, the router master controller uses the cached eveop to issue AT commands, and after another 75-second timeout, calls set_find_next_apn_flag(true).
[0052] get_unused_apn_info() enters the cache branch (because the cached APN has expired), skips the failed APN, and returns to the next mobileweb.
[0053] The router master controller sends the AT command: AT+CGDCONT="mobileweb", and the dial-up connection is successful.
[0054] Calling `imsi_cache_set` will automatically update the cache to the new successful APN (mobileweb), completing cache self-healing.
[0055] S101: Read the IMSI of the SIM card, and query the local APN database based on the mobile country code in the IMSI and the two-digit mobile network code and three-digit mobile network code to construct a candidate APN list.
[0056] In this embodiment of the invention, a three-digit mobile country code, a two-digit mobile network code candidate, and a three-digit mobile network code candidate are extracted from the IMSI; a query condition is executed in the local APN database, the query condition including that the mobile country code is equal to the three-digit mobile country code and the mobile network code is equal to or equal to the two-digit mobile network code candidate.
[0057] Specifically, Figure 3 This is a flowchart illustrating a method for constructing a candidate APN pool according to an embodiment of the present invention. After starting, the IMSI of the SIM card is read. The validity of the IMSI format is determined. If the IMSI format is invalid (e.g., not purely numeric or less than 14-15 digits), it is rejected and an error is reported, and the process terminates. If the IMSI format is valid, execution continues. The Mobile Country Code (MCC), the two-digit Mobile Network Code (MNC2), and the three-digit Mobile Network Code (MNC3) are extracted from the valid IMSI. A double-binding SQL query is executed in the local APN database, querying based on the condition that the Mobile Country Code equals the MCC and the Mobile Network Code equals or equals MNC2 or MNC3. The query results are loaded into the candidate pool, and the number of APN entries in the candidate pool does not exceed 64. The imsi_cache table (local cache table) is queried to determine if a cached record with the IMSI as the primary key exists. If a cache hit occurs, the corresponding cache_id is recorded in the candidate pool list (apn_list). If a cache miss occurs, the cache_id in the candidate pool list is set to 0. The completed candidate pool (apn_list) is returned, and the process ends.
[0058] The triggering time is after the router receives the module's SIM registration ready event (CPIN:READY), and then calls the IMSI to read and trigger the APN automatic selection process. The execution logic is as follows: The input is an IMSI string (14-15 digits); the output is a list of candidate APNs, apn_list (containing N cell_apn_info_ts).
[0059] First, verify that the IMSI format is valid (14-15 digits, pure numbers). If it fails, the process will terminate. Next, we perform the truncating process, as shown in the example below: mcc = IMSI[0..2] (3-bit MCC) mnc_2 = IMSI[3..4] (2 MNC candidates) mnc_3 = IMSI[3..5] (3 MNC candidates). Then query the sqlite3 APN database, as shown in the example below: SELECT id,mcc,mnc,apn,user,password,auth_type,pdp,pdp_type FROM apn WHERE mcc=? AND (mnc=? OR mnc=?). This binds both mnc_2 and mnc_3 simultaneously. Then load all N (≤64) matching rows into apn_list[] by sorting them by id.
[0060] For each entry, the default is_used = AUTO_APN_IS_UNUSED Simultaneously query the imsi_cache table, as shown in the example below: SELECT id FROM imsi_cache WHERE imsi=? If a cache hit occurs, the ID is stored in aPN_list.imsi_cache_id; otherwise, imsi_cache_id = 0. Finally, it returns apn_list.
[0061] This step addresses the issue of dual MNC length compatibility, avoiding the discrepancy where the SIM card's MNC is actually 3 digits (such as Verizon 311480, AT&T 310410) but only 2 digits are matched in the database; it also ensures that the candidate pool contains only records of legitimate operators, avoiding the blindness of the existing solution A's "full list traversal".
[0062] In one implementation of this invention, the APN candidate pool is dynamically sorted according to "historical success rate". The success_count and failure_count columns are expanded in the APN table, and are accumulated each time a dialing is successful / failed. When constructing the candidate pool, it is sorted according to "descending success rate, with first-time unattended SIMs being prioritized", so that newly inserted unknown SIMs can also try the most frequently successful APNs in the same MCC+MNC range in history.
[0063] Applicable scenarios include "factory-level SaaS" scenarios where integrators deploy in bulk—the same firmware image runs on tens of thousands of devices, and the statistics for a single device may be incomplete. However, if the success_count / fail_count is aggregated to the cloud and then backfeeded to the device's local database through the operation and maintenance channel (after the VPN tunnel is established), the "most popular APN" can automatically rise to the top of the candidate pool. During the next cross-border deployment, the new SIM will have a higher probability of hitting the target on its first attempt. This mechanism retains all existing three-state machine and caching logic unchanged, only modifying the candidate pool construction order, ensuring backward compatibility.
[0064] Specifically, the process includes the following steps: The dialing event ends, and the dialing result is obtained.
[0065] The process is divided according to the dialing result: If the dialing is successful, execute `apn.success_count++` (increment the success count by 1) on the currently used APN. If the dialing fails, execute `apn.fail_count++` (increment the failure count by 1) on the currently used APN.
[0066] The success and failure counts mentioned above are accumulated and stored locally.
[0067] Determine if a network connection exists (i.e., whether the device is connected to the network).
[0068] If a network connection exists, the accumulated success and failure counts locally are periodically reported to the cloud. The cloud then aggregates the data, calculates the historical success rate of each APN, and generates a popular ranking (recommendation priority).
[0069] If there is no network connection, do not report for the time being, and wait for the network to be restored before reporting.
[0070] During the next firmware upgrade or configuration synchronization, the cloud will send the calculated weight table (containing the recommended ranking or weighted score of each APN) to the local device.
[0071] When constructing the next candidate APN pool, the local device sorts the candidate APNs according to the weight table (i.e., sorted by historical success rate), so that APNs with high success rates are tried first.
[0072] This implementation method, based on the candidate pool construction of the basic implementation method, introduces a closed loop of local accumulation of success / failure counts, cloud aggregation, and weight table distribution, so that the candidate APN ranking is dynamically optimized according to actual usage data, thereby improving the hit probability of the first attempt.
[0073] S102: Query the local cache using IMSI as the primary key. If the corresponding APN identifier exists in the local cache and the corresponding APN is in an unused state in the candidate APN list, then select the corresponding APN as the APN to be dialed.
[0074] In this embodiment of the invention, a cache table in the local database is queried. The cache table stores the row identifier of the APN used each time a dial-up call is successful, with IMSI as the primary key. If the query finds a match, the APN corresponding to the row identifier is obtained.
[0075] Specifically, Figure 4 This is a flowchart illustrating a cache hit priority method provided in an embodiment of the present invention, as shown below. Figure 4 As shown, when it is necessary to obtain the next APN to be dialed, perform the following steps: Check if the cache identifier `cache_id` is not equal to 0. If `cache_id` is not equal to 0, search the candidate APN list for an APN that matches `cache_id` and is in an unused state (UNUSED). If a matching APN is found, mark the APN as in use (USING), clear `cache_id` to zero, and return the APN, achieving a hit within seconds. If no matching APN is found, proceed to step S103 (three-state machine traversal) for further processing. If `cache_id` is equal to 0, directly proceed to step S103 (three-state machine traversal).
[0076] This is triggered after the candidate pool is built, whenever it is necessary to select the next APN to be dialed. The execution logic is as follows: The input is apn_list, which configures the PDP type cfg_pdp; the output is cell_apn_info_t (APN configuration to be sent to the module).
[0077] If apn_list.imsi_cache_id != 0: Traverse apn_list: If entry.id == imsi_cache_id and entry.is_used != AUTO_APN_IS_USED: Clear imsi_cache_id (to prevent repeated cache hits in the future). entry.is_used = AUTO_APN_IS_USING find_next_apn_flag = false (disable iteration) Return to entry ← Second-level hit branch If step S101 fails (the APN in the cache has already been tried once in this cycle without success, or the cache has not been initialized), proceed to step S103 for iteration. This step addresses issues such as SIM card restart / reinsertion, where the embodiment of this invention directly hits the last successful APN, saving all traversal time; and SIM card with a cached APN that has become invalid due to operator policy changes, where the embodiment of this invention automatically skips the cache and proceeds with normal traversal without manual intervention.
[0078] S103: If the local cache misses or the corresponding APN is already in use, the candidate APN list is traversed based on the three-state machine. Each APN maintains an unused state, a used state, and a used state in memory. The APN in the unused state is selected as the APN to be dialed.
[0079] In this embodiment of the invention, before traversing the candidate APN list based on the tri-state machine, the candidate APN list is filtered according to the PDP protocol type configured in the cellular router, and APNs whose PDP protocol type does not match the configured PDP protocol type are skipped.
[0080] Specifically, Figure 5 This is a flowchart illustrating a three-state machine last-position loop traversal method provided in an embodiment of the present invention, as shown below. Figure 5 As shown, each candidate APN maintains three states in memory, and the transition relationships between the states are as follows: Initial state (UNUSED): After the candidate APN pool is built, all APNs are initialized to the unused state (UNUSED), indicating that the APN has not been tried in this period.
[0081] Entering the USING state: When a cache hit occurs or a certain APN is selected during the three-state machine traversal, the state of the APN changes from the unused state to the USING state, indicating that the APN is being used for dialing attempts.
[0082] Entering Used State (USED): When dialing fails and the status advance flag (find_next) is set, the APN's status will be changed from the in-use state to the used state (USED) during the next scan, indicating that the APN has been tried and failed in this cycle.
[0083] Return to Unused State (Loop Reset): When the candidate pool is traversed to the end and all APNs are in the used state, the last loop or external reset operation is triggered to clear the state of all APNs to the unused state, making the candidate pool available again in the new dialing cycle.
[0084] Special transition (successful dialing): When dialing is successful, the system writes the APN in the current use state (USING) to the IMSI cache (writes to imsi_cache), but the state of the APN remains unchanged (still USING) so that the cache can be directly hit when restarting or reconnecting.
[0085] The aforementioned three-state machine works in conjunction with the last-position loopback mechanism to ensure that each APN is tried at most once within each closed cycle, avoiding repeated trial and error, and automatically resets the state after the cycle ends, thus achieving adaptive closed loop.
[0086] The trigger condition is a cache miss, or the cache has already failed to be accessed once in the current cycle. The execution logic is as follows: The input is aPN_list, cfg_pdp, and find_next_apn_flag (global atom bits); the output is the next APN to be issued.
[0087] for i = 0 to apn_list.count - 1: entry = apn_list[i] / PDP type filtering / if (cfg_pdp == IPV4 and entry.pdp_type == IPV6) or (cfg_pdp == IPV6 and entry.pdp_type == IPV4): continue if find_next_apn_flag == true: / The last dial-up call failed; I need to find the next one. / if entry.is_used == USING: entry.is_used = USED ← Marks the last used entry as USED if i == count - 1: auto_apn_clear_used_flag() ← Last-bit loop: Clears all used flags to zero. if entry.is_used == UNUSED: entry.is_used = USING find_next_apn_flag = false ← Disable bit traversal return entry else: / The current USING is still in effect. / if entry.is_used == USING: return entry ← Returns to the currently used APN This step addresses the following issues: each APN is tried at most once within a single closed cycle (from the first trial to the completion of all trials), avoiding the problem of "sequential traversal but possible duplication" in the existing solution A; the pool is automatically cleared when the last digit is not successfully traversed, making the candidate pool immediately available again, corresponding to the scenario of "an old APN becoming valid again after the operator updates the policy"; find_next_apn_flag is protected by the global atomic operation sync_lock_test_and_set, preventing race conditions in multi-threaded environments; PDP protocol family filtering is independent of the status bit, avoiding the waste of 75 seconds for network registration when trying to configure an IPv4 link with an IPv6-only APN.
[0088] S104: Send the APN to be dialed to the cellular module for dialing; when dialing is successful, write the identifier of the currently used APN to the local cache with IMSI as the primary key, and keep the status of the currently used APN as in use; when dialing fails, trigger the status advancement flag, update the status of the currently used APN to used, and advance to the next unused APN in the next selection.
[0089] In this embodiment of the invention, the INSERT OR REPLACE statement is used to write the row identifier of the currently used APN to the cache table, so that only the latest record of the same IMSI is retained in the cache table. A global atomic flag is set to indicate that the next selection needs to proceed to the next APN; when the global atomic flag is set, the currently used APN is marked as used in the next traversal, and the search for the next unused APN continues.
[0090] Specifically, Figure 6 A timing diagram of a dialing failure status progression and dialing success cache persistence method provided in an embodiment of the present invention is shown below. Figure 6 As shown in the diagram, the interaction between the dialer controller, cellular module, auto_apn module, and sqlite3 imsi_cache database involves two paths: Successful dialing path: The auto_apn module calls get_unused_apn_info() to obtain the APN to be dialed, returns APN_X, and marks the status as USING.
[0091] The dial controller sends APN_X to the cellular module using the AT command AT+CGDCONT=APN_X.
[0092] The cellular module dialed successfully and returned PDP UP (PDP context activation successful).
[0093] The dialer controller notifies the auto_apn module that the dialing was successful, and the auto_apn module calls imsi_cache_set(IMSI, apn_list).
[0094] The auto_apn module executes INSERT OR REPLACE imsi_cache(IMSI, X.id) on the sqlite3 imsi_cache database, writing the current IMSI and the row identifier of the successful APN into the cache.
[0095] Operation complete, OK returned.
[0096] Path to dialing failure: The auto_apn module calls get_unused_apn_info() to obtain the APN to be dialed, returns APN_Y, and marks the status as USING.
[0097] The dial controller sends APN_Y to the cellular module using the AT command AT+CGDCONT=APN_Y.
[0098] Cellular module dialing failed, returning a timeout (75s timeout) or +CME ERROR.
[0099] The dialer controller calls set_find_next_apn_flag(true) to set the status advancement flag.
[0100] The dialer controller notifies the auto_apn module (notify_db) that the APN dialing failed.
[0101] The auto_apn module will uniformly advance the current APN_Y status from USING to USED during the next scan and continue to try the next APN.
[0102] The two paths mentioned above correspond to the cache persistence after a successful dial-up call and the status progression after a failed dial-up call, respectively, together forming a complete closed-loop control logic.
[0103] The trigger condition for this step is that the module reports the dialing result (success / +CME ERROR / timeout 75s). The execution logic is as follows: Successful dialing branch (cellular.c:826-830): 1. Do not change the entry status (keep it USING) 2. auto_apn_imsi_cache_set(imsi, apn_list) → INSERT OR REPLACE the current USING entry.id with IMSI as the primary key into imsi_cache(imsi,id) 3. Completed. This process will not be called again until the card is replaced or the process fails.
[0104] Dial-up failure branch (cellular.c:818-820): 1. Do not update is_used immediately (leave it in USING and update it to USED during the next scan). 2. `auto_apn_set_find_next_apn_flag(true)` → Triggers the "Find Next" branch in step three. 3. Wait for an external re-call of step S101 or step S103 (triggered by the failure reconnection timer). This step addresses issues such as persisting "successful memories" to disk sqlite3, ensuring they remain valid even after power outages / restarts; not immediately marking failures as "USED" but relying on the next scan, making the process interruptible (e.g., no special cleanup is needed when the user manually changes the APN); and ensuring that INSERT OR REPLACE always retains only the latest record for the IMSI, with a controllable cache table size (linearly related only to the number of previously used SIMs).
[0105] In one implementation of this invention, the cache table is upgraded to a dual primary key (IMSI, module model). The primary key of the imsi_cache table is expanded from a single field imsi to a composite key (imsi, modem_revision), allowing the same SIM card to retain successful memories for each module after being replaced (e.g., from EC25 to EG95). Applicable scenarios include hot-swapping of backup modules in engineering vehicles / mobile cabinets, or rotating the same SIM card between primary and backup devices. Some modules (especially North American modules supporting Verizon) exhibit different parsing behaviors for the same APN string (refer to Verizon Slot 3 APN cleanup in commit 7718d2e68 of this repository). Relying solely on the IMSI cache may result in incorrect hits in cross-module scenarios, leading to dialing failures.
[0106] Specifically, the process includes two phases: writing and querying.
[0107] Write Phase (Dial Success Event): When a dial success event is triggered, the IMSI of the current SIM card and the model identifier (modem_revision) of the currently used cellular module are read. Using the IMSI and module model as a combined primary key, an INSERT OR REPLACE operation is performed to write the identifier of the currently successful APN to the cache table.
[0108] Query Phase: When querying the cache, the query is first performed using the IMSI and module model as a combined primary key. If the combined primary key is matched, the corresponding APN identifier is used directly, and the result is returned. If the combined primary key is not matched, a further query is performed to see if a record exists that uses only the IMSI as the primary key. If only the IMSI is matched, the APN identifier is used instead, and the record is marked as pending verification (indicating that the record comes from another module and may require further confirmation). If only the IMSI is not matched, the three-state machine traversal process is initiated.
[0109] This implementation allows the same SIM card to retain its last successful APN record for different module models, avoiding cache misses caused by module differences.
[0110] In one implementation of this invention, "+QICSGP slot number" is used as an optional field of cell_apn_info_t, allowing modules supporting multiple PDP slots (such as the entire Quectel series supporting +QICSGP=1 / =2 / =3) to store data in slots according to SIM type. This avoids failures caused by residual parameters when Verizon cards and non-Verizon cards share the same slot (corresponding to commit 7718d2e68 in this repository). Applicable scenarios include when a router is equipped with modules supporting multiple PDP slots and SIM hot-switching (dual SIM switching) is required. Combined with the tri-state mechanism of this invention, each SIM can independently maintain its APN state without interference.
[0111] Specifically, the core components of the automatic selection general method and their interrelationships include the following: I. Identity Primary Key Layer It supports multiple identity key types, including the complete IMSI string, IMSI + SIM slot number, IMSI + module model, ICCID, PIN / PUK auto-attempt, plan speed limit level, SIM type (normal / eSIM / Verizon), etc., to uniquely identify the SIM card or contract information.
[0112] II. Candidate Pool Construction Layer A candidate APN pool is constructed based on conditions such as operator number segment table PLMN, MCC+IMSI segment precise matching, MCC+dual MNC compatibility query, network standard (4G / 5G NSA / SA), PDP protocol family (IPv4 / v6 / dual stack), and roaming partner table.
[0113] It also supports automatic adaptation of cellular access parameters such as automatic matching of operator authentication certificates and automatic selection of authentication types.
[0114] III. Successful Memory Layer Successful APNs are recorded using persistent storage (sqlite / key-value library), and are valid across restarts and power outages.
[0115] Using the INSERT OR REPLACE operation ensures that only the latest record is retained for the same primary key.
[0116] Extended support for memory isolation of multiple modules without interference.
[0117] IV. State Machine Layer Define three states: UNUSED (unused), USING (used), and USED (used), and protect them with atomic operations (such as __sync_lock_test_and_set).
[0118] Achieve closed-cycle convergence (at most one attempt per APN per cycle).
[0119] It supports last-digit loopback, meaning that after traversing to the end, the state is automatically cleared and a new cycle begins.
[0120] V. Extended Applications Candidate pool filtering: APNs can be further filtered based on module PDP slot number, package speed limit level, SIM type, etc.
[0121] Adaptive capability: Automatically adjusts the selection strategy based on network type and PDP protocol family.
[0122] Multiple modules do not interfere with each other: different modules can independently maintain their own success memories and state machines.
[0123] This extended framework further generalizes the three core mechanisms (dual MNC compatible query, IMSI-level cache memory, and tri-state machine last bit loopback) in the basic implementation, and can flexibly adapt to multiple identity primary keys, multiple access parameters, and multiple persistence methods. It also supports advanced features such as module PDP slot coupling and historical success rate sorting.
[0124] S105: When the end of the candidate APN list is reached and all APNs in the candidate APN list are in a used state, reset the state of all APNs to an unused state, forming a loop.
[0125] In this embodiment of the invention, a clearing function is called to traverse the candidate APN list and clear the used status flag of all APNs to an unused status, so that the candidate APN list becomes available again in the new round of dialing attempts.
[0126] Compared with the prior art, the technical solution of the present invention has the following improvements and beneficial effects: Improvement 1: Introduce a "success memory" cache table with IMSI as the primary key.
[0127] Existing solution A has no memory and iterates from the beginning of the list each time the device boots up. Existing solution B uses a one-way static table "MCC+MNC→Default APN", which cannot record "which APN was successful last time for the same SIM". When the same SIM is repeatedly inserted or removed or restarted, it needs to retry from the incorrect APN each time (75 seconds), which accumulates to a considerable amount of time in engineering / vehicle scenarios. This invention maintains the imsi_cache(imsi TEXT PRIMARY KEY, id INTEGER) table in sqlite3. Each time a dial-up call is successful, INSERT OR REPLACE writes the IMSI→APN row id mapping. The next time the same IMSI re-enters the network, it directly hits this row and prioritizes its delivery to the module, skipping the traversal.
[0128] The essential differences include: Memory granularity: Existing solutions are "carrier-grade" (MCC+MNC), while the technical solution of this invention is "single SIM-level" (complete IMSI), accurate to the card level.
[0129] Persistence method: Existing solutions rely on built-in firmware, which can only be updated with upgrades; the technical solution of this invention adaptively accumulates as it is used, requiring zero maintenance.
[0130] Table size: INSERT OR REPLACE guarantees that each IMSI stores only one row, table size O (number of SIMs used), which is manageable for embedded devices.
[0131] Improvement point 2: The UNUSED / USING / USED three-state machine is coordinated with the last bit loop.
[0132] The existing scheme A uses sequential traversal without state records. After a dialing failure, an external retry mechanism is called repeatedly, which may repeatedly try on the same APN; it may also skip an untried APN due to a module malfunction. There is no automatic loopback after the last bit is reached; a restart is required to recover.
[0133] In this invention, each candidate APN is maintained in memory in three states: UNUSED (untried), USING (currently in use), and USED (tried and failed in this cycle). The global atomic flag `find_next_apn_flag` controls whether to proceed to the next one. The three states and this flag work together to ensure that each APN is tried at most once within the same cycle; when the last APN is reached and all APNs are USED, the flag is automatically cleared to UNUSED, forming a closed-loop restart; thread safety is guaranteed by the built-in atomic operations `__sync_lock_test_and_set` and `__sync_fetch_and_add`.
[0134] The essential differences include: Existing solutions employ a "stateless sequential scan," while the present invention uses a "stateful single consumption" approach, which can be proven to converge within a closed cycle. Existing solutions require external intervention after exhaustive search failures, while the present invention automatically loops back without requiring a restart.
[0135] Improvement point 3: Construction of a candidate pool with dual filtering of MCC + dual MNC (2 / 3 bit compatible) + PDP protocol family.
[0136] Existing solution B typically uses only a fixed 5-digit (or 6-digit) MCC+MNC for database lookup. The MNC length is determined by the carrier (mostly 3 digits in North America and 2 digits in Europe). When devices roam across regions, misjudgment of the MNC length can easily lead to unfindable results. Furthermore, failing to filter according to the PDP protocol family and issuing an IPv6-only APN to an IPv4 link wastes 75 seconds of network registration time. This invention binds both a 2-digit and a 3-digit MNC during the sqlite3 query phase: SELECT ... FROM apn WHERE mcc=? AND (mnc=? OR mnc=?); During the traversal of the three-state machine, filtering is performed according to the configured cfg_pdp: IPv4 is configured to skip entries with pdp_type==IPv6, IPv6 is configured to skip entries with pdp_type==IPv4, and dual-stack is not filtered.
[0137] The essential differences include: The existing solution is "single query MNC", while the technical solution of this invention is "double binding fault-tolerant query"; the existing solution does not filter PDP, while the technical solution of this invention filters during the consumption stage of the three-state machine, providing two independent layers of protection.
[0138] Improvement point four (combination effect): the synergy of the three mechanisms and the indispensability of any one of them.
[0139] Even if a certain existing solution uses a "subset" of a similar mechanism, such as ModemManager's mbpi.db containing some MNC double queries, it lacks the cooperation of "success memory" and "state machine" - once the dialing error occurs, it still needs to be reselected from the operator table.
[0140] The three mechanisms of the technical solution of this invention are inseparable. Mechanism 1 (caching) alone: there is no caching when changing cards or making the first call, which degenerates into exhaustive search without memory; Mechanism 2 alone (three-state device): when restarting with the same SIM, it is still necessary to traverse from the beginning, and caching the SIM does not improve the efficiency of dialing; Mechanism 3 alone (MNC / PDP filtering) alone: it is only an optimization of the candidate pool and has no impact on the traversal efficiency.
[0141] The essential differences include: Existing solutions only optimize in a single dimension (memory, state, or filtering). The technical solution of this invention is a three-dimensional collaborative closed loop: first, mechanism three constructs an unambiguous candidate pool; then, mechanism one attempts to successfully hit a memory; if it misses, mechanism two consumes the memory in a single step until success or a loop is completed at the last position. There are corresponding optimal paths for the three scenarios: initial activation, card replacement, and restart.
[0142] As shown in Table 1, Table 1 is a multi-dimensional comparison table provided by the embodiments of the present invention, which quantitatively compares the technical solution of the present invention with three existing solutions (Solution A: hard-coded traversal, Solution B: static IMSI mapping, Solution C: cloud-based delivery) in ten core dimensions. The comparison dimensions include: typical time for first-time cross-border internet access, time for restarting / reinserting the same SIM card, network availability, adaptation method when the new operator's APN policy changes, whether the closed cycle converges (at most one trial per APN), compatibility of candidate pool MNC length, waste due to PDP protocol family mismatch, offline compliance, cache table size, and speedup multiple relative to the baseline. As shown in Table 1, in the scenario of first-time cross-border internet access, if the 8th candidate is matched, the total time is approximately 1.5 minutes (including one failure in the first round), which is far less than the 10 minutes of Solution A. During SIM restart, this invention only requires ≤2 seconds, while Solution B still requires 75 seconds for one failure. In the absence of network, this invention can work entirely locally, while Solution C is unusable due to deadlock. After changes in operator APN policies, this invention can adapt through automatic trial and error and writing to the cache, without requiring firmware upgrades. This invention uses a tri-state machine to ensure at most one attempt within each APN closed cycle, while Solution A relies on an external retry mechanism. Dual MNC compatibility query and PDP protocol family filtering respectively solve the problems of MNC length ambiguity and protocol mismatch waste. Simultaneously, this invention meets offline compliance requirements, and the cache table size is extremely small (linearly related to the number of previously used SIMs). In summary, this invention achieves a speedup of over 300 times compared to the baseline Solution A in the same SIM restart scenario.
[0143] Table 1 Multidimensional Comparison Table
[0144] Based on the methods provided in the above embodiments, this invention also provides an automatic APN selection device for cellular routers. The automatic APN selection device for cellular routers is described below with reference to the accompanying drawings.
[0145] See Figure 7 The figure is a schematic diagram of the structure of an automatic APN selection device for a cellular router provided in an embodiment of the present invention.
[0146] The cellular router automatic APN selection device 700 provided in this embodiment of the invention includes: a candidate pool construction module 701, a cache query module 702, a three-state machine traversal module 703, a dialing execution module 704, a success cache module 705, a failure push module 706, and a last-digit loopback module 707.
[0147] The candidate pool construction module 701 is used to read the IMSI of the SIM card, query the local APN database based on the mobile country code in the IMSI and the two-digit mobile network code and the three-digit mobile network code, and construct a candidate APN list. The cache query module 702 is used to query the local cache with IMSI as the primary key. If the corresponding APN identifier exists in the local cache and the corresponding APN is in an unused state in the candidate APN list, the corresponding APN is selected as the APN to be dialed. The three-state machine traversal module 703 is used to traverse the candidate APN list based on the three-state machine when the local cache misses or the corresponding APN is already in use. Each APN maintains an unused state, a used state, and a used state in memory. The APN in the unused state is selected as the APN to be dialed in turn. The dialing execution module 704 is used to send the APN to be dialed to the cellular module for dialing. The success caching module 705 is used to write the identifier of the currently used APN to the local cache with IMSI as the primary key when the dialing is successful, and to keep the status of the currently used APN as "in use". The failure push module 706 is used to trigger the status push flag when dialing fails, update the status of the currently used APN to "used", and push to the next unused APN on the next selection. The last loop module 707 is used to reset the state of all APNs to unused state when the end of the candidate APN list is reached and all APNs in the candidate APN list are in the used state, thus forming a loop.
[0148] In one possible implementation, the candidate pool construction module 701 is specifically used for: Extract a three-digit mobile country code, a two-digit mobile network code candidate, and a three-digit mobile network code candidate from the IMSI; Execute a query in the local APN database. The query conditions include a mobile country code equal to a three-digit mobile country code and a mobile network code equal to a two-digit mobile network code candidate or equal to a three-digit mobile network code candidate.
[0149] In one possible implementation, the three-state machine traversal module 703 is specifically used for: The candidate APN list is filtered based on the PDP protocol type configured on the cellular router, and APNs whose PDP protocol type does not match the configured PDP protocol type are skipped.
[0150] In one possible implementation, the cache query module 702 is specifically used for: Query the cache table in the local database. The cache table stores the row identifier of the APN used each time a dial-up call is successful, with IMSI as the primary key. If the query finds a match, the APN corresponding to the row identifier is retrieved.
[0151] In one possible implementation, the success cache module 705 is specifically used for: The INSERT OR REPLACE statement is used to write the row identifier of the currently used APN to the cache table, so that only the latest record of the same IMSI is retained in the cache table.
[0152] In one possible implementation, the failure propagation module 706 is specifically used for: Set a global atomic flag, which is used to indicate that the next selection should advance to the next APN; When the global atom flag is set, the APN currently in use is marked as used during the next traversal, and the search continues for the next unused APN.
[0153] In one possible implementation, the last-digit loopback module 707 is specifically used for: The function to clear the list of candidate APNs is called to clear the used status flag of all APNs to the unused status, so that the list of candidate APNs becomes available again in the next round of dialing attempts.
[0154] Since the cellular router automatic APN selection device 400 is a device corresponding to the cellular router automatic APN selection method provided in the above method embodiments, the specific implementation of each unit of the cellular router automatic APN selection device 400 is based on the same concept as the above method embodiments. Therefore, for the specific implementation of each unit of the cellular router automatic APN selection device 400, please refer to the description of the cellular router automatic APN selection method in the above method embodiments, and it will not be repeated here.
[0155] This invention also provides an automatic APN selection device for cellular routers, the device comprising: a processor and a memory; The memory is used to store instructions; The processor is used to execute the instructions in the memory to perform the automatic APN selection method for cellular routers mentioned in the above embodiments.
[0156] It should be noted that the hardware structure of the cellular router automatic APN selection device provided in the embodiments of the present invention can be as follows: Figure 8 The structure shown, Figure 8 This is a schematic diagram of the structure of a device provided in an embodiment of the present invention.
[0157] Please see Figure 8 As shown, device 800 includes: processor 810, communication interface 820, and memory 830. The number of processors 810 in device 800 can be one or more. Figure 8 Taking a processor as an example, in this embodiment of the invention, the processor 810, communication interface 820, and memory 830 can be connected via a bus device or other means. Figure 8 For example, China and Israel are connected via bus device 840.
[0158] Processor 810 may be a central processing unit (CPU), a network processor (NP), or a combination of a CPU and an NP. Processor 810 may further include hardware chips. These hardware chips may be application-specific integrated circuits (ASICs), programmable logic devices (PLDs), or combinations thereof. The PLD may be a complex programmable logic device (CPLD), a field-programmable gate array (FPGA), generic array logic (GAL), or any combination thereof.
[0159] The memory 830 may include volatile memory, such as random-access memory (RAM); the memory 830 may also include non-volatile memory, such as flash memory, hard disk drive (HDD) or solid-state drive (SSD); the memory 830 may also include a combination of the above types of memory.
[0160] Optionally, the memory 830 stores operating devices and programs, executable modules or data structures, or subsets thereof, or extended sets thereof. The programs may include various operating instructions for implementing various operations. The operating devices may include various device programs for implementing various basic services and processing hardware-based tasks. The processor 810 can read the programs in the memory 830 to implement the automatic APN selection method for cellular routers provided in this embodiment of the invention.
[0161] The bus device 840 can be a Peripheral Component Interconnect (PCI) bus or an Extended Industry Standard Architecture (EISA) bus, etc. The bus device 840 can be divided into address bus, data bus, control bus, etc. For ease of representation, Figure 8 The bus is represented by a single thick line, but this does not mean that there is only one bus or one type of bus.
[0162] This invention also provides a computer-readable storage medium including instructions that, when executed on a computer, cause the computer to perform the cellular router automatic APN selection method mentioned in the above embodiments.
[0163] This invention also provides a computer program product containing instructions that, when run on a computer, causes the computer to execute the cellular router automatic APN selection method mentioned in the above embodiments.
[0164] Although the invention has been specifically shown and described in conjunction with preferred embodiments, those skilled in the art should understand that various changes in form and detail may be made to the invention without departing from the spirit and scope of the invention as defined in the appended claims, all of which shall be within the scope of protection of the invention.
Claims
1. A method for automatic APN selection in a cellular router, characterized in that, include: Read the SIM card's IMSI, and based on the mobile country code in the IMSI and the two-digit mobile network code and three-digit mobile network code used simultaneously, query the local APN database to construct a candidate APN list; The local cache is queried using the IMSI as the primary key. If the local cache contains a corresponding APN identifier and the corresponding APN is in an unused state in the candidate APN list, then the corresponding APN is selected as the APN to be dialed. If the local cache misses or the corresponding APN is already in use, the candidate APN list is traversed based on the three-state machine, where each APN maintains an unused state, a used state, and a used state in memory, and the APN in the unused state is selected as the APN to be dialed in turn; The APN to be dialed is sent to the cellular module for dialing; When the dialing is successful, the identifier of the currently used APN is written to the local cache with the IMSI as the primary key, and the status of the currently used APN is kept as "in use". When dialing fails, a status advancement flag is triggered, updating the status of the currently used APN to "used", and advancing to the next unused APN during the next selection. When the process reaches the end of the candidate APN list and all APNs in the candidate APN list are in a used state, the state of all APNs is reset to an unused state, forming a loop.
2. The method according to claim 1, characterized in that, The query in the local APN database based on the mobile country code in the IMSI and simultaneously using a two-digit mobile network code and a three-digit mobile network code includes: Extract a three-digit mobile country code, a two-digit mobile network code candidate, and a three-digit mobile network code candidate from the IMSI; Execute a query in the local APN database, the query conditions including the Mobile Country Code being equal to the three-digit Mobile Country Code, and the Mobile Network Code being equal to or equal to the two-digit Mobile Network Code candidate.
3. The method according to claim 1, characterized in that, Before traversing the candidate APN list based on a three-state machine, the following is also included: The candidate APN list is filtered according to the PDP protocol type configured in the cellular router, and APNs whose PDP protocol type does not match the configured PDP protocol type are skipped.
4. The method according to claim 1, characterized in that, The querying of the local cache using the IMSI as the primary key includes: Query the cache table in the local database, which stores the row identifier of the APN used each time a dial-up call is successful, with IMSI as the primary key; If the query is successful, the APN corresponding to the row identifier is obtained.
5. The method according to claim 1, characterized in that, The step of writing the identifier of the currently used APN to the local cache using the IMSI as the primary key includes: Use the INSERT OR REPLACE statement to write the row identifier of the currently used APN to the cache table, so that only the latest record of the same IMSI is retained in the cache table.
6. The method according to claim 1, characterized in that, The trigger state advancement flag includes: A global atomic flag is set to indicate that the next selection needs to proceed to the next APN; When the global atom flag is set, the APN currently in use is marked as used during the next traversal, and the search continues for the next unused APN.
7. The method according to claim 1, characterized in that, The step of resetting the status of all APNs to an unused state includes: The zeroing function is called to traverse the candidate APN list and clear the used status flag of all APNs to the unused status, so that the candidate APN list becomes available again in the new round of dialing attempts.
8. An automatic APN selection device for a cellular router, characterized in that, include: The candidate pool construction module is used to read the IMSI of the SIM card, query the local APN database based on the mobile country code in the IMSI and the two-digit mobile network code and the three-digit mobile network code, and construct a candidate APN list. The cache query module is used to query the local cache using the IMSI as the primary key. If the local cache contains a corresponding APN identifier and the corresponding APN is in an unused state in the candidate APN list, then the corresponding APN is selected as the APN to be dialed. The three-state machine traversal module is used to traverse the candidate APN list based on the three-state machine when the local cache misses or the corresponding APN is used. Each APN maintains an unused state, a used state, and a used state in memory. The APN in the unused state is selected as the APN to be dialed in turn. The dialing execution module is used to send the APN to be dialed to the cellular module for dialing; A success caching module is used to write the identifier of the currently used APN to the local cache with the IMSI as the primary key when the dialing is successful, and to keep the status of the currently used APN as "in use". The failure push module is used to trigger the status push flag when dialing fails, update the status of the currently used APN to "used", and push to the next unused APN on the next selection. The last-position loop module is used to reset the state of all APNs to unused state when the end of the candidate APN list is reached and all APNs in the candidate APN list are in a used state, thus forming a loop.
9. An electronic device, characterized in that, The device includes: a processor and a memory; The memory is used to store instructions; The processor is configured to execute the instructions in the memory to perform the method according to any one of claims 1-7.
10. A computer-readable storage medium, characterized in that, Including instructions that, when run on a computer, cause the computer to perform the method described in any one of claims 1-7 above.