void __ubmodem_recvfrom_socket(struct modem_socket_s *sock)
{
  struct ubmodem_s *modem = sock->modem;
  int err;
  size_t inlen;
  size_t max_stream_len;
  size_t recvlen;

  if (sock->is_closed)
    {
      /* Socket closed! */

      (void)__ubmodem_usrsock_send_response(modem, &sock->req, false, -EPIPE);
      __ubsocket_work_done(sock);
      return;
    }

  inlen = sock->recv.avail;

  if (inlen > sock->recv.max_buflen)
    inlen = sock->recv.max_buflen;

  if (sock->type == SOCK_DGRAM)
    {
      max_stream_len = __ubmodem_stream_max_readbuf_len(&cmd_ATpUSORF);
      max_stream_len -= INET_ADDRSTRLEN;
    }
  else
    {
      max_stream_len = __ubmodem_stream_max_readbuf_len(&cmd_ATpUSORD);
    }

  MODEM_DEBUGASSERT(modem, inlen > 0); /* sockets state machine should not allow
                                        * recv if input buffer has no space
                                        * left. */

  recvlen = max_stream_len;
  if (recvlen > MODEM_MAX_BINARY_SOCKET_READ_BYTES)
    recvlen = MODEM_MAX_BINARY_SOCKET_READ_BYTES;
  if (recvlen > inlen)
    recvlen = inlen;

  if (sock->type == SOCK_DGRAM)
    {
      /* Read data and peer address from modem. */

      err = __ubmodem_send_cmd(modem, &cmd_ATpUSORF, socket_recvfrom_handler,
                               sock, "=%d,%d", sock->modem_sd, recvlen);
      MODEM_DEBUGASSERT(modem, err == OK);
    }
  else
    {
      /* Read data from modem. */

      err = __ubmodem_send_cmd(modem, &cmd_ATpUSORD, socket_recvfrom_handler,
                               sock, "=%d,%d", sock->modem_sd, recvlen);
      MODEM_DEBUGASSERT(modem, err == OK);
    }
}
void __ubmodem_substate_start_setup_network(struct ubmodem_s *modem)
{
  struct modem_sub_setup_network_s *sub = &modem->sub.setup_network;
  int err;

  MODEM_DEBUGASSERT(modem, modem->level == UBMODEM_LEVEL_SIM_ENABLED);

  /*
   * Setup network sequence is:
   *
   * 1. Enable "+CREG" URC.
   * 2. Send "AT+CFUN=1".
   * 3. Send "AT+COPS=0".
   * 4. Wait until connected (Wait information from +CREG)
   *
   */

  MODEM_DEBUGASSERT(modem, modem->creg_urc_registered == false);
  MODEM_DEBUGASSERT(modem, modem->creg_timer_id == -1);

  /* Reset sub-state data and initiate sub-state machine work. */

  memset(sub, 0, sizeof(*sub));
  sub->network_state = NETWORK_SETUP_ENABLING_CREG;

  /* Setup sub-state clean-up function. */

  modem->substate_cleanup_fn = setup_network_cleanup;

  /* Enable +CREG. */

  err = __ubmodem_send_cmd(modem, &cmd_ATpCREG, ATpCREG_handler, sub,
                           "%s", "=1");
  MODEM_DEBUGASSERT(modem, err == OK);
}
static int network_start_register_handler(struct ubmodem_s *modem,
                                          const int timer_id,
                                          void * const arg)
{
  struct modem_sub_setup_network_s *sub = &modem->sub.setup_network;
  int err;

  MODEM_DEBUGASSERT(modem, modem->creg_timer_id == timer_id);

  if (timer_id != -1)
    {
      /* One-shot timer, not registered anymore. */

      modem->creg_timer_id = -1;

      ubmodem_pm_set_activity(modem, UBMODEM_PM_ACTIVITY_HIGH, false);
    }

  /* Keep retrying automatic network registration until timeout. */

  sub->network_state = NETWORK_SETUP_RETRYING_NETWORK_REGISTRATION;
  sub->received_creg_while_retrying = -1;

  err = __ubmodem_send_cmd(modem, &cmd_ATpCOPS,
                           retry_ATpCOPS_handler, sub, "%s", "=0");
  MODEM_DEBUGASSERT(modem, err == OK);
  return OK;
}
void __ubmodem_substate_start_disconnect_network(struct ubmodem_s *modem)
{
  struct modem_sub_setup_network_s *sub = &modem->sub.setup_network;
  int err;

  MODEM_DEBUGASSERT(modem, modem->level == UBMODEM_LEVEL_NETWORK ||
                           modem->level == UBMODEM_LEVEL_GPRS);

  /*
   * Disconnect network sequence is:
   *
   * 1. Send "AT+COPS=2".
   * 2. Send "AT+CFUN=0".
   *
   */

  __ubmodem_network_cleanup(modem);

  /* Reset sub-state data and initiate sub-state machine work. */

  memset(sub, 0, sizeof(*sub));
  sub->network_state = NETWORK_SETUP_DISCONNECTING;

  /* Disable network. */

  err = __ubmodem_send_cmd(modem, &cmd_ATpCOPS, set_ATpCOPS_off_handler, sub,
                           "%s", "=2");
  MODEM_DEBUGASSERT(modem, err == OK);
}
static void config_audio_out_ctrl_gpio(struct ubmodem_s *modem, int pin,
                                       bool set)
{
  int err;

  err = __ubmodem_send_cmd(modem, &cmd_ATpUGPIOC,
                           __ubmodem_cmdprompt_generic_config_handler,
                           (void *)&cmd_ATpUGPIOC, "=%d,0,%d", pin, set);
  MODEM_DEBUGASSERT(modem, err == OK);
}
static void config_enable_urc_common(struct ubmodem_s *modem,
                                     const struct at_cmd_def_s *cmd)
{
  int err;

  __ubmodem_voice_control_setup(modem);

  err = __ubmodem_send_cmd(modem, cmd,
                           __ubmodem_cmdprompt_generic_config_handler,
                           (void *)cmd, "=1");
  MODEM_DEBUGASSERT(modem, err == OK);
}
static int network_unregister_timer_handler(struct ubmodem_s *modem,
                                            const int timer_id,
                                            void * const arg)
{
  struct modem_sub_setup_network_s *sub = arg;
  int err;

  /* Send +CFUN=0 */

  err = __ubmodem_send_cmd(modem, &cmd_ATpCFUN, set_ATpCFUN_off_handler, sub,
                           "%s", "=0");
  MODEM_DEBUGASSERT(modem, err == OK);

  return OK;
}
static int network_unregister_timer_handler(struct ubmodem_s *modem,
                                            const int timer_id,
                                            void * const arg)
{
  struct modem_sub_setup_network_s *sub = &modem->sub.setup_network;
  int err;

  /* Send +CFUN=0 */

  ubmodem_pm_set_activity(modem, UBMODEM_PM_ACTIVITY_HIGH, false);
  err = __ubmodem_send_cmd(modem, &cmd_ATpCFUN, set_ATpCFUN_off_handler, sub,
                           "%s", "=0");
  MODEM_DEBUGASSERT(modem, err == OK);

  return OK;
}
static int start_task_voice_hangup(struct ubmodem_s *modem, void *priv)
{
  int err;

  if (modem->level < UBMODEM_LEVEL_NETWORK)
    {
      return ERROR;
    }

  /* Send hangup call command 'AT+CHUP' */

  err = __ubmodem_send_cmd(modem, &cmd_ATpCHUP, ATpCHUP_handler, modem, "");
  MODEM_DEBUGASSERT(modem, err == OK);

  return OK;
}
static int start_task_voice_answer(struct ubmodem_s *modem, void *priv)
{
  int err;

  if (modem->level < UBMODEM_LEVEL_NETWORK)
    {
      return ERROR;
    }

  /* Send answer call command 'ATA' */

  err = __ubmodem_send_cmd(modem, &cmd_ATA, ATA_handler, priv, "");
  MODEM_DEBUGASSERT(modem, err == OK);

  return OK;
}
static void ATpCREG_handler(struct ubmodem_s *modem,
                            const struct at_cmd_def_s *cmd,
                            const struct at_resp_info_s *info,
                            const uint8_t *resp_stream,
                            size_t stream_len, void *priv)
{
  struct modem_sub_setup_network_s *sub = &modem->sub.setup_network;
  int err;

  /*
   * Response handler for AT+CREG=1
   */

  MODEM_DEBUGASSERT(modem, cmd == &cmd_ATpCREG);

  if (resp_status_is_error_or_timeout(info->status))
    {
      __ubmodem_common_failed_command(modem, cmd, info, "=1");
      return;
    }

  if (info->status != RESP_STATUS_OK)
    {
      MODEM_DEBUGASSERT(modem, false); /* Should not get here. */
      return;
    }

  /* Register "+CREG" URC handler. */

  __ubparser_register_response_handler(&modem->parser, &urc_ATpCREG,
                                       registration_urc_pCREG_handler,
                                       sub, true);
  modem->creg_urc_registered = true;
  sub->network_state = NETWORK_SETUP_ENABLING_RF;

  /* Enable modem RF. */

  err = __ubmodem_send_cmd(modem, &cmd_ATpCFUN, ATpCFUN_handler, sub, "%s", "=1");
  MODEM_DEBUGASSERT(modem, err == OK);
}
static void ATpCFUN_handler(struct ubmodem_s *modem,
                            const struct at_cmd_def_s *cmd,
                            const struct at_resp_info_s *info,
                            const uint8_t *resp_stream,
                            size_t stream_len, void *priv)
{
  struct modem_sub_setup_network_s *sub = &modem->sub.setup_network;
  int err;

  /*
   * Response handler for AT+CFUN=1
   */

  MODEM_DEBUGASSERT(modem, cmd == &cmd_ATpCFUN);

  if (resp_status_is_error_or_timeout(info->status))
    {
      __ubmodem_common_failed_command(modem, cmd, info, "=1");
      return;
    }

  if (info->status != RESP_STATUS_OK)
    {
      MODEM_DEBUGASSERT(modem, false); /* Should not get here. */
      return;
    }

  /*
   * Modem RF enabled, now disable previous automatic network registration.
   * +CREG:0 will be received and +COPS=0 will be issued to start new automatic
   * network registration.
   */

  sub->network_state = NETWORK_SETUP_STARTING_NETWORK_REGISTRATION;
  (void)clock_gettime(CLOCK_MONOTONIC, &sub->net_reg_start_ts);

  err = __ubmodem_send_cmd(modem, &cmd_ATpCOPS, disable_ATpCOPS_handler, sub,
                           "%s", "=2");
  MODEM_DEBUGASSERT(modem, err == OK);
}
static void ATpCFUN_handler(struct ubmodem_s *modem,
                            const struct at_cmd_def_s *cmd,
                            const struct at_resp_info_s *info,
                            const uint8_t *resp_stream,
                            size_t stream_len, void *priv)
{
  struct modem_sub_setup_network_s *sub = priv;
  int err;

  /*
   * Response handler for AT+CFUN=1
   */

  MODEM_DEBUGASSERT(modem, cmd == &cmd_ATpCFUN);

  if (resp_status_is_error_or_timeout(info->status))
    {
      __ubmodem_common_failed_command(modem, cmd, info, "=1");
      return;
    }

  if (info->status != RESP_STATUS_OK)
    {
      MODEM_DEBUGASSERT(modem, false); /* Should not get here. */
      return;
    }

  /*
   *  Modem RF enabled, now start automatic network registration.
   */

  sub->network_state = NETWORK_SETUP_STARTING_NETWORK_REGISTRATION;

  err = __ubmodem_send_cmd(modem, &cmd_ATpCOPS, set_ATpCOPS_handler, sub,
                       "%s", "=0");
  MODEM_DEBUGASSERT(modem, err == OK);
}
static int network_retry_registration_timer_handler(struct ubmodem_s *modem,
                                                    const int timer_id,
                                                    void * const arg)
{
  struct modem_sub_setup_network_s *sub = &modem->sub.setup_network;
  int err;

  MODEM_DEBUGASSERT(modem, modem->creg_timer_id == timer_id);

  if (timer_id != -1)
    {
      /* One-shot timer, not registered anymore. */

      modem->creg_timer_id = -1;

      ubmodem_pm_set_activity(modem, UBMODEM_PM_ACTIVITY_HIGH, false);
    }

  DEBUGASSERT(
      sub->network_state == NETWORK_SETUP_RETRYING_NETWORK_REGISTRATION);

  if (sub->received_creg_while_retrying > 0)
    {
      ubdbg("Handling deferred +CREG: %d\n", sub->received_creg_while_retrying);

      network_registration_successed(modem, sub);
    }
  else
    {
      err = __ubmodem_send_cmd(modem, &cmd_ATpCOPS,
                               retry_ATpCOPS_handler, sub, "%s", "=0");
      MODEM_DEBUGASSERT(modem, err == OK);
    }

  return OK;
}
static void urc_pCREG_handler(struct ubmodem_s *modem,
                              const struct at_cmd_def_s *cmd,
                              const struct at_resp_info_s *info,
                              const uint8_t *resp_stream,
                              size_t stream_len, void *priv)
{
  int8_t val;
  int err;
  int ret;

  /*
   * Response handler for +CREG URC.
   */

  MODEM_DEBUGASSERT(modem, cmd == &urc_ATpCREG);

  if (info->status != RESP_STATUS_URC)
    {
      /* Should not happen. */

      MODEM_DEBUGASSERT(modem, false);
      return;
    }

  if (!__ubmodem_stream_get_int8(&resp_stream, &stream_len, &val))
    {
      /* Should not happen. */

      MODEM_DEBUGASSERT(modem, false);
      return;
    }

  dbg("Network registration URC, +CREG=%d.\n", val);

  if (val >= 0 && val < ARRAY_SIZE(creg_strings))
    {
      dbg("%s\n", creg_strings[val]);
    }
  else
    {
      dbg("Unknown +CREG status: %d\n", val);
    }

  if (modem->level < UBMODEM_LEVEL_NETWORK)
    {
      struct modem_sub_setup_network_s *sub = &modem->sub.setup_network;

      DEBUGASSERT(modem->state == MODEM_STATE_IN_SUBSTATE);

      if (sub->network_state < NETWORK_SETUP_WAITING_NETWORK_REGISTRATION)
        {
          /* Not ready yet, spurious +CREG URC? */

          ubdbg("Ignored spurious +CREG URC.\n");

          return;
        }

      switch (val)
      {
        case 1:
        case 5:
          /*
           * If 'val' is 1, registered: home network.
           * If 'val' is 5, registered: roamed.
           */

          if (sub->network_state == NETWORK_SETUP_RETRYING_NETWORK_REGISTRATION)
            {
              /* Cannot do state transition to UBMODEM_LEVEL_NETWORK right now
               * as still retrying AT+COPS=0. Defer handling to
               * retry_ATpCOPS_handler. */

              sub->received_creg_while_retrying = val;
            }
          else
            {
              /* Report successful cellular network connection. */

              sub->keep_creg_urc = true;
              __ubmodem_reached_level(modem, UBMODEM_LEVEL_NETWORK);
            }

          return;

        case 0:
          /*
           * MT not searching for connection.
           */

          if (sub->network_state == NETWORK_SETUP_WAITING_NETWORK_REGISTRATION)
            {
              /* Keep retrying automatic network registration until timeout. */

              sub->network_state = NETWORK_SETUP_RETRYING_NETWORK_REGISTRATION;
              sub->received_creg_while_retrying = -1;

              err = __ubmodem_send_cmd(modem, &cmd_ATpCOPS,
                                       retry_ATpCOPS_handler, sub, "%s", "=0");
              MODEM_DEBUGASSERT(modem, err == OK);
            }

          return;

        case 4:
          /*
           * If 'val' is 4, unknown registration error.
           */

          /* no break */

        case 3:
          /*
           * If 'val' is 3, registration was denied.
           */

          /* Perform fail-over code from timeout handler. */

          network_register_timer_handler(modem, -1, sub);

          return;

        case 2:
          /*
           * If 'val' is 2, modem is trying to register.
           */

          return;

        default:
          /*
           * Unknown.
           */

          return;
      }
    }
  else
    {
      /* Current level is UBMODEM_LEVEL_NETWORK or higher. */

      switch (val)
        {
          default: /* Unknown? */
          case 1: /* Switched to home network? */
          case 5: /* Switched to roaming? */

            if (modem->creg_timer_id >= 0)
              {
                __ubmodem_remove_timer(modem, modem->creg_timer_id);
                modem->creg_timer_id = -1;
              }

            return;

          case 2: /* Looking for connection. */

            /* Start connection search timeout timer. */

            ret = __ubmodem_set_timer(modem, MODEM_CMD_NETWORK_TIMEOUT * 100,
                                      &network_reregister_timer_handler, modem);
            if (ret == ERROR)
              {
                /* Error here? Add assert? Or just try bailout? */

                MODEM_DEBUGASSERT(modem, false);

                (void)network_reregister_timer_handler(modem, -1, modem);
                return;
              }

            modem->creg_timer_id = ret;

            return;

          case 3: /* Registration failed? */
          case 4: /* Unknown registration error? */
          case 0: /* MT not searching for connection. */

            /* Unregister +CREG URC */

            __ubparser_unregister_response_handler(&modem->parser,
                                                   urc_ATpCREG.name);
            modem->creg_urc_registered = false;

            /* Issue new task. We cannot issue new state machine work from
             * URC 'context' as other work might be active in main state
             * machine. Task will be run with main state machine in proper
             * state. */

            __ubmodem_add_task(modem, retry_network_through_sim, NULL);

            return;
        }
    }
}