From 1078f7aced63c6216bffe649930b97c9ccf9a16e Mon Sep 17 00:00:00 2001
From: Andrzej Zaborowski <balrog@zabor.org>
Date: Wed, 19 Sep 2007 14:04:50 +0200
Subject: [PATCH] Flush all pending commands before restarting the modem initialisation.

---
 include/gsmd/gsmd.h |    1 +
 src/gsmd/atcmd.c    |   21 +++++++++++++++++++++
 src/gsmd/timer.c    |    8 ++++++++
 3 files changed, 30 insertions(+), 0 deletions(-)

diff --git a/include/gsmd/gsmd.h b/include/gsmd/gsmd.h
index 4afdf66..6ac9d8e 100644
--- a/include/gsmd/gsmd.h
+++ b/include/gsmd/gsmd.h
@@ -131,6 +131,7 @@ struct gsmd_timer {
 
 int gsmd_timer_init(void);
 void gmsd_timer_check_n_run(void);
+void gsmd_timer_reset(void);
 
 struct gsmd_timer *gsmd_timer_alloc(void);
 int gsmd_timer_register(struct gsmd_timer *timer);
diff --git a/src/gsmd/atcmd.c b/src/gsmd/atcmd.c
index 27dfa41..2f6cee2 100644
--- a/src/gsmd/atcmd.c
+++ b/src/gsmd/atcmd.c
@@ -264,6 +264,27 @@ static int ml_parse(const char *buf, int len, void *ctx)
 	if (strlen(buf) == 0 ||
 	    !strcmp(buf, "AT-Command Interpreter ready")) {
 		g->interpreter_ready = 1;
+		g->clear_to_send = 1;
+
+		/* Flush current queue and reinitialise */
+		while (!llist_empty(&g->busy_atcmds)) {
+			cmd = llist_entry(g->busy_atcmds.next,
+					  struct gsmd_atcmd, list);
+			gsmd_log(GSMD_NOTICE, "discarding busy cmd %s\n",
+					cmd->buf);
+			llist_del(&cmd->list);
+			talloc_free(cmd);
+		}
+		while (!llist_empty(&g->pending_atcmds)) {
+			cmd = llist_entry(g->pending_atcmds.next,
+					  struct gsmd_atcmd, list);
+			gsmd_log(GSMD_NOTICE, "discarding pending cmd %s\n",
+					cmd->buf);
+			llist_del(&cmd->list);
+			talloc_free(cmd);
+		}
+
+		gsmd_timer_reset();
 		gsmd_initsettings(g);
 		gmsd_alive_start(g);
 		atcmd_wake_queue(g);
diff --git a/src/gsmd/timer.c b/src/gsmd/timer.c
index 5200690..8877275 100644
--- a/src/gsmd/timer.c
+++ b/src/gsmd/timer.c
@@ -215,3 +215,11 @@ void gsmd_timer_unregister(struct gsmd_timer *timer)
 	/* re-calculate next expiration */
 	calc_next_expiration();
 }
+
+void gsmd_timer_reset(void)
+{
+	while (!llist_empty(&gsmd_timers))
+		/* TODO: free associated resources (e.g timer->cancel_cb()) */
+		llist_del(&llist_entry(gsmd_timers.next,
+					struct gsmd_timer, list)->list);
+}
-- 
1.5.2.1

