@@ -631,3 +631,69 @@ nsapi_error_t AT_CellularNetwork::set_packet_domain_event_reporting(bool on)
631631
632632 return _at.at_cmd_discard (" +CGEREP" , " =" , " %d" , on ? 1 : 0 );
633633}
634+
635+ nsapi_error_t AT_CellularNetwork::clear ()
636+ {
637+ tr_info (" AT_CellularNetwork::clear" );
638+
639+ _at.lock ();
640+ _at.cmd_start_stop (" +CGDCONT" , " ?" );
641+ _at.resp_start (" +CGDCONT:" );
642+
643+ struct context_s {
644+ int id;
645+ context_s *next;
646+ };
647+ CellularList<context_s> contexts;
648+ while (_at.info_resp ()) {
649+ int cid = _at.read_int ();
650+ // clear all but the default context
651+ if (cid <= 0 ) {
652+ continue ;
653+ } else if (cid == 1 ) {
654+ #ifndef MBED_CONF_NSAPI_DEFAULT_CELLULAR_APN
655+ continue ;
656+ #else
657+ char pdp_type_from_context[10 ];
658+ int pdp_type_len = _at.read_string (pdp_type_from_context, sizeof (pdp_type_from_context));
659+ if (pdp_type_len > 0 ) {
660+ char apn[MAX_ACCESSPOINT_NAME_LENGTH];
661+ int apn_len = _at.read_string (apn, sizeof (apn));
662+ if (apn_len >= 0 ) {
663+ if (strcmp (apn, MBED_CONF_NSAPI_DEFAULT_CELLULAR_APN) == 0 ) {
664+ continue ;
665+ }
666+ }
667+ }
668+ #endif
669+ }
670+ contexts.add_new ()->id = cid;
671+ }
672+ _at.resp_stop ();
673+
674+ if (contexts.get_head ()) {
675+ // try to detach from network before deleting contexts
676+ (void )detach ();
677+ context_s *context = contexts.get_head ();
678+ while (context) {
679+ if (_at.at_cmd_discard (" +CGDCONT" , " =" , " %d" , context->id ) != NSAPI_ERROR_OK) {
680+ tr_warn (" Clear context %d failed" , context->id );
681+ }
682+ context = context->next ;
683+ }
684+ #ifdef MBED_CONF_NSAPI_DEFAULT_CELLULAR_APN
685+ char pdp_type_str[sizeof (" IPV4V6" )];
686+ if (get_property (PROPERTY_IPV4V6_PDP_TYPE) ||
687+ (get_property (PROPERTY_IPV4_PDP_TYPE) && get_property (PROPERTY_IPV6_PDP_TYPE))) {
688+ strcpy (pdp_type_str, " IPV4V6" );
689+ } else if (get_property (PROPERTY_IPV6_PDP_TYPE)) {
690+ strcpy (pdp_type_str, " IPV6" );
691+ } else {
692+ strcpy (pdp_type_str, " IP" );
693+ }
694+ _at.at_cmd_discard (" +CGDCONT" , " =" , " %d%s%s" , 1 , pdp_type_str, MBED_CONF_NSAPI_DEFAULT_CELLULAR_APN);
695+ #endif
696+ }
697+
698+ return _at.unlock_return_error ();
699+ }
0 commit comments