采用TCP协议实现PIC18F97J60 ethernet bootloader

               了解更多关于bootloader 的C语言实现,请加我Q扣: 1273623966 (验证信息请填 bootloader),欢迎咨询或定制bootloader(在线升级程序)。

  TCP/IP Stack

  Microchip TCP/IP Stack是免费的,广泛应用于PIC单片机中。由于有远程更新程序的需求,我决定开发基于TCP协议的ethernet bootloader, 主要使用了Microchip TCP/IP Stack的TCP模块。最终我开发出来的ethernet bootloader 在PIC18F97J60上验证通过。整个实现上分两部分,一部分是单片机端的基于TCP协议的bootloader程序,我将其命名为PhnBoot_v2.0, 另外一部分是同样基于TCP协议与单片机互动的PC端通信程序,我将其命名为PhnLoader_v2.0。我还定义了PhnBoot_v2.0和PhnLoader_v2.0之间传输数据的通信协定。下面将细说我是如何实现的。

  通信协定

  单片机端PhnBoot_v2.0和PC端PhnLoader_v2.0之间的通信数据包采用以下协定

<STX><CMD><ADDRL><ADDRH><ADDRU><LEN><DATA>...<DATA><ETX>

  定义如下:

STX - Start of packet indicator
ETX - End of packet indicator
LEN - The length of true data
DATA - General data 16 bytes, only first LEN of datas are true
CMD - Base command
ADDR - Address up to 24 bits  ( ADDRL , ADDRH , ADDRH)

  具体有以下Base command:

RD-VER:  0x00 -- Read Version Information (最终版本删除了此命令)
RD_MEM: 0x01 -- Read Program Memory (最终版本删除了此命令)
ER_MEM: 0x03 -- Erase Program Memory
WR_MEM: 0x02 -- Write Program Memory
WR_CFG: 0x04 -- Write Configuration Registers

  PhnLoader_v2.0 功能

  定义好了通讯协定, 接着就按照协定去实现PhnLoader_v2.0。 PhnLoader_v2.0的具体功能包括选择IP地址,端口和协议类型, 目前只支持TCP协议, 创建TCP服务器,加载应用程序Hex文件,Parse 应用程序的Hex文件,一行一行解读Hex文件,一旦收到连接请求,建立TCP连接,一旦收到应用程序更新请求,立刻按照通讯协定采用TCP协议发送Hex记录到单片机,接收单片机发送回来的Response,发送完毕后断开TCP连接,发送期间出现问题就立马结束发送。

  PhnLoader_v2.0 主要代码段

  PhnLoader_v2.0是用C#实现的,是我在利用空余时间自学C#后写的,上面提到的功能都实现了。

        private void btnDownload_Click(object sender, EventArgs e)
        {
            btnDownload.Enabled = false;
            pBarLoading.Visible = false;
            if (!this.connect())
            {
                Debug.WriteLine("Udp server building unsuccessfully");
                textBoxStatus.ForeColor = Color.Red;
                textBoxStatus.AppendText("Udp server building unsuccessfully\r\n");
                textBoxStatus.ForeColor = Color.Black;
                btnDownload.Enabled = true;
                return;
            }

            try
            {
                loaderReader = new StreamReader(textBoxFile.Text);

            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error: " + ex.Message);
                textBoxStatus.ForeColor = Color.Red;
                textBoxStatus.AppendText("Read hex file unsuccessfully\r\n");
                textBoxStatus.ForeColor = Color.Black;
                loaderReader.Close();
                loaderServer.Close();
                btnDownload.Enabled = true;
                return;
            }

            loaderFrame = new SerialFrame();
            DateTime startTime = DateTime.Now;
            IPEndPoint clientPoint = new IPEndPoint(IPAddress.Any, 0);
            
            if (!loaderServer.Read(readyMsg,timeSpan))
            {
                Debug.WriteLine("Error: Timeout receive ready message from bootloader");
                textBoxStatus.ForeColor = Color.Red;
                textBoxStatus.AppendText("Timeout receive ready message from bootloader\r\n");
                textBoxStatus.ForeColor = Color.Black;
                loaderServer.Close();
                loaderReader.Close();
                btnDownload.Enabled = true;
                return;
            }

            if (!erase())
            {
                textBoxStatus.ForeColor = Color.Red;
                textBoxStatus.AppendText("Erase unsuccessfully\r\n");
                textBoxStatus.ForeColor = Color.Black;
                loaderReader.Close();
                loaderServer.Close();
                btnDownload.Enabled = true;
                return;
            }

            pBarLoading.Refresh();
            pBarLoading.Visible = true;
            pBarLoading.Value = 0;
            pBarLoading.Maximum = loaderLines;
            pBarLoading.Step = 1;

            string recordLine;
            Address_U = 0;
            bool isNextLineUserID = false;
            bool isNextLineConfigBits = false;
            textBoxStatus.AppendText("\r\nDownloading hex file ...\r\n");
            try
            {
                while (loaderReader.Peek() >= 0)
                {
                    pBarLoading.PerformStep();
                    recordLine = loaderReader.ReadLine();

                    if (recordLine.Contains(EXTEND_TOKEN) == true)
                    {
                        if (recordLine.Contains(USER_ID_TOKEN) == true)
                        {
                            isNextLineUserID = true;
                            continue;
                        }
                        else if (recordLine.Contains(CONFIG_BITS_TOKEN) == true)
                        {
                            const int ADDR_U_START_INDEX = 9;
                            const int ADDR_U_LENGTH = 4;
                            string addrU = recordLine.Substring(ADDR_U_START_INDEX, ADDR_U_LENGTH);
                            Address_U = Convert.ToInt32(addrU, 16) << 16;
                            isNextLineConfigBits = true;
                            continue;
                        }
                        else
                        {
                            const int ADDR_U_START_INDEX = 9;
                            const int ADDR_U_LENGTH = 4;
                            string addrU = recordLine.Substring(ADDR_U_START_INDEX, ADDR_U_LENGTH);
                            Address_U = Convert.ToInt32(addrU, 16) << 16;
                            continue;
                        }
                    }
                    else if (((recordLine.Contains(J_TYPE_CONFIG_BITS_1) == true) ||
                             (recordLine.Contains(J_TYPE_CONFIG_BITS_2) == true) ||
                             (recordLine.Contains(J_TYPE_CONFIG_BITS_3) == true) ||
                             (recordLine.Contains(J_TYPE_CONFIG_BITS_4) == true) ||
                             (recordLine.Contains(J_TYPE_CONFIG_BITS_5) == true) ||
                             (recordLine.Contains(J_TYPE_CONFIG_BITS_6) == true) ||
                             (recordLine.Contains(J_TYPE_CONFIG_BITS_TOKEN_1) == true) ||
                             (recordLine.Contains(J_TYPE_CONFIG_BITS_TOKEN_2) == true)) &&
                             (Address_U == 0x010000))
                    {
                        if (!DownloadConfigLine(recordLine))
                        {
                            Debug.WriteLine("Error found during configuration bits programming");
                            loaderReader.Close();
                            loaderServer.Close();
                            btnDownload.Enabled = true;
                            return;
                        }
                        continue;
                    }
                    else if (recordLine.Contains(END_OF_HEX_FILE_TOKEN) == true)
                    {
                        break;
                    }
                    if (isNextLineUserID)
                    {
                        isNextLineUserID = false;
                        // do nothing;
                    }
                    else if (isNextLineConfigBits)
                    {
                        if (!DownloadConfigLine(recordLine))
                        {
                            Debug.WriteLine("Error found during configuration bits programming");
                            loaderReader.Close();
                            loaderServer.Close();
                            btnDownload.Enabled = true;
                            return;
                        }
                        isNextLineConfigBits = false;
                    }
                    else
                    {
                        if (!DownloadDataLine(recordLine))
                        {
                            Debug.WriteLine("Error found during data programming");
                            loaderReader.Close();
                            loaderServer.Close();
                            btnDownload.Enabled = true;
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error: " + ex.Message);
                textBoxStatus.ForeColor = Color.Red;
                textBoxStatus.AppendText("Downloading failed\r\n");
                textBoxStatus.ForeColor = Color.Black;
                loaderServer.Close();
                loaderReader.Close();
                btnDownload.Enabled = true;
                return;
            }
            textBoxStatus.AppendText("Downloading completed\r\n");

            if (!run())
            {
                textBoxStatus.ForeColor = Color.Red;
                textBoxStatus.AppendText("Jump to Application unsuccessfully\r\n");
                textBoxStatus.ForeColor = Color.Black;
                loaderReader.Close();
                loaderServer.Close();
                btnDownload.Enabled = true;
                return;
            }
            loaderServer.Close();
            loaderReader.Close();
            btnDownload.Enabled = true;
        }    
View Code

  PhnLoader_v2.0 用户界面

  

  PhnBoot_v2.0 功能

  在PhnLoader_v2.0完成后,接着就是完成PhnBoot_v2.0。 PhnBoot_v2.0主要功能就是使用Microchip的TCP/IP Stack建立TCP Client,发送连接请求,建立连接后发送更新应用程序请求,接收PhnLoader_v2.0传送过来的Hex记录。解读Hex记录中的启始位,命名,地址,数据和结束位,将数据烧录到指定的程序存储器的位置上,然后通过ethernet返回Response消息给PC端PhnLoader_v2.0。

  PhnBoot_v2.0 位置

  PhnBoot_v2.0放置在程序存储器的头部,大小为0x4C00程序字。

  

  Interrupt Vector Remap

  由于PhnBoot_v2.0位于程序存储器的头部,需要对Interrupt Vector进行remap. 代码如下。

    #define APP_START                           0x4C00
    #define REMAPPED_APP_HIGH_INTERRUPT_VECTOR  0x4C08
    #define REMAPPED_APP_LOW_INTERRUPT_VECTOR   0x4C18 
    #pragma code low_vector_section=0x018
    void low_vector (void)
    {
        _asm
            goto REMAPPED_APP_LOW_INTERRUPT_VECTOR
        _endasm
    }

    #pragma code high_vector_section=0x08
    void high_vector (void)
    {
        _asm
            goto REMAPPED_APP_HIGH_INTERRUPT_VECTOR
        _endasm
    }

  PhnBoot_v2.0 主要代码段

  PhnBoot_v2.0 是用C语言写的,Microchip 8-bit C Compiler--MCC18编译的。

        switch (GenState)
        {
        case SM_HOME:
            ARPResolve(&Server.IPAddr);
            if (ARPIsResolved(&Server.IPAddr,&Server.MACAddr))
            {
            #ifdef STACK_USE_UDP
                MySock = UDPOpen(ClientPort,&Server,ServerPort);
            #endif
            #ifdef STACK_USE_TCP
                MySock = TCPOpen((DWORD)&Server, TCP_OPEN_NODE_INFO, ServerPort, 0);
            #endif
                if (MySock != INVALID_SOCKET)
                {
                    tick = 0x4000;
                    delay = BOOT_TIMEOUT;
                    GenState++;
                }
            }
            else
            {
                tick--;
                if (tick==0)
                {
                    tick = 0x4000;
                    if (delay == 0)
                    {
                        delay = BOOT_TIMEOUT;
                        GenState = SM_CLOSE;
                    }
                    delay--;
                }
            }
            break;
        case SM_READY:
            #ifdef STACK_USE_UDP
            if (UDPIsPutReady(MySock) > BUFFER_MAX)
            {
                UDPPutString(ok);
                UDPFlush();
                GenState++;
            }
            #endif
            #ifdef STACK_USE_TCP
            if (TCPIsConnected(MySock))
            {
                TCPPutString(MySock,ok);
                TCPFlush(MySock);
                GenState++;
            }
            #endif
            else
            {
                tick--;
                if (tick==0)
                {
                    tick = 0x4000;
                    if (delay == 0)
                    {
                        delay = BOOT_TIMEOUT;
                        GenState = SM_CLOSE;
                    }
                    delay--;
                }
            }
            break;
        case SM_RESPONSE:
            #ifdef STACK_USE_UDP
            networkBytes = UDPIsGetReady(MySock);
            #endif
            #ifdef STACK_USE_TCP
            networkBytes = TCPIsGetReady(MySock);
            #endif
            if (networkBytes >= BUFFER_MAX)
            {
            #ifdef STACK_USE_UDP
                UDPGetArray(line_buffer, BUFFER_MAX);
                UDPDiscard();
            #endif
            #ifdef STACK_USE_TCP
                TCPGetArray(MySock,line_buffer,BUFFER_MAX);
                TCPDiscard(MySock);
            #endif
                
                if (line_buffer[0] == STX && line_buffer[BUFFER_MAX - 1] == ETX)
                {
                    switch (line_buffer[CMD_INDEX])
                    {
                    case WR_MEM:
                        EECON1 = PGM_WRITE;
                        WriteMem();
                        break;
                    case WR_CFG:
                        if (!last_block_written&&!CFG_NUM)
                        {
                            WriteStart();
                            last_block_written = 1;
                            ResetBlockBuffer();
                        }
                        CFG_NUM++;
                        EECON1 = CFG_WRITE;
                        WriteCfg();
                        break;
                    case ER_MEM:
                        EECON1 = PGM_ERASE;
                        EraseMem();
                        break;
                    case RUN_APP:
                        if (!last_block_written)
                        {
                            WriteStart();
                            last_block_written = 1;
                            ResetBlockBuffer();
                        }
                        GenState++;
                    default:
                        break;
                    }
                    #ifdef STACK_USE_UDP
                    if (UDPIsPutReady(MySock) >= BUFFER_MAX)
                    {
                        UDPPutArray(line_buffer, BUFFER_MAX);
                        UDPFlush();
                    }
                    #endif
                    #ifdef STACK_USE_TCP
                    if (TCPIsPutReady(MySock) >= BUFFER_MAX)
                    {
                        TCPPutArray(MySock,line_buffer, BUFFER_MAX);
                        TCPFlush(MySock);
                    }
                    #endif
                }
            }
            else
            {
                tick--;
                if (tick==0)
                {
                    tick = 0x4000;
                    if (delay == 0)
                    {
                        delay = BOOT_TIMEOUT;
                        GenState = SM_CLOSE;
                    }
                    delay--;
                }
            }
            break;
        case SM_CLOSE:
            while (!TXSTAbits.TRMT);
            TXREG='>';
            #ifdef STACK_USE_UDP
            UDPClose(MySock);
            #endif
            #ifdef STACK_USE_TCP
            TCPDisconnect(MySock);
            #endif
            MySock = INVALID_SOCKET;
            _asm
                goto APP_START
            _endasm
            break;
        }

  如何使用 

  1. 使用MCC18编译PhnBoot_v2.0,

  2. 使用pickit3烧录PhnBoot_v2.0的Hex文件到目标板中。

  3. 拔除pickit3烧录器

  4. 将目标板与PC的接入同一局域网,并设置PC的IP地址和目标板的IP地址为同一网域,打开PhnLoader_v2.0用户界面,选择IP, 端口,和通信协议。

  5. 点击PhnLoader_v2.0用户界面上的“.."按钮加载需要烧录的应用程序Hex文件 (注意:由于PhnBoot_v2.0占用了程序存储器头部0x4C00程序字,所以应用程序编译需要设置Code offset为0x4C00)。

  6. 重启目标板,接着立刻在PhnLoader_v2.0界面上点击Download按钮。如果超时未点击Download按钮,目标板会自动跳转到上次烧录的应用程序中去。

  7. 烧录完毕,再次重启目标板, 2秒后目标板开始正常运行应用程序。

  之后每次更新应用程序,只需重复步骤 4 ~ 7 就可以了。

  主要特性

  本PIC ethernet bootloader有以下主要特性

  1. 使用了Microchip免费的TCP/IP Stack,采用TCP协议。

  2. C语言写的,MCC18 编译。

  3. 非常容易移植。

  4. 支持FLASH烧写, 快速,占用空间小。

  5. 可支持EEPROM烧写。

  6. 支持CONFIG BITS/IDLOC 烧写。

 

如果你有什么疑问,或有兴趣了解更多关于bootloader 的C语言实现,请加我Q扣: 1273623966 (验证信息请填 bootloader 或 cnblogs)。

posted @ 2015-10-24 21:04  GeekyGeek  阅读(2385)  评论(0编辑  收藏  举报