/*
 * config.c
 *
 *  Created on: Nov 30, 2022
 *      Author: ianst
 */


#include "config.h"
#include "math.h"
#include "TCPIPConfig.h"
#include "ianENC28J60.h"
#include "scheduler.h"
IP_CONFIG IPC_Local;
CONFIGPAGE IPConfig;
const CONFIGPAGE IPConfigF __attribute__ ((section (".config_data")))={
.IP.MyIPAddr.v[0]
=MY_DEFAULT_IP_ADDR_BYTE1,
MY_DEFAULT_IP_ADDR_BYTE2,
MY_DEFAULT_IP_ADDR_BYTE3,
MY_DEFAULT_IP_ADDR_BYTE4,

.IP.MyMask.v[0]=
MY_DEFAULT_MASK_BYTE1,
MY_DEFAULT_MASK_BYTE2,
MY_DEFAULT_MASK_BYTE3,
MY_DEFAULT_MASK_BYTE4,

.IP.MyGateway.v[0]=
MY_DEFAULT_GATE_BYTE1,
MY_DEFAULT_GATE_BYTE2,
MY_DEFAULT_GATE_BYTE3,
MY_DEFAULT_GATE_BYTE4,

.IP.PrimaryDNSServer.v[0]=
MY_DEFAULT_PRIMARY_DNS_BYTE1,
MY_DEFAULT_PRIMARY_DNS_BYTE2,
MY_DEFAULT_PRIMARY_DNS_BYTE3,
MY_DEFAULT_PRIMARY_DNS_BYTE4,

.IP.SecondaryDNSServer.v[0]=
MY_DEFAULT_SECONDARY_DNS_BYTE1,
MY_DEFAULT_SECONDARY_DNS_BYTE2,
MY_DEFAULT_SECONDARY_DNS_BYTE3,
MY_DEFAULT_SECONDARY_DNS_BYTE4,

.IP.MyMACAddr.v[0]=
MY_DEFAULT_MAC_BYTE1,
MY_DEFAULT_MAC_BYTE2,
MY_DEFAULT_MAC_BYTE3,
MY_DEFAULT_MAC_BYTE4,
MY_DEFAULT_MAC_BYTE5,
MY_DEFAULT_MAC_BYTE6,


.AutoStart=0,
.PartSerno[0]=1234,
.PartSerno[1]=1,

.StartUp[0]=0

};

void StartUpConfig(void)
{
	uint8_t * ptr;
	uint16_t len;
	uint8_t cmd;
	uint32_t addr;
   if (IPConfig.AutoStart==1)
   {

	ptr= (uint8_t *)IPConfig.StartUp;

	if ((*ptr)==CONFIG_LIST_TYPE_1)
	{
	 ptr++;
	 cmd=*ptr;
	 ptr++;
	 while (cmd>0)
	 {
		 addr=(uint32_t)*ptr;
		 ptr++;
		 addr+=(((uint32_t)*ptr)<<8);
		 ptr++;
		 addr+=(((uint32_t)*ptr)<<16);
		 ptr++;
		 addr+=(((uint32_t)*ptr)<<24);
		 ptr++;
	     len=(uint16_t )*ptr;
	     ptr++;
	     len+=((uint16_t )*ptr)<<8;
	     ptr++;
         if (((len&0x03)==0)&&((addr&0x03)==0))
         {
        	 while (len>0)
        	        	 {

        	        		 if (cmd==CONFIG_WRITE) *(uint32_t *)addr=*(uint32_t *)ptr;
        	        		 if (cmd==CONFIG_BIT_SET) *(uint32_t *)addr|=*(uint32_t *)ptr;
        	        		 if (cmd==CONFIG_BIT_CLEAR) *(uint32_t *)addr&=~(*(uint32_t *)ptr);
        	        		 ptr+=4;
        	        		 addr+=4;
        	        		 len-=4;
        	        	 }

         }
         else
         {
        	 while (len>0)
        	 {

        		 if (cmd==CONFIG_WRITE) *(uint8_t *)addr=*ptr;
        		 if (cmd==CONFIG_BIT_SET) *(uint8_t *)addr|=*ptr;
        		 if (cmd==CONFIG_BIT_CLEAR) *(uint8_t *)addr&=~(*ptr);
        		 ptr++;
        		 addr++;
        		 len--;
        	 }
         }
	     cmd=*ptr;
	     ptr++;
	 }
	}
   }
}
