/*******************************************************************************
	sms2smtp.c	3/24/03
	-	This program will take sms message received and forward the text as an
		smtp message to a sendmail server, defined by the following defines. This
		demo is based on basic_sms.c and is used in conjunction with smtp2msg.c
		to display SMS messages on a Display board using a local area WiFI network.

	SMTP_SERVER		- server host
   SMTP_TO			- Recipient of Email
   SMTP_FROM		- Sender of Email

END DESCRIPTION **********************************************************/

#memmap 	xmem
#class	auto
//#define	MDM_DEBUG				// Allows Single Stepping
//#define	GSM_DEBUG            // For Single stepping
//#define SMTP_VERBOSE
//#define NUMBERCHECK		// uncomment to enable phonenumber checking

// Response replied to if SMS message is received
#define	AUTO_RSP	"THANKS FOR VISITING RABBIT SEMICONDUCTOR"
// Check for Rabbit 3000 Chip installed
#if (_CPU_ID_ >= R3000)
	#define 	PORTA_AUX_IO 					// needed for the R3k and LCD
	#if (_BOARD_TYPE_ < RCM3400A  ||   _BOARD_TYPE_ > RCM3410A )
		#define SERB_CTS_PORT PCDR
		#define SERB_CTS_BIT 3					// use PC3 as CTS (input)
		#define SERB_RTS_PORT PCDR
		#define SERB_RTS_SHADOW PCDRShadow
		#define SERB_RTS_BIT 2              // use PC2 as RTS (output)
      #define 	MODEM_SERB_ENABLED      // Serial Port to Connect Modem to
		#define 	MODEM_SERB_HANDSHAKING  // Enables Handshaking (RTS/CTS)
	#else
      #define SERD_CTS_PORT PCDR
		#define SERD_CTS_BIT 3					// use PC3 as CTS (input)
		#define SERD_RTS_PORT PCDR
		#define SERD_RTS_SHADOW PCDRShadow
		#define SERD_RTS_BIT 2              // use PC2 as RTS (output)
      #define 	MODEM_SERD_ENABLED      // Serial Port to Connect Modem to
		#define 	MODEM_SERD_HANDSHAKING  // Enables Handshaking (RTS/CTS)
	#endif
#endif


#define	MAX_MODEMS	1				// Number Of Modems to Use (6 max)
#define	MDM_WAVECOM	0				// Used in sample only
#if (_BOARD_TYPE_ < RCM3400A  ||   _BOARD_TYPE_ > RCM3410A)
	#define 	BINBUFSIZE  255         // Largest RX Packet Avail.
	#define 	BOUTBUFSIZE 255         // Largest TX Packet
   #define	MDM_INBUFSIZE	BINBUFSIZE  // Modem Input Buffer Size
	#define	MDM_OUTBUFSIZE	BOUTBUFSIZE // Modem Output Buffer Size
#else
   #define 	DINBUFSIZE  255         // Largest RX Packet Avail.
	#define 	DOUTBUFSIZE 255         // Largest TX Packet
   #define	MDM_INBUFSIZE	DINBUFSIZE  // Modem Input Buffer Size
	#define	MDM_OUTBUFSIZE	DOUTBUFSIZE // Modem Output Buffer Size
#endif

#define	GSM_SMS_ENABLE             // Enables SMS Text Messaging
#use 		"mdm_wavecom.lib"				// wavecom specific library

// setting up the SSID, Ad-hoc mode, and channel 3
#define SSID	"RabbitDemo:1234"
#define WIFI_INIT	\
	pd_ioctl(0,WIFI_MODE,"IBSS",0);\
	pd_ioctl(0,WIFI_SSID,SSID,0);\
   pd_ioctl(0,WIFI_OWNSSID,SSID,0);\
   pd_ioctl(0,WIFI_OWNCHAN,"3",0);

#define TCPCONFIG 1

#define SMTP_SERVER	"192.168.0.1"	// set this to your smtp server
#define SMTP_TO		"smtp2msg"
#define SMTP_FROM		"sms2smtp"
#define SMTP_SUBJECT	"testing..."


#define "CFPRISM.LIB"
#use "dcrtcp.lib"
#use "smtp.lib"

// Display A String at a specific location in the STDIO window
void DispStr(int x, int y, char *s)
{
   x += 0x20;
   y += 0x20;
   printf ("\x1B=%c%c%s", x, y, s);
}

main ()
{
	static char at_rsp[MDM_INBUFSIZE];
	static int str,berr,done,index,chk,recv,loop;
	static struct tm	Time;
   static long tmChk;
	// Initialize SBC
   brdInit();
   // Initialize Serial Port for Modem Control.
   #if (_BOARD_TYPE_ < RCM3400A  ||  _BOARD_TYPE_ > RCM3410A)
   Modem_Serial_Options(MDM_WAVECOM, M_SERB, 9600, PARAM_8BIT, PARAM_NOPARITY, 1);
   Modem_Signal_Config(MDM_WAVECOM, MODEM_RTS, WrPortI, PCDR, &PCDRShadow, SERB_RTS_BIT, 0);
   Modem_Signal_Config(MDM_WAVECOM, MODEM_CTS, RdPortI, PCDR, &PCDRShadow, SERB_CTS_BIT, 0);
   #else
   Modem_Serial_Options(MDM_WAVECOM, M_SERD, 9600, PARAM_8BIT, PARAM_NOPARITY, 1);
   Modem_Signal_Config(MDM_WAVECOM, MODEM_RTS, WrPortI, PCDR, &PCDRShadow, SERD_RTS_BIT, 0);
   Modem_Signal_Config(MDM_WAVECOM, MODEM_CTS, RdPortI, PCDR, &PCDRShadow, SERD_CTS_BIT, 0);
   #endif
   Modem_Port_Open(MDM_WAVECOM);
   #if (_CPU_ID_ < R3000)
   serMode(1);
   #endif
   if (tmChk != dc_timestamp)
   {
    	mktm(&Time,dc_timestamp);
    	tm_wr(&Time);
    	tmChk = dc_timestamp;
   }
   tm_rd(&Time);
   printf("Modem Sample Program");
   // Initialize Modem
   while ((chk = GSM_Initialize(MDM_WAVECOM,10,1000)) == 0);
   if (chk != MDM_SUCCESS)
   {
    	DispStr(0,1,"!!!NO MODEM PRESENT!!!");
    	exit(1);
   }
   done = 0;
   index = 0;
   // Loop until all functions are completed.
   while (!done)
   {
      // Sample costate for getting misc. information from the modem.
    	costate
    	{
    		// Get the Manufacturer Description
       	waitfor(GSM_GetManuFacturer(MDM_WAVECOM,at_rsp));
       	DispStr(0,2,"Manufacturer:");
       	DispStr(20,2,at_rsp);
       	// Get the Model ID Number
         waitfor(GSM_GetModelID(MDM_WAVECOM,at_rsp));
         DispStr(0,3,"Model ID:");
       	DispStr(20,3,at_rsp);
       	// Get the Subscriber Phone on the Sim Card
         waitfor(GSM_GetPhoneNumber(MDM_WAVECOM,at_rsp));
         DispStr(0,4,"Phone Number:");
       	DispStr(20,4,at_rsp);
       	waitfor(GSM_SetTimeDate(MDM_WAVECOM,&Time));
       	// Get the Time and Date from the Modem
         waitfor(GSM_GetTimeDate(MDM_WAVECOM,&Time));
         DispStr(0,5,"Time Date:");
         sprintf(at_rsp,"%02d/%02d/%04d  %02d:%02d:%02d",
         		   Time.tm_mday,Time.tm_mon,Time.tm_year + 1900,
         		   Time.tm_hour,Time.tm_min,Time.tm_sec);
       	DispStr(20,5,at_rsp);
       	// Get the SMSC Number from the sim card
         waitfor(GSM_GetSMSCNumber(MDM_WAVECOM,at_rsp));
         DispStr(0,6,"SMSC Number:");
       	DispStr(20,6,at_rsp);
       	// Check the Current Network Status
       	waitfor(GSM_NetworkConnect(MDM_WAVECOM));
       	waitfor(GSM_GetNetworkStatus(MDM_WAVECOM,&str,&berr));
         DispStr(0,7,"Network Status:");
         if (str)sprintf(at_rsp,"Enabled,");
         else sprintf(at_rsp,"Disabled,");
         DispStr(20,7,at_rsp);
         if (!berr) sprintf(at_rsp,"Connected");
         else if (berr == 5) sprintf(at_rsp,"Roaming");
         else sprintf(at_rsp,"%d",berr);
         DispStr(31,7,at_rsp);
         // Initialize SMS Text Messaging
         waitfor(GSM_SmsInit(MDM_WAVECOM));
         // Set the Modem in SMS Text mode.
         waitfor(GSM_SmsMode(MDM_WAVECOM));
       	done = 1;
    	}
   }

// Main Loop For Receiving/Send Reply to SMS Messages.
	sock_init();

   smtp_sendmail(SMTP_TO,
   SMTP_FROM,
   SMTP_SUBJECT,
   "MSG=sms2smtp is up and running");

   printf("\n\nWaiting for SMS Message\n\n");
   for (;;)
   {
   	costate {
      	waitfor(DelayMs(50));
         smtp_mailtick();
      }
   	costate
   	{
         // Delay Between Checking for Messages
      	waitfor(DelayMs(5000));
      	// recv = 1 if A msg is received, -1 if no Msgs received.
   		waitfor((recv = GSM_SmsGet(MDM_WAVECOM,index))!= 0);
         if (recv == 1)
         {
         	// Display the Message from the sms_inbox structure.
         	printf("\n\n!!!!SMS Message Received!!!!\n\n");
         	printf("\nFrom:     %s\n",sms_inbox[MDM_WAVECOM][index].dpfp_num);
   			printf("\nTimeDate:  %s\n",sms_inbox[MDM_WAVECOM][index].date_time);
   			printf("\nMessage:   %s\n\n",sms_inbox[MDM_WAVECOM][index].txt_msg);
            smtp_sendmail(SMTP_TO,
            		sms_inbox[MDM_WAVECOM][index].dpfp_num,
            		sms_inbox[MDM_WAVECOM][index].date_time,
                  sms_inbox[MDM_WAVECOM][index].txt_msg);
#ifdef NUMBERCHECK
   			// Check for a proper phonenumber before sending reply.
   			if(strlen(sms_inbox[MDM_WAVECOM][index].dpfp_num) > 7)
   			{
         		printf("\nSending Reply to %s\n\n",
         				 sms_inbox[MDM_WAVECOM][index].dpfp_num+1);
         		waitfor(DelayMs(2500));
         		// Send the Message
         		waitfor((chk = GSM_SmsSend(MDM_WAVECOM,
         							sms_inbox[MDM_WAVECOM][index].dpfp_num+1,
         							AUTO_RSP)) != 0);
         		if (chk == 1) printf("Message Sent Successfully\n");
         		else	printf("Failed to send Message.\n");
         	}
         	// Phone number was invalid, message must have come form
         	// www.tmobile.com
         	else
         	{
          		printf("Can't Reply, Bad Phone Number (From a Website?)\n");
         	}
#endif
   			if (index < SMS_MSG_MAXMSGS -1) index++;
   			else index = 0;
   			// Setup for next text message reception.
   			printf("\n\nWaiting for SMS Message\n\n");
   		}
   	}
   }
}


