当我连接到以太网时、我无法获得 DHCP 分配的 IP、但通过我的笔记本电脑共享的以太网、我获得了 DHCP 分配的 IP、
我正在处理一个充电器、我的代码几乎是最终的。唯一的问题是、当我将以太网连接到我的 PC 共享以太网端口时、我能够以分配的 DHCP IP 访问服务器、但当我尝试通过调制解调器的实际以太网或进行访问时 一些其它的以太网 DHCP IP 未分配。我已经使用多个以太网端口进行了测试。每个端口都可以与我的 PC 和其它服务配合使用。
请检查文件以了解一些配置更改。我使用了 enet_weather 示例库。
//*****************************************************************************
//
// eth_client.c - This file handles all of the Ethernet connections using lwIP.
//
// Copyright (c) 2014-2017 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
//
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
//
// This is part of revision 2.1.4.178 of the EK-TM4C1294XL Firmware Package.
//
//*****************************************************************************
#include <stdint.h>
#include<string.h>
#include <stdbool.h>
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "driverlib/flash.h"
#include "driverlib/gpio.h"
#include "driverlib/interrupt.h"
#include "utils/ustdlib.h"
#include "driverlib/sysctl.h"
#include "driverlib/systick.h"
#include "utils/lwiplib.h"
#include "lwip/dns.h"
#include "eth_client.h"
#include "json.h"
#include "utils/uartstdio.h"
#include "driverlib/uart.h"
#include "PacketFormat/format.h"
#include "PacketFormat/tables.h"
#include "UART_Control/UARTHandler.h"
//*****************************************************************************
//
// Flag indexes for g_sEnet.ui32Flags
//
//*****************************************************************************
#define FLAG_TIMER_DHCP_EN 0
#define FLAG_TIMER_DNS_EN 1
#define FLAG_TIMER_TCP_EN 2
#define FLAG_DHCP_STARTED 3
#define FLAG_DNS_ADDRFOUND 4
//*****************************************************************************
//
// g_sEnet.ulRequest Values
//
//*****************************************************************************
#define WEATHER_NONE 0
#define WEATHER_CURRENT 1
#define WEATHER_FORECAST 2
extern uint8_t TestMode;
char buftemp[255];
uint8_t PacketType=e_None;
extern funct ReqFunctions[];
extern TransmitProcess ProcessTransmit; /*Ethernet Transmit Structure*/
extern char Response[1024];
extern Web_Socket_Flags WebSocketflags;
extern WebSocket_Strct WebSocket;
//*****************************************************************************
//
// The current state of the Ethernet connection.
//
//*****************************************************************************
struct
{
volatile uint32_t ui32Flags;
//
// Array to hold the MAC addresses.
//
uint8_t pui8MACAddr[8];
//
// Global define of the TCP structure used.
//
struct tcp_pcb *psTCP;
//
// Global IP structure to hold a copy of the IP address.
//
struct ip_addr sLocalIP;
//
// Global IP structure to hold a copy of the DNS resolved address.
//
struct ip_addr sServerIP;
//
// The saved proxy name as a text string.
//
const char *pcProxyName;
volatile enum
{
iEthNoConnection,
iEthDHCPWait,
iEthDHCPComplete,
iEthDNSWait,
iEthTCPConnectWait,
iEthTCPConnectComplete,
iEthQueryWait,
iEthTCPOpen,
iEthIdle
} eState;
unsigned long ulRequest;
tEventFunction pfnEvent;
}
g_sEnet;
//*****************************************************************************
//
// Maximum size of an weather request.
//
//*****************************************************************************
#define MAX_REQUEST 4096//2048
extern uint32_t g_ui32SysClock;
extern uint32_t g_ui32IPaddr;
//*****************************************************************************
//
// Various strings used to access weather information on the web.
//
//*****************************************************************************
char g_cWeatherRequest[] =
"GET ">api.openweathermap.org/.../weather
char g_cWeatherRequestForecast[] =
"GET ">api.openweathermap.org/.../daily
char g_cMode[] = "&mode=json&units=metric";
char g_cAPPIDOpenWeather[] =
"&APPID=afc5370fef1dfec1666a5676346b163b";
char g_cHTTP11[] = " HTTP/1.0\r\n\r\n";
/****************Hnadshake Data and URL**************/
//char cmd_1[] ="GET /EFILLXOCPP20J/AC001TEST HTTP/1.1\r\n";//"GET HTTP/1.1\r\n";//"GET 65.0.24.136:3002/EFILL002 HTTP/1.1\r\n";
//char cmd_2[] ="Host: 13.127.80.198:6002\r\n";
//char cmd_1[] ="GET /OCPP2.0.1/AC001TEST HTTP/1.1\r\n";//"GET HTTP/1.1\r\n";//"GET 65.0.24.136:3002/EFILL002 HTTP/1.1\r\n";
//char cmd_2[] ="Host: 65.0.24.136:3002\r\n";
char cmd_1[] ="GET /EFILLXOCPP16J/EFILLAC001_00002 HTTP/1.1\r\n";
//char cmd_1[] ="GET /EFILLXOCPP16J/EFILLAC001_00007 HTTP/1.1\r\n";
//char cmd_1[] ="GET /EFILLXOCPP16J/EFILLAC001_00001 HTTP/1.1\r\n";
//char cmd_1[] ="GET /EVELTXRFIK/PRO-GUJ-SZ-AC-002 HTTP/1.1\r\n";
char cmd_2[] ="Host: 13.127.80.198:6002\r\n";
//char cmd_2[] ="Host: econnect.electreefi.com:80\r\n";
char cmd_3[] ="Upgrade: websocket\r\n";
char cmd_4[] ="Connection: Upgrade\r\n";
char cmd_5[] ="Sec-WebSocket-Key: hsgS1BezikgQ9FxPJ3qWyw==\r\n";
char cmd_6[] ="Sec-WebSocket-Protocol: ocpp1.6\r\n";
char cmd_7[] ="Sec-WebSocket-Version: 13\r\n\r\n";
/***************************************************/
//*****************************************************************************
//
// This structure holds the state and control values for the weather requests.
//
//*****************************************************************************
struct
{
//
// The current weather source.
//
tWeatherSource eWeatherSource;
//
// The format expected from the weather source.
//
enum
{
iFormatJSON
}
eFormat;
//
// The application provided callback function.
//
tEventFunction pfnEvent;
//
// The application provided weather information structure.
//
tWeatherReport *psWeatherReport;
//
// The local buffer used to store the current weather request.
//
char pcRequest[MAX_REQUEST];
//
// The number of valid bytes in the request.
//
uint32_t ui32RequestSize;
}
g_sWeather;
//*****************************************************************************
//
// Close an active connection.
//
//*****************************************************************************
void
EthClientReset(void)
{
//
// No longer have a link.
//
g_sEnet.eState = iEthNoConnection;
//
// Reset the flags to just enable the lwIP timer.
//
g_sEnet.ui32Flags = (1 << FLAG_TIMER_DHCP_EN);
//
// Reset the addresses.
//
g_sEnet.sLocalIP.addr = 0;
g_sEnet.sServerIP.addr = 0;
//
// Deallocate the TCP structure if it was already allocated.
//
if(g_sEnet.psTCP)
{
//
// Clear out all of the TCP callbacks.
//
tcp_sent(g_sEnet.psTCP, NULL);
tcp_recv(g_sEnet.psTCP, NULL);
tcp_err(g_sEnet.psTCP, NULL);
//
// Close the TCP connection.
//
tcp_close(g_sEnet.psTCP);
g_sEnet.psTCP = 0;
}
}
//*****************************************************************************
//
// Handles lwIP TCP/IP errors.
//
// \param vPArg is the state data for this connection.
// \param iErr is the error that was detected.
//
// This function is called when the lwIP TCP/IP stack has detected an error.
// The connection is no longer valid.
//
// \return None.
//
//*****************************************************************************
static void
TCPError(void *vPArg, err_t iErr)
{
}
//*****************************************************************************
//
// Finalizes the TCP connection in client mode.
//
// \param pvArg is the state data for this connection.
// \param psPcb is the pointer to the TCP control structure.
// \param psBuf is the buffer structure that holds the data for this receive
// event.
// \param iErr is not used in this implementation.
//
// This function is called when the lwIP TCP/IP stack has completed a TCP
// connection.
//
// \return This function will return an lwIP defined error code.
//
//*****************************************************************************
static err_t
TCPReceive(void *pvArg, struct tcp_pcb *psPcb, struct pbuf *psBuf, err_t iErr)
{
struct pbuf *psBufCur;
// char buftemp[1024];
int32_t i32Items;
if(psBuf == 0)
{
//
// Tell the application that the connection was closed.
//
if(g_sWeather.pfnEvent)
{
g_sWeather.pfnEvent(ETH_EVENT_CLOSE, 0, 0);
g_sWeather.pfnEvent = 0;
}
//
// Close out the port.
//
tcp_close(psPcb);
if(psPcb == g_sEnet.psTCP)
{
g_sEnet.psTCP = 0;
}
g_sEnet.eState = iEthIdle;
PacketType = e_None;
return(ERR_OK);
}
if(g_sEnet.eState == iEthQueryWait) //Data Response for Query
{
// memset(buftemp,0,psBuf->len);
// memcpy(buftemp ,psBuf->payload,psBuf->len );
// UARTprintf("\n\t%s",buftemp);//@@@
// UARTprintf("\n\tLen:- %d",psBuf->len);//@@@
// UARTprintf("\n\t%s",((uint8_t *)psBuf->payload));//@@@
// UARTprintf("\n");
i32Items = ParseExample(0,psBuf);
// UARTprintf("NumberofItems: %u\n\r",i32Items);
if(i32Items>0)
{
// UARTprintf("NumberofItems: %u\n\r",i32Items);
}
if(g_sWeather.pfnEvent)
{
g_sWeather.pfnEvent(ETH_EVENT_RECEIVE,
(void *)g_sWeather.psWeatherReport, 0);
//
// Clear the event function and return to the idle state.
//
g_sEnet.eState = iEthIdle;
PacketType = e_InitbyClientRec;
}
}
else //Data Recieved without Query
{
//
// Go to idle state.
//
// memcpy(buftemp ,psBuf->payload,psBuf->len );
// UARTprintf("\n\t%s",buftemp);//@@@
// UARTprintf("\n\t%s",((uint8_t *)psBuf->payload));//@@@
// UARTprintf("\n");
i32Items = ParseExample(0,psBuf);
if(g_sWeather.pfnEvent)
{
g_sWeather.pfnEvent(ETH_EVENT_RECEIVE,
(void *)g_sWeather.psWeatherReport, 0);
//
// Clear the event function and return to the idle state.
//
g_sEnet.eState = iEthIdle;
}
g_sEnet.eState = iEthIdle;
PacketType = e_InitByServerRec;
}
//
// Initialize the linked list pointer to parse.
//
psBufCur = psBuf;
//
// Free the buffers used since they have been processed.
//
while(psBufCur->len != 0)
{
//
// Indicate that you have received and processed this set of TCP data.
//
tcp_recved(psPcb, psBufCur->len);
//
// Go to the next buffer.
//
psBufCur = psBufCur->next;
//
// Terminate if there are no more buffers.
//
if(psBufCur == 0)
{
break;
}
}
//
// Free the memory space allocated for this receive.
//
pbuf_free(psBuf);
//
// Return.
//
return(ERR_OK);
}
//*****************************************************************************
//
// Handles acknowledgment of data transmitted via Ethernet.
//
// \param pvArg is the state data for this connection.
// \param psPcb is the pointer to the TCP control structure.
// \param ui16Len is the length of the data transmitted.
//
// This function is called when the lwIP TCP/IP stack has received an
// acknowledgment for data that has been transmitted.
//
// \return This function will return an lwIP defined error code.
//
//*****************************************************************************
static err_t
TCPSent(void *pvArg, struct tcp_pcb *psPcb, u16_t ui16Len)
{
//
// Return OK.
//
return (ERR_OK);
}
//*****************************************************************************
//
// Finalizes the TCP connection in client mode.
//
// \param pvArg is the state data for this connection.
// \param psPcb is the pointer to the TCP control structure.
// \param iErr is not used in this implementation.
//
// This function is called when the lwIP TCP/IP stack has completed a TCP
// connection.
//
// \return This function will return an lwIP defined error code.
//
//*****************************************************************************
static err_t
TCPConnected(void *pvArg, struct tcp_pcb *psPcb, err_t iErr)
{
//
// Check if there was a TCP error.
//
if(iErr != ERR_OK)
{
//
// Clear out all of the TCP callbacks.
//
tcp_sent(psPcb, NULL);
tcp_recv(psPcb, NULL);
tcp_err(psPcb, NULL);
//
// Close the TCP connection.
//
tcp_close(psPcb);
if(psPcb == g_sEnet.psTCP)
{
g_sEnet.psTCP = 0;
}
//
// And return.
//
return (ERR_OK);
}
//
// Setup the TCP receive function.
//
tcp_recv(psPcb, TCPReceive);
//
// Setup the TCP error function.
//
tcp_err(psPcb, TCPError);
//
// Setup the TCP sent callback function.
//
tcp_sent(psPcb, TCPSent);
//
// Connection is complete.
//
g_sEnet.eState = iEthTCPConnectComplete;
//
// Return a success code.
//
return(ERR_OK);
}
//*****************************************************************************
//
// TCP connect
//
// This function attempts to connect to a TCP endpoint.
//
// \return None.
//
//*****************************************************************************
err_t
EthClientTCPConnect(uint32_t ui32Port)
{
err_t eTCPReturnCode;
//
// Enable the TCP timer function calls.
//
HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_TCP_EN) = 1;
if(g_sEnet.psTCP)
{
//
// Initially clear out all of the TCP callbacks.
//
tcp_sent(g_sEnet.psTCP, NULL);
tcp_recv(g_sEnet.psTCP, NULL);
tcp_err(g_sEnet.psTCP, NULL);
//
// Make sure there is no lingering TCP connection.
//
tcp_close(g_sEnet.psTCP);
}
//
// Create a new TCP socket.
//
g_sEnet.psTCP = tcp_new();
//
// Check if you need to go through a proxy.
//
// if(g_sEnet.pcProxyName != 0)
// {
//
// Attempt to connect through the proxy server.
//
// eTCPReturnCode = tcp_connect(g_sEnet.psTCP, &g_sEnet.sServerIP,
// ui32Port, TCPConnected);
// }
// else
// {
//
// Attempt to connect to the server directly.
//
eTCPReturnCode = tcp_connect(g_sEnet.psTCP, &g_sEnet.sServerIP,
ui32Port, TCPConnected);
// }
return(eTCPReturnCode);
}
//*****************************************************************************
//
// TCP connect
//
// This function attempts to connect to a TCP endpoint.
//
// \return None.
//
//*****************************************************************************
void
EthClientTCPDisconnect(void)
{
//
// No longer have a link.
//
g_sEnet.eState = iEthNoConnection;
//
// Deallocate the TCP structure if it was already allocated.
//
// HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_TCP_EN) = 0;
if(g_sEnet.psTCP)
{
//
// Close the TCP connection.
//
tcp_close(g_sEnet.psTCP);
g_sEnet.psTCP = 0;
}
}
//*****************************************************************************
//
// Handler function when the DNS server gets a response or times out.
//
// \param pcName is DNS server name.
// \param psIPAddr is the DNS server's IP address.
// \param vpArg is the configurable argument.
//
// This function is called when the DNS server resolves an IP or times out.
// If the DNS server returns an IP structure that is not NULL, add the IP to
// to the g_sEnet.sServerIP IP structure.
//
// \return None.
//
//*****************************************************************************
static void
DNSServerFound(const char *pcName, struct ip_addr *psIPAddr, void *vpArg)
{
//
// Check if a valid DNS server address was found.
//
if(psIPAddr != NULL)
{
//
// Copy the returned IP address into a global IP address.
//
g_sEnet.sServerIP = *psIPAddr;
//
// Tell the main program that a DNS address was found.
//
HWREGBITW(&g_sEnet.ui32Flags, FLAG_DNS_ADDRFOUND) = 1;
}
else
{
//
// Disable the DNS timer.
//
HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_DNS_EN) = 0;
}
}
//*****************************************************************************
//
// Required by lwIP library to support any host-related timer functions.
//
//*****************************************************************************
void
lwIPHostTimerHandler(void)
{
}
//*****************************************************************************
//
// Send a request to the server
//
// \param pcRequest request to be sent
// \param ui32Size length of the request to be sent. this is usually the size
// of the request minus the termination character
//
// This function will send the request to the connected server
//
// \return the lwIP error code.
//
//*****************************************************************************
err_t
EthClientSend(char *pcRequest, uint32_t ui32Size)
{
err_t eError;
eError = tcp_write(g_sEnet.psTCP, pcRequest, ui32Size,
TCP_WRITE_FLAG_COPY);
//
// Write data for sending (but does not send it immediately).
//
if(eError == ERR_OK)
{
//
// Find out what we can send and send it
//
tcp_output(g_sEnet.psTCP);
}
return(eError);
}
//*****************************************************************************
//
// DHCP connect
//
// This function obtains the MAC address from the User registers, starts the
// DHCP timer and blocks until an IP address is obtained.
//
// \return None.
//
//*****************************************************************************
err_t
EthClientDHCPConnect(void)
{
//
// Check if the DHCP has already been started.
//
if(HWREGBITW(&g_sEnet.ui32Flags, FLAG_DHCP_STARTED) == 0)
{
//
// Set the DCHP started flag.
//
HWREGBITW(&g_sEnet.ui32Flags, FLAG_DHCP_STARTED) = 1;
}
else
{
//
// If DHCP has already been started, we need to clear the IPs and
// switch to static. This forces the LWIP to get new IP address
// and retry the DHCP connection.
//
// lwIPNetworkConfigChange(0, 0, 0, IPADDR_USE_STATIC);
//
// Restart the DHCP connection.
//
lwIPNetworkConfigChange(0, 0, 0, IPADDR_USE_DHCP);
}
return ERR_OK;
}
//*****************************************************************************
//
// Handler function when the DNS server gets a response or times out.
//
// \param pcName is DNS server name.
//
// This function is called when the DNS server resolves an IP or times out.
// If the DNS server returns an IP structure that is not NULL, add the IP to
// to the g_sEnet.sServerIP IP structure.
//
// \return None.
//
//*****************************************************************************
int32_t
EthClientDNSResolve(const char *pcName)
{
err_t iRet;
if(HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_DNS_EN))
{
return(ERR_INPROGRESS);
}
//
// Set DNS config timer to true.
//
HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_DNS_EN) = 1;
//
// Initialize the host name IP address found flag to false.
//
HWREGBITW(&g_sEnet.ui32Flags, FLAG_DNS_ADDRFOUND) = 0;
//
// Resolve host name.
//
iRet = dns_gethostbyname(pcName, &g_sEnet.sServerIP, DNSServerFound, 0);
//
// If ERR_OK is returned, the local DNS table resolved the host name. If
// ERR_INPROGRESS is returned, the DNS request has been queued and will be
// sent to the DNS server.
//
if(iRet == ERR_OK)
{
//
// Stop calling the DNS timer function.
//
HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_DNS_EN) = 0;
}
//
// Return host name not found.
//
return(iRet);
}
//*****************************************************************************
//
// Returns the IP address for this interface.
//
// This function will read and return the currently assigned IP address for
// the Tiva Ethernet interface.
//
// \return Returns the assigned IP address for this interface.
//
//*****************************************************************************
uint32_t
EthClientAddrGet(void)
{
//
// Return IP.
//
return(lwIPLocalIPAddrGet());
}
//*****************************************************************************
//
// Returns the weather server IP address for this interface.
//
// This function will read and return the weather server IP address that is
// currently in use. This could be the proxy server if the Internet proxy
// is enabled.
//
// \return Returns the weather server IP address for this interface.
//
//*****************************************************************************
uint32_t
EthClientServerAddrGet(void)
{
//
// Return IP.
//
return((uint32_t)g_sEnet.sServerIP.addr);
}
//*****************************************************************************
//
// Returns the MAC address for the Tiva Ethernet controller.
//
// \param pui8MACAddr is the 6 byte MAC address assigned to the Ethernet
// controller.
//
// This function will read and return the MAC address for the Ethernet
// controller.
//
// \return Returns the weather server IP address for this interface.
//
//*****************************************************************************
void
EthClientMACAddrGet(uint8_t *pui8MACAddr)
{
int32_t iIdx;
for(iIdx = 0; iIdx < 6; iIdx++)
{
pui8MACAddr[iIdx] = g_sEnet.pui8MACAddr[iIdx];
}
}
//*****************************************************************************
//
// Set the proxy string for the Ethernet connection.
//
// \param pcProxyName is the string used as the proxy server name.
//
// This function sets the current proxy used by the Ethernet connection. The
// \e pcProxyName value can be 0 to indicate that no proxy is in use or it can
// be a pointer to a string that holds the name of the proxy server to use.
// The content of the pointer passed to \e pcProxyName should not be changed
// after this call as this function only stores the pointer and does not copy
// the data from this pointer.
//
// \return None.
//
//*****************************************************************************
void
EthClientProxySet(const char *pcProxyName)
{
//
// Save the new proxy string.
//
g_sEnet.pcProxyName = pcProxyName;
//
// Reset the connection on any change to the proxy.
//
EthClientReset();
}
//*****************************************************************************
//
// Initialize the Ethernet client
//
// This function initializes all the Ethernet components to not configured.
// This tells the SysTick interrupt which timer modules to call.
//
// \return None.
//
//*****************************************************************************
void
EthClientInit(tEventFunction pfnEvent)
{
uint32_t ui32User0, ui32User1;
//
// Initialize all the Ethernet components to not configured. This tells
// the SysTick interrupt which timer modules to call.
//
HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_DHCP_EN) = 0;
HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_DNS_EN) = 0;
HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_TCP_EN) = 0;
g_sEnet.eState = iEthNoConnection;
g_sEnet.pfnEvent = pfnEvent;
//
// Convert the 24/24 split MAC address from NV ram into a 32/16 split MAC
// address needed to program the hardware registers, then program the MAC
// address into the Ethernet Controller registers.
//
FlashUserGet(&ui32User0, &ui32User1);
g_sEnet.pui8MACAddr[0] = ((ui32User0 >> 0) & 0xff);
g_sEnet.pui8MACAddr[1] = ((ui32User0 >> 8) & 0xff);
g_sEnet.pui8MACAddr[2] = ((ui32User0 >> 16) & 0xff);
g_sEnet.pui8MACAddr[3] = ((ui32User1 >> 0) & 0xff);
g_sEnet.pui8MACAddr[4] = ((ui32User1 >> 8) & 0xff);
g_sEnet.pui8MACAddr[5] = ((ui32User1 >> 16) & 0xff);
lwIPInit(g_ui32SysClock, g_sEnet.pui8MACAddr, 0, 0, 0, IPADDR_USE_DHCP);
//
// Start lwIP tick interrupt.
//
HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_DHCP_EN) = 1;
}
//*****************************************************************************
//
// Periodic Tick for the Ethernet client
//
// This function is the needed periodic tick for the Ethernet client. It needs
// to be called periodically through the use of a timer or systick.
//
// \return None.
//
//*****************************************************************************
void
EthClientTick(uint32_t ui32TickMS)
{
uint32_t ui32IPAddr;
int32_t i32Ret;
if(HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_DHCP_EN))
{
lwIPTimer(ui32TickMS);
}
if(HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_DNS_EN))
{
dns_tmr();
}
if(HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_TCP_EN))
{
tcp_tmr();
}
//
// Check for loss of link.
//
if((g_sEnet.eState != iEthNoConnection) &&
(lwIPLocalIPAddrGet() == 0xffffffff))
{
//
// Reset the connection due to a loss of link.
//
EthClientReset();
//
// Signal a disconnect event.
//
g_sEnet.pfnEvent(ETH_EVENT_DISCONNECT, 0, 0);
}
else if(g_sEnet.eState == iEthNoConnection)
{
//
// Once link is detected start DHCP.
//
if(lwIPLocalIPAddrGet() != 0xffffffff)
{
EthClientDHCPConnect();
g_sEnet.eState = iEthDHCPWait;
}
}
else if(g_sEnet.eState == iEthDHCPWait)
{
//
// Get IP address.
//
ui32IPAddr = lwIPLocalIPAddrGet();
//
// If IP Address has not yet been assigned, update the display
// accordingly.
//
if((ui32IPAddr != 0xffffffff) && (ui32IPAddr != 0))
{
//
// Update the DHCP IP address.
//
g_sEnet.sLocalIP.addr = ui32IPAddr;
g_sEnet.eState = iEthDHCPComplete;
//
// Stop DHCP timer since an address has been provided.
//
HWREGBITW(&g_sEnet.ui32Flags, FLAG_DHCP_STARTED) = 0;
}
}
else if(g_sEnet.eState == iEthDHCPComplete)
{
if(g_sEnet.pcProxyName == 0)
{
//
// Resolve the host by name.
//
// i32Ret = EthClientDNSResolve("api.openweathermap.org");
// i32Ret = EthClientDNSResolve("65.0.24.136");
i32Ret = EthClientDNSResolve("13.127.80.198");
//i32Ret = EthClientDNSResolve("cms.efillelectric.com");
//i32Ret = EthClientDNSResolve("192.168.137.1");
//i32Ret = EthClientDNSResolve("econnect.electreefi.com");
}
else
{
//
// Resolve the proxy by name.
//
i32Ret = EthClientDNSResolve(g_sEnet.pcProxyName);
}
if(i32Ret == ERR_OK)
{
//
// If the address was already returned then go to idle.
//
g_sEnet.eState = iEthIdle;
//
// Notify the main routine of the new Ethernet connection.
//
g_sEnet.pfnEvent(ETH_EVENT_CONNECT, &g_sEnet.sLocalIP.addr, 4);
}
else if(i32Ret == ERR_INPROGRESS)
{
//
// If the request is pending the go to the iEthDNSWait state.
//
g_sEnet.eState = iEthDNSWait;
}
}
else if(g_sEnet.eState == iEthDNSWait)
{
//
// Check if the host name was resolved.
//
if(HWREGBITW(&g_sEnet.ui32Flags, FLAG_DNS_ADDRFOUND))
{
//
// Stop calling the DNS timer function.
//
HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_DNS_EN) = 0;
g_sEnet.eState = iEthIdle;
//
// Notify the main routine of the new Ethernet connection.
//
g_sEnet.pfnEvent(ETH_EVENT_CONNECT, &g_sEnet.sLocalIP.addr, 4);
}
}
else if(g_sEnet.eState == iEthTCPConnectWait)
{
}
else if(g_sEnet.eState == iEthTCPConnectComplete)
{
err_t eError;
g_sEnet.eState = iEthTCPOpen;
eError = EthClientSend(g_sWeather.pcRequest,
g_sWeather.ui32RequestSize);
if(eError == ERR_OK)
{
//
// Waiting on a query response.
//
g_sEnet.eState = iEthQueryWait;
}
else
{
g_sEnet.eState = iEthIdle;
}
}
}
//*****************************************************************************
//
// Set the current weather source.
//
//*****************************************************************************
void
WeatherSourceSet(tWeatherSource eWeatherSource)
{
//
// Save the source.
//
g_sWeather.eWeatherSource = eWeatherSource;
g_sWeather.eFormat = iFormatJSON;
}
//*****************************************************************************
//
// Merges strings into the current request at a given pointer and offset.
//
//*****************************************************************************
uint32_t MergeRequest1(int32_t i32Offset, char *pcSrc, int32_t i32Size)
{
int32_t i32Idx;
//
// Copy the base request to the buffer.
//
for(i32Idx = 0; i32Idx < i32Size; i32Idx++)
{
g_sWeather.pcRequest[i32Offset] = pcSrc[i32Idx];
if(WebSocketflags.HandshakeInprogress==1)
{
if((i32Offset >= sizeof(g_sWeather.pcRequest)) ||
(pcSrc[i32Idx] == 0))
{
break;
}
}
else
{
if(i32Offset >= sizeof(g_sWeather.pcRequest))
{
break;
}
}
i32Offset++;
}
return(i32Offset);
}
//*****************************************************************************
//
// Gets the daily forecast for a given city.
//
//*****************************************************************************
int32_t
WeatherForecast(tWeatherSource eWeatherSource, const char *pcQuery,
tWeatherReport *psWeatherReport, tEventFunction pfnEvent)
{
int32_t i32Idx;
// const char pcCount[] = "&cnt=1";
//
// If the requested source is not valid or there is no call back then
// just fail.
//
// if((eWeatherSource != iWSrcOpenWeatherMap) || (g_sWeather.pfnEvent))
// {
// return (-1);
// }
if(eWeatherSource != iWSrcOpenWeatherMap)
{
if(g_sWeather.pfnEvent)
{
return (-1);
}
}
g_sWeather.pfnEvent = pfnEvent;
g_sWeather.psWeatherReport = psWeatherReport;
// if(g_sEnet.eState == iEthNoConnection) return(0);
//
// Connect or reconnect to port 80.
//
// g_sEnet.eState = iEthTCPConnectWait;
//
// Copy the base forecast request to the buffer.
//
// i32Idx = MergeRequest1(0, g_cWeatherRequestForecast,
// sizeof(g_cWeatherRequestForecast));
//
// Append the request.
//
//i32Idx = MergeRequest1(i32Idx, pcQuery, sizeof(g_sWeather.pcRequest));
//
// Append the request mode.
//
// i32Idx = MergeRequest1(i32Idx, g_cMode, sizeof(g_cMode));
//
// Append the count.
//
//i32Idx = MergeRequest1(i32Idx, pcCount, sizeof(pcCount));
//
// Append the App ID.
//
// i32Idx = MergeRequest1(i32Idx, g_cAPPIDOpenWeather,
// sizeof(g_cAPPIDOpenWeather));
//
// Append the "HTTP:/1.1" string.
//
// i32Idx = MergeRequest1(i32Idx, g_cHTTP11, sizeof(g_cHTTP11));
// UARTprintf("\n\t%s",g_sWeather.pcRequest);
//
// Forcast weather report request.
//
// g_sEnet.ulRequest = WEATHER_FORECAST;
/*
ProcessTransmit.Tx_ActionIndex = Id_Heartbeat;
ProcessTransmit.Tx_MessageId[e_IdCallResult] = 2;
i32Idx = MergeRequest1(0,Webpack,sizeof(Webpack));
*/
if(ProcessTransmit.TransmitFlag[e_IdCall]==1)
{
ProcessTransmit.TransmitLength = ReqFunctions[ProcessTransmit.TransmitIndex[e_IdCall]]();
}
else
{
ProcessTransmit.TransmitLength = ReqFunctions[ProcessTransmit.TransmitIndex[e_IdCallResult]]();
}
WebSocketflags.DataLen = Websocket_TxHandle(Response,ProcessTransmit.TransmitLength,1,1);
i32Idx = MergeRequest1(0, WebSocketflags.DataBuff, WebSocketflags.DataLen);
if(WebSocketflags.HandshakeInprogress==1)
{
i32Idx = MergeRequest1(0, cmd_1, sizeof(cmd_1));
i32Idx = MergeRequest1(i32Idx, cmd_2, sizeof(cmd_2));
i32Idx = MergeRequest1(i32Idx, cmd_3, sizeof(cmd_3));
i32Idx = MergeRequest1(i32Idx, cmd_4, sizeof(cmd_4));
i32Idx = MergeRequest1(i32Idx, cmd_5, sizeof(cmd_5));
i32Idx = MergeRequest1(i32Idx, cmd_6, sizeof(cmd_6));
i32Idx = MergeRequest1(i32Idx, cmd_7, sizeof(cmd_7));
/*
i32Idx = MergeRequest1(i32Idx,Webpack,sizeof(Webpack));
ProcessTransmit.TransmitLength = ReqFunctions[ProcessTransmit.TransmitIndex[e_IdCallResult]]();
i32Idx = MergeRequest1(i32Idx, Response, ProcessTransmit.TransmitLength);
*/
// if(EthClientTCPConnect(3002) != ERR_OK)
if(EthClientTCPConnect(6002) != ERR_OK)
//if(EthClientTCPConnect(80) != ERR_OK)
{
return(-1);
}
}
else
{
// tcp_connect(g_sEnet.psTCP, &g_sEnet.sServerIP,3002, TCPConnected);
HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_TCP_EN) = 1;
// Setup the TCP receive function.
//
tcp_recv(g_sEnet.psTCP, TCPReceive);
//
// Setup the TCP error function.
//
tcp_err(g_sEnet.psTCP, TCPError);
//
// Setup the TCP sent callback function.
//
tcp_sent(g_sEnet.psTCP, TCPSent);
//
// Connection is complete.
//
g_sEnet.eState = iEthTCPConnectComplete;
}
//
// Save the size of the request.
//
g_sWeather.ui32RequestSize = i32Idx;
return(0);
}
//*****************************************************************************
//
// Gets the current weather information for a given city.
//
//*****************************************************************************
int32_t
WeatherCurrent(tWeatherSource eWeatherSource, const char *pcQuery,
tWeatherReport *psWeatherReport, tEventFunction pfnEvent)
{
int32_t i32Idx;
// if(eWeatherSource != iWSrcOpenWeatherMap)
// {
// if(g_sWeather.pfnEvent)
// {
// return (-1);
// }
// }
g_sWeather.pfnEvent = pfnEvent;
g_sWeather.psWeatherReport = psWeatherReport;
// tcp_connect(g_sEnet.psTCP, &g_sEnet.sServerIP,3002, TCPConnected);
ProcessTransmit.TransmitLength = ReqFunctions[ProcessTransmit.TransmitIndex[e_IdCall]]();
WebSocketflags.DataLen = Websocket_TxHandle(Response,ProcessTransmit.TransmitLength,1,1);
i32Idx = MergeRequest1(0, WebSocketflags.DataBuff, WebSocketflags.DataLen);
HWREGBITW(&g_sEnet.ui32Flags, FLAG_TIMER_TCP_EN) = 1;
// Setup the TCP receive function.
//
tcp_recv(g_sEnet.psTCP, TCPReceive);
//
// Setup the TCP error function.
//
tcp_err(g_sEnet.psTCP, TCPError);
//
// Setup the TCP sent callback function.
//
tcp_sent(g_sEnet.psTCP, TCPSent);
//
// Connection is complete.
//
g_sEnet.eState = iEthTCPConnectComplete;
g_sWeather.ui32RequestSize = i32Idx;
return(0);
}
void restore(void)
{
g_sEnet.eState = iEthIdle;
PacketType = e_None;
}
//Function Returns Length of Data After Adding Websocket
uint32_t Websocket_TxHandle(char *payload , uint32_t dtln,uint8_t Fin, uint8_t Masking)
{
uint32_t Dl=0;
if(WebSocketflags.HanshakeStatus==0)return 0;
WebSocket.BIT_FIELD.FIN =Fin;
WebSocket.BIT_FIELD.RSV1=0;
WebSocket.BIT_FIELD.RSV2=0;
WebSocket.BIT_FIELD.RSV3=0;
WebSocket.BIT_FIELD.OPCODE=1;
WebSocketflags.DataBuff[0]=WebSocket.BYTE_ARRAY[0];
Dl++;
WebSocket.BIT_FIELD.MASK=Masking;
//if(masking =1, Do masking of payload otherwise Do not mask payload)
//Generate a 32 bit Masking Key if Mask flag=1;
WebSocket.BIT_FIELD.MASKING_KEY1=0x2A;//ReturnRandomHex();// 0x2A;
WebSocket.BIT_FIELD.MASKING_KEY2=0x3C;//ReturnRandomHex();//0x3C;
WebSocket.BIT_FIELD.MASKING_KEY3=0x4D;//ReturnRandomHex();//0x4D;
WebSocket.BIT_FIELD.MASKING_KEY4=0x5B;//ReturnRandomHex();//0x5B;
//For now masking is fixed @enable i.e. 1
if(dtln>=126) //and smaller than 65535
{
//insert extended payload length here
WebSocket.BIT_FIELD.PAYLOAD_LEN = 126;
WebSocketflags.DataBuff[1] = WebSocket.BYTE_ARRAY[1];
Dl++;
WebSocket.BIT_FIELD.EXTENDED_PAYLOAD_LEN = dtln;
WebSocketflags.DataBuff[2] = WebSocket.BYTE_ARRAY[3];
Dl++;
WebSocketflags.DataBuff[3] = WebSocket.BYTE_ARRAY[2];
Dl++;
WebSocketflags.DataBuff[4] = WebSocket.BIT_FIELD.MASKING_KEY1;
Dl++;
WebSocketflags.DataBuff[5] = WebSocket.BIT_FIELD.MASKING_KEY2;
Dl++;
WebSocketflags.DataBuff[6] = WebSocket.BIT_FIELD.MASKING_KEY3;
Dl++;
WebSocketflags.DataBuff[7] = WebSocket.BIT_FIELD.MASKING_KEY4;
Dl++;
MaskData(dtln,payload);
Dl = (Dl+dtln);
}
else
{
WebSocket.BIT_FIELD.PAYLOAD_LEN = dtln;
WebSocketflags.DataBuff[1] = WebSocket.BYTE_ARRAY[1];
Dl++;
WebSocketflags.DataBuff[2] = WebSocket.BIT_FIELD.MASKING_KEY1;
Dl++;
WebSocketflags.DataBuff[3] = WebSocket.BIT_FIELD.MASKING_KEY2;
Dl++;
WebSocketflags.DataBuff[4] = WebSocket.BIT_FIELD.MASKING_KEY3;
Dl++;
WebSocketflags.DataBuff[5] = WebSocket.BIT_FIELD.MASKING_KEY4;
Dl++;
MaskData(dtln,payload);
Dl = (Dl+dtln);
}
return Dl;
}
void MaskData(uint32_t DataSize,char *payload) //if Data Size is smaller than equal to 125 bytes
{
uint32_t Lp=0;
uint8_t KeyId=0;
if(TestMode==false)UARTprintf("\r\nTX:- ");
if(DataSize>=126)
{
for(Lp=0;Lp<DataSize;Lp++)
{
if(TestMode==false)UARTCharPut(UART0_BASE,payload[Lp]);
WebSocketflags.DataBuff[Lp+8] = payload[Lp]^WebSocketflags.DataBuff[KeyId+4];
KeyId++;
if(KeyId>3)KeyId=0;
}
}
else
{
for(Lp=0;Lp<DataSize;Lp++)
{
if(TestMode==false)UARTCharPut(UART0_BASE,payload[Lp]);
WebSocketflags.DataBuff[Lp+6] = payload[Lp]^WebSocketflags.DataBuff[KeyId+2];
KeyId++;
if(KeyId>3)KeyId=0;
}
}
}
uint8_t ReturnRandomHex(void)
{
uint8_t RdmNum=0;
RdmNum = urand()%256-13;
return RdmNum;
}
/////////////////////////////////////////////////////////////////////
//*****************************************************************************
//
// enet_weather.c - Sample Weather application using lwIP.
//
// Copyright (c) 2014-2017 Texas Instruments Incorporated. All rights reserved.
// Software License Agreement
//
//*****************************************************************************
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "inc/hw_types.h"
#include "inc/hw_ints.h"
#include "inc/hw_memmap.h"
#include "inc/hw_nvic.h"
#include "inc/hw_gpio.h"
#include "driverlib/flash.h"
#include "driverlib/gpio.h"
#include "driverlib/interrupt.h"
#include "driverlib/pin_map.h"
#include "driverlib/rom.h"
#include "driverlib/rom_map.h"
#include "driverlib/sysctl.h"
#include "driverlib/systick.h"
#include "driverlib/emac.h"
#include "driverlib/timer.h"
#include "drivers/pinout.h"
#include "utils/cmdline.h"
#include "utils/locator.h"
#include "utils/flash_pb.h"
#include "utils/lwiplib.h"
#include "utils/uartstdio.h"
#include "utils/ustdlib.h"
#include "driverlib/uart.h"
#include "eth_client.h"
#include "enet_weather.h"
#include "fatfs/src/ff.h"
#include "fatfs/src/diskio.h"
#include "json.h"
#include "Timer_Control/TimerHandler.h"
#include "PacketFormat/format.h"
#include "Conversions/unit_conversion.h"
#include "GPIO_Control/GPIO_Controls.h"
#include "UART_Control/UARTHandler.h"
#include "Sensing_ADC/ADC_Sensing.h"
#include "sd_card/sd_card.h"
#include "EEPROM_Control/Int_EEPR.h"
#include "EEPROM_Control/i2c_config.h"
#include "EEPROM_Control/24AAN256.h"
#include "PacketFormat/tables.h"
#include "DisplayData/DisplayCommands.h"
#include "inc/hw_hibernate.h"
#include "driverlib/hibernate.h"
#include "UART_Control/Modem.h"
void Transmit_DataForCallResult(void);
void Transmit_DataForCall(void);
void HandleConnectionsServerStates(void);
void SendHandshake(void);
//extern VP_Table Variabledatatable[];
extern Relay_States RelayStates;
uint32_t OCPPVersion=0;
extern Level_Passwords LevelPasswords;
uint32_t OV_OC_DelayTime=0;
extern EV_Param EVParam;
char buffr[50];
uint8_t PowerUpflag=1;
uint8_t EthResetRequired=0;
uint32_t WaitEthReconnect=WAIT_ETH_RECONNECT;
extern Fuction_Handle FuctionHandle[TOTAL_ACTION_ARRAY_COUNT];
//extern uint16_t *tableArray1[];
extern char Response[1024];
extern TransmitProcess ProcessTransmit; /*Ethernet Transmit Structure*/
extern Web_Socket_Flags WebSocketflags;
extern TransmitProcess ProcessTransmit; /*Ethernet Transmit Structure*/
extern Param_Update_Flags ParamUpdateFlags;
extern UpdateSDCard_TL UpdateSDCardTL;
extern uint8_t Fault_Table1K_Flag;
extern uint8_t TL_Table1K_Flag;
extern uint8_t CacheMem1K_Flag;
extern Disp_ControlFunc DispControlFuncLatest;
//extern Relay_States RelayStates;
//extern struct g_sEnet;
//*****************************************************************************
//
//! \addtogroup example_list
//! <h1>Ethernet Weather Application (enet_weather)</h1>
//!
//! This example application demonstrates the operation of the Tiva C series
//! evaluation kit as a weather reporting application.
//!
//! The application supports updating weather information from Open Weather Map
//! weather provider(http://openweathermap.org/). The application uses the
//! lwIP stack to obtain an address through DNS, resolve the address of the
//! Open Weather Map site and then build and handle all of the requests
//! necessary to access the weather information. The application can also use
//! a web proxy, allows for a custom city to be added to the list of cities and
//! toggles temperature units from Celsius to Fahrenheit. The application
//! scrolls through the city list at a fixed interval when there is a valid
//! IP address and displays this information over the UART.
//!
//! The application will print the city name, status, humidity, current temp
//! and the high/low. In addition the application will display what city it
//! is currently updating. Once the app has scrolled through the cities a
//! a defined amount of times, it will attempt to update the information.
//!
//! UART0, connected to the Virtual Serial Port and running at 115,200, 8-N-1,
//! is used to display messages from this application.
//!
//!/ For additional details about Open Weather Map refer to their web page at:
//! http://openweathermap.org/
//!
//! For additional details on lwIP, refer to the lwIP web page at:
//! savannah.nongnu.org/.../
//
//*****************************************************************************
//*****************************************************************************
//
// Connection states for weather application.
//
//*****************************************************************************
volatile enum
{
STATE_NOT_CONNECTED, //ETHERNET NOT CONNECTED
STATE_NEW_CONNECTION, //SERVER CONNECTION STARTED
STATE_CONNECTED_IDLE, //CONNECTED AND CLIENT IN IDLE STATE
STATE_WAIT_DATA, //WAITING DATA TO RECEIVE
STATE_PROCESS_RX_DATA, //PROCESSING RECIEVED DATA
STATE_SERVER_BUSY,//This Happens if Server do not Respond Any Data for A Query
STATE_DATA_PROCESSED,
}
g_iState = STATE_NOT_CONNECTED;
uint8_t TCP_ConnectionStatus= e_TCP_Disconnected;
//*****************************************************************************
//
// Global for IP address.
//
//*****************************************************************************
uint32_t g_ui32IPaddr;
//*****************************************************************************
//
// The delay count to reduce traffic to the weather server.
//
//*****************************************************************************
volatile uint32_t g_ui32Delay;
err_t Err;
//*****************************************************************************
//
// System Clock rate in Hertz.
//
//*****************************************************************************
uint32_t g_ui32SysClock;
//*****************************************************************************
//
// Flag indicate Ehernet Transmission//1-->Transmit,0-->Idle
//
//*****************************************************************************
//uint8_t EthFlagTransmit=0;
extern Timer_Flags TimerFlags;
extern uint32_t Time_Sec;
//*****************************************************************************
//
// The defaults for the flash and application settings.
//
//*****************************************************************************
static const sParameters g_sDefaultParams =
{
0,
{"Custom City Name"},
{"your.proxy.com"},
false,
false,
false,
false
};
//
// The current live configuration settings for the application.
//
sParameters g_sConfig;
//*****************************************************************************
//
// The state of each city panel.
//
//*****************************************************************************
struct
{
//
// The last update time for this city.
//
uint32_t ui32LastUpdate;
//
// The current weather report data for this city.
//
tWeatherReport sReport;
//
// Indicates if the city needs updating.
//
bool bNeedsUpdate;
//
// The name of the current city.
//
const char *pcName;
}
g_psCityInfo[1];
//*****************************************************************************
//
// Interrupt priority definitions. The top 3 bits of these values are
// significant with lower values indicating higher priority interrupts.
//
//*****************************************************************************
#define SYSTICK_INT_PRIORITY 0x80
#define ETHERNET_INT_PRIORITY 0xC0
//*****************************************************************************
//
// The error routine that is called if the driver library encounters an error.
//
//*****************************************************************************
#ifdef DEBUG
void
__error__(char *pcFilename, uint32_t ui32Line)
{
}
#endif
//*****************************************************************************
//
// MAC address.
//
//*****************************************************************************
char g_pcMACAddr[40];
//*****************************************************************************
//
// IP address.
//
//*****************************************************************************
char g_pcIPAddr[20];
//*****************************************************************************
//
// Update the IP address string.
//
//*****************************************************************************
void
UpdateIPAddress(char *pcAddr, uint32_t ipAddr)
{
uint8_t *pui8Temp = (uint8_t *)&ipAddr;
if(ipAddr == 0)
{
ustrncpy(pcAddr, "IP: ---.---.---.---", sizeof(g_pcIPAddr));
}
else
{
usprintf(pcAddr,"IP: %d.%d.%d.%d", pui8Temp[0], pui8Temp[1],
pui8Temp[2], pui8Temp[3]);
}
}
void ProcessMcuLed(void);
//*****************************************************************************
//
// Update the MAC address string.
//
//*****************************************************************************
void
UpdateMACAddr(void)
{
uint8_t pui8MACAddr[6];
EthClientMACAddrGet(pui8MACAddr);
usprintf(g_pcMACAddr, "MAC: %02x:%02x:%02x:%02x:%02x:%02x",
pui8MACAddr[0], pui8MACAddr[1], pui8MACAddr[2], pui8MACAddr[3],
pui8MACAddr[4], pui8MACAddr[5]);
}
//*****************************************************************************
//
// Print the IP address string.
//
//*****************************************************************************
void
PrintIPAddress(char *pcAddr, uint32_t ipaddr)
{
uint8_t *pui8Temp = (uint8_t *)&ipaddr;
//
// Convert the IP Address into a string.
//
UARTprintf("%d.%d.%d.%d\n", pui8Temp[0], pui8Temp[1], pui8Temp[2],
pui8Temp[3]);
}
//*****************************************************************************
//
// Updates the UART information.
//
//*****************************************************************************
void
UpdateUART(void)
{
volatile uint32_t ui32IPaddr;
//
// Get the IP address.
//
ui32IPaddr = EthClientAddrGet();
//
// If the IP changed, reassign.
//
if (g_ui32IPaddr != ui32IPaddr)
{
//
// Reassign the global IP to the current.
//
g_ui32IPaddr = ui32IPaddr;
//
// Update the UART.
//
// g_UpdateUART = 1;
}
//
// Check if we should scroll the cities.
//
//
// Clear the terminal. Print the banner and IP place holder.
//
UARTprintf("SYSTEM IP: ");
//
// Print the IP address.
//
PrintIPAddress(g_pcIPAddr, ui32IPaddr);
UARTprintf("\n");
}
void
WeatherEvent(uint32_t ui32Event, void* pvData, uint32_t ui32Param)
{
if(ui32Event == ETH_EVENT_RECEIVE)
{
//
// Let the main loop update the city.
//
g_iState = STATE_DATA_PROCESSED;
g_iState= STATE_CONNECTED_IDLE;
// g_psCityInfo[g_ui32CityUpdating].ui32LastUpdate =
// g_psCityInfo[g_ui32CityUpdating].sReport.ui32Time;
}
else if(ui32Event == ETH_EVENT_INVALID_REQ)
{
//if Data packet Recieved not Valid
// g_psCityInfo[g_ui32CityUpdating].sReport.pcDescription = g_pcNotFound;
//g_iState = STATE_UPDATE_CITY;
g_iState= STATE_CONNECTED_IDLE;
}
else if(ui32Event == ETH_EVENT_CLOSE)
{
if(g_iState == STATE_WAIT_DATA)
{
// g_psCityInfo[g_ui32CityUpdating].sReport.pcDescription =
// g_pcServerBusy;
//SERVER NOT ABLE TO RESPOND//
g_iState = STATE_SERVER_BUSY;
}
}
//
// If the update indicated no time, then just set the time to a value
// to indicate that at least the update occurred.
//
if(g_psCityInfo[0].ui32LastUpdate == 0)
{
//
// Failed to update for some reason.
//
g_psCityInfo[0].ui32LastUpdate = 1;
}
}
//*****************************************************************************
//
// The interrupt handler for the SysTick interrupt.
//
//*****************************************************************************
void
SysTickIntHandler(void)
{
//
// Call the lwIP timer handler.
//
EthClientTick(SYSTEM_TICK_MS);
disk_timerproc();
//
// Handle the delay between accesses to the weather server.
//
if(g_ui32Delay != 0)
{
g_ui32Delay--;
}
}
//*****************************************************************************
//
// Network events handler.
//
//*****************************************************************************
void
EnetEvents(uint32_t ui32Event, void *pvData, uint32_t ui32Param)
{
if(ui32Event == ETH_EVENT_CONNECT)
{
// if(!(TCP_ConnectionStatus==e_TCP_NotResponding))
// {
g_iState = STATE_NEW_CONNECTION;
// }
//
// Update the string version of the address.
//
UpdateIPAddress(g_pcIPAddr, EthClientAddrGet());
}
else if(ui32Event == ETH_EVENT_DISCONNECT)
{
g_iState = STATE_NOT_CONNECTED;
//
// Update the address to 0.0.0.0.
//
UpdateIPAddress(g_pcIPAddr, 0);
}
}
int
main(void)
{
ROM_FPULazyStackingEnable();
ROM_FPUEnable();
sParameters *pParams;
//
// Make sure the main oscillator is enabled because this is required by
// the PHY. The system must have a 25MHz crystal attached to the OSC
// pins. The SYSCTL_MOSC_HIGHFREQ parameter is used when the crystal
// frequency is 10MHz or higher.
//
SysCtlMOSCConfigSet(SYSCTL_MOSC_HIGHFREQ);
#if INTERNAL_CLOCK
//Run On internal Clock
g_ui32SysClock = MAP_SysCtlClockFreqSet(SYSCTL_OSC_INT | SYSCTL_USE_PLL | SYSCTL_CFG_VCO_480, 120000000);
//
#elif EXTERNAL_CLOCK
//
// Run from the PLL at 120 MHz.
//
g_ui32SysClock = MAP_SysCtlClockFreqSet((SYSCTL_XTAL_25MHZ |
SYSCTL_OSC_MAIN |
SYSCTL_USE_PLL |
SYSCTL_CFG_VCO_480), 120000000);
#endif
//
// Configure the device pins.
//
PinoutSet(true, false);
GPIO_Configure();
/********************************EEPROM INITIALIZATION********************************/
initialize_Internal_EEPR();
LoadEEPROMAllParameters();
/**************************************************************************************/
//
// Initialize the UART 0.
//
UARTStdioConfig(0, 115200, g_ui32SysClock);
/********************************UART CONFIGURATIONS**********************************/
// Initialize_Uart(0);
Initialize_Uart(1);
Initialize_Uart(2);
Initialize_Uart(3);
/*************************************************************************************/
//
// Configure SysTick for a periodic interrupt at 10ms.
//
SysTickPeriodSet((g_ui32SysClock / 1000) * SYSTEM_TICK_MS);
SysTickEnable();
SysTickIntEnable();
//
// Initialized the flash program block and read the current settings.
//
FlashPBInit(FLASH_PB_START, FLASH_PB_END, 256);
pParams = (sParameters *)FlashPBGet();
//
// Use the defaults if no settings were found.
//
if(pParams == 0)
{
g_sConfig = g_sDefaultParams;
}
else
{
g_sConfig = *pParams;
}
//
// Set the IP address to 0.0.0.0.
//
UpdateIPAddress(g_pcIPAddr, 0);
//
// Enable processor interrupts.
//
IntMasterEnable();
//
// Set the interrupt priorities. We set the SysTick interrupt to a higher
// priority than the Ethernet interrupt to ensure that the file system
// tick is processed if SysTick occurs while the Ethernet handler is being
// processed. This is very likely since all the TCP/IP and HTTP work is
// done in the context of the Ethernet interrupt.
//
IntPriorityGroupingSet(4);
IntPrioritySet(INT_EMAC0, ETHERNET_INT_PRIORITY);
IntPrioritySet(FAULT_SYSTICK, SYSTICK_INT_PRIORITY);
g_sConfig.bProxyEnabled=0;
if(g_sConfig.bProxyEnabled)
{
EthClientProxySet(g_sConfig.pcProxy);
EthClientInit(EnetEvents);
}
else
{
EthClientProxySet(0);
EthClientInit(EnetEvents);
}
UpdateMACAddr();
//
// Get the IP address.
//
g_ui32IPaddr = EthClientAddrGet();
//
// Update the current city information.
//
UpdateUART();
//
// Loop forever. All the work is done in interrupt handlers.
//
/*************************************ENABLING RTC MODULE******************************************************/
ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_HIBERNATE);
// Wait for the Hibernate module to be ready.
while(!ROM_SysCtlPeripheralReady(SYSCTL_PERIPH_HIBERNATE)){}
ROM_HibernateEnableExpClk(g_ui32SysClock);
ROM_SysCtlDelay(3000);
ROM_HibernateClockConfig(HIBERNATE_OSC_LOWDRIVE);
ROM_SysCtlDelay(1000);
ROM_HibernateRTCTrimSet(0x7FFF);
ROM_HibernateRTCEnable(); // start RTC count
/******************************************************************************************************/
/********************************TIMER CONFIGURATIONS**********************************/
Initialize_TIMER(TIMER1);
Initialize_TIMER(TIMER0);
/************************************************************************************/
/*******************************Initialize EEPROM I2C********************************/
InitI2C1();
/************************************************************************************/
/********************************ADC CONFIGURATIONS**********************************/
ADC_Configure();
/************************************************************************************/
/********************************SD Card CONFIGURATIONS**********************************/
ConfigureSD_Card();
/************************************************************************************/
UpadateParam();
/*******************************UPDATE DISPLAY PARAMETERS****************************/
InitDisplayVariables();
/*******************************UPDATE DISPLAY PARAMETERS****************************/
//WriteEEPbysize(&Def_QR_CodeA[0] , 0X28 ,20);
//WriteEEPbysize(&Def_QR_CodeB[0] , 0x3C ,20);
// WriteEEPbysize(&Def_QR_CodeC[0] , 0X50 ,20);
// UpdateFaultLogCount(1);
// SetChargingCostParams(0,0,0,0,1);
// SetChargingCostParams(0,0,0,0,2);
// SetChargingCostParams(0,0,0,0,3);
InitCostVariablesfromEEPOnLoad();
LoadEEPParameters();
LoadVPParamValueFromEEProm();
LoadMeterValueOnInitialization();
FormatHandshakeStr();
//UpdateFaultTabletoSDCard();
//UpdateTLTabletoSDCard();
// Update1KfullCountFlag(0,enFaultLog);
// Update1KfullCountFlag(0,enTradeLog);
//Update1KfullCountFlag(0,enCacheData);
//Fault_Table1K_Flag = Read1Kflag(enFaultLog);
//TL_Table1K_Flag = Read1Kflag(enTradeLog);
//CacheMem1K_Flag = Read1Kflag(enCacheData);
//UpdateFaultLogCount(1);
//UpdateTLLogCount(0);
// FaultTableTotalPages = TotalPageCount(TotalSavedLogCount_Fault);
// TL_TotalPages = TotalPageCount(TotalSavedLogCount_TL);
//FaultTableCurrentPageNo = GetCurrentPage(6);
//TL_CurrentPageNo = GetCurrentPage(12);
//ParseSDCardDataFaultTable(1);
//ParseSDCardDataTLTable(1);
// InitializeDisplayParameters();
//memset(&ChargingRateA,0,4);
//ReadEEpbysize(Variabledatatable[TBID_PRODUCTID].Default_value ,Variabledatatable[TBID_PRODUCTID].EepAdress,Variabledatatable[TBID_PRODUCTID].DataLength );
// uint32_t defval[1];
// defval[0] = 0;
// Set_Int_EEP_32bit(defval , OCPP_VERSION );
//Set_Int_EEP_32bit(defval , 820 );
// Set_Int_EEP_32bit(defval , 824 );
//OverVoltage = Get_Int_EEP_32bit(Variabledatatable[TBID_OVERVOLTAGE].EepAdress);
//LocalIpAddr = Get_Int_EEP_32bit(Variabledatatable[TBID_LOCALIPADDR].EepAdress);
// xx = ReqFunctions[Id_Authorize]();
// UARTprintf("%s \n", Response);
// xx = ReqFunctions[Id_BootNotification]();
// UARTprintf("%s \n", Response);
/*
xx = Req_Authorize();
UARTprintf("%s \n", Response);
*/
//Pointer to string Array Get Field Value example
/*
int i=0;
char **ptr = NULL;
ptr =ActionString;
strcpy(buffr, ptr[0]);
strcpy(buffr, ptr[1]);
for(i=0;i<2;i++)
{
UARTprintf(" %s \n", ptr[i]);
}
*/
//////////////////////////////////////////////////
//Pointer to string Array Get Field Name example
/*
int i=0;
char **ptr = NULL;
ptr =TypeField_Name_strings[0];
strcpy(buffr, ptr[0]);
strcpy(buffr, ptr[1]);
for(i=0;i<2;i++)
{
UARTprintf(" %s \n", ptr[i]);
}
*/
//////////////////////////////////////////////////
//Pointer to string Array Get Field Value example
/*
strcpy(model_str , "EVAC001.01");
strcpy(VendorName_str , "E-fill Pvt. Ltd.");
int i=0;
char **ptr = NULL;
ptr =TypeFieldstrings[0];
strcpy(buffr, ptr[0]);
strcpy(buffr, ptr[1]);
for(i=0;i<2;i++)
{
UARTprintf(" %s \n", ptr[i]);
}
*/
//////////////////////////////////////////////////
//Pointer to string Array Get Enum strings Example
/*
int i=0;
char **ptr = NULL;
char **ptr1 = NULL;
ptr =EnumStrings[0]; //Here Enter index of Enum
ptr1 =EnumStrings[1]; //Here Enter index of Enum
strcpy(buffr, ptr[0]); //Get this by enum Value for perticular parameter
strcpy(buffr, ptr[1]); //Get this by enum Value for perticular parameter
strcpy(buffr, ptr[2]);
strcpy(buffr, ptr[3]);
strcpy(buffr, ptr[4]);
strcpy(buffr, ptr1[0]);
strcpy(buffr, ptr1[1]);
strcpy(buffr, ptr1[2]);
strcpy(buffr, ptr1[3]);
strcpy(buffr, ptr1[4]);
strcpy(buffr, ptr1[5]);
strcpy(buffr, ptr1[6]);
strcpy(buffr, ptr1[7]);
strcpy(buffr, ptr1[8]);
strcpy(buffr, ptr1[9]);
//sprintf("%s",ptr[0]);
for(i=0;i<4;i++)
{
UARTprintf(" %s \n", ptr[i]);
}
for(i=0;i<4;i++)
{
UARTprintf(" %s \n", ptr1[i]);
}
*/
//////////////////////////////////////////////////
// UARTprintf("This is new! \n", Response);
// RelayStates.Bit.Relay_1=STATEON;
// RelayStates.Bit.Relay_2=STATEON;
// RelayStates.Bit.Relay_3=STATEON;
UpdateSDCardTL.TL_SavePending[1]=0;
UpdateSDCardTL.TL_SavePending[2]=0;
UpdateSDCardTL.TL_SavePending[3]=0;
ParamUpdateFlags.Bit.ParamStartStopFlag=0;
ParamUpdateFlags.Bit.TimerFlagInitDelay=0;
DispControlFuncLatest.Bit.Flag_fault_Upbtn=1;
DispControlFuncLatest.Bit.Flag_TL_Downbtn=1;
TimerFlags.Bit.Flag_InitFault=0;
EVParam.InitBootNotificationDoneflag=0;
FuctionHandle[Id_BootNotification].BIT_FIELD.ProcessingEn=1;
//FuctionHandle[Id_StartTransactionOCP16].BIT_FIELD.ProcessingEn=1;
InitModemParams();
OV_OC_DelayTime = OVOC_DETECT_DELAY;
RelayStates.Bit.BatteryPowerRelay = STATEON;
while(1)
{
if(g_iState == STATE_NEW_CONNECTION) g_iState = STATE_CONNECTED_IDLE;
if((PowerUpflag==1)&&(g_iState==STATE_CONNECTED_IDLE))
{
PowerUpflag = 0;
}
if((PowerUpflag==0)&&(g_iState == STATE_NOT_CONNECTED)&&(EthResetRequired==0))
{
EthResetRequired = 1;
}
if((g_iState == STATE_CONNECTED_IDLE)&&(EthResetRequired==1))
{
WaitEthReconnect = WAIT_ETH_RECONNECT;
//reset here
}
Sec_1Loop();
// HandleConnectionsServerStates();
CalculateEnergy_MeterValues();
ProcessMcuLed();
InputPfcStatus();
RelayControl();
//Response once Data Received from Server(Take a flag which tell to responce)
if(g_ui32Delay<=0)
{
UpdateUART();
g_ui32Delay = SYSTEM_TICK_MS * 50;
}
SendHandshake();
Transmit_DataForCallResult();
TransmitModemDataToServer();
// Transmit_DataForCall();
// SD_Card_CommandHandler_Processor(); //UART Commands for SD Card
//OCPP1.6 related Commands//
GetStartTransactionResponseparam(); //OCPP1.6
///////////
GetAuthResponseParam();
GetBootNotificationResponseparam();
GetUndefinedResponseparam();
GetHeartbeatResponseParam();
GetTransactionEventResponseparam();
GetStopTransactionResponseparam();
GetCancelReservationReqparam();
GetCertificateSignedReqparam();
GetChangeAvailabilityReqparam();
GetClearCacheReqparam();
GetClearChargingProfileReqparam();
GetClearDisplayMessageReqparam();
GetClearVariableMonitoringReqparam();
GetCostUpdatedReqparam();
GetCustomerInformationReqparam();
GetDataTransferReqparam();
GetDeleteCertificateReqparam();
GetBaseReportReqparam();
GetChargingProfilesReqparam();
GetCompositeScheduleReqparam();
GetDisplayMessagesReqparam();
GetInstalledCertificateIdsReqparam();
GetLocalListVersionReqparam();
GetLogReqparam();
GetMonitoringReportReqparam();
GetReportReqparam();
GetTransactionStatusReqparam();
InstallCertificateReqparam();
PublishFirmwareReqparam();
RequestStartTransactionReqparam();
RemoteStartTransactionReqparam();
RequestStopTransactionReqparam();
RemoteStopTransactionReqparam();
ReserveNowReqparam();
ResetReqparam();
SendLocalListReqparam();
SetChargingProfileReqparam();
SetDisplayMessageReqparam();
SetMonitoringBaseReqparam();
SetMonitoringLevelReqparam();
SetNetworkProfileReqparam();
SetVariablesReqparam();
TriggerMessageReqparam();
UnlockConnectorReqparam();
UnpublishFirmwareReqparam();
UpdateFirmwareReqparam();
GetConfigurationReqparam();
FnTx_Authorize();
FnTx_BootNotification();
FnTx_FirmwareStatusNotification();
FnTx_Heartbeat();
FnTx_LogStatusNotification();
FnTx_MeterValues();
FnTx_NotifyChargingLimit();
FnTx_ReservationStatusUpdate();
FnTx_SecurityEventNotification();
FnTx_StatusNotification();
FnTx_TransactionEvent();
FnTx_StartTransaction();
FnTx_StopTransaction();
FnTxC_CancelReservation();
FnTxC_CertificateSigned();
FnTxC_ChangeAvailability();
FnTxC_ClearCache();
FnTxC_ClearChargingProfile();
FnTxC_ClearDisplayMessage();
FnTxC_ClearVariableMonitoring();
FnTxC_CostUpdated();
FnTxC_CustomerInformation();
FnTxC_DataTransfer();
FnTxC_DeleteCertificate();
FnTxC_GetBaseReport();
FnTxC_GetChargingProfiles();
FnTxC_GetCompositeSchedule();
FnTxC_GetDisplayMessages();
FnTxC_GetInstalledCertificateIds();
FnTxC_GetLocalListVersion();
FnTxC_GetLog();
FnTxC_GetMonitoringReport();
FnTxC_GetReport();
FnTxC_GetTransactionStatus();
FnTxC_InstallCertificate();
FnTxC_PublishFirmware();
FnTxC_RequestStartTransaction();
FnTxC_RequestStopTransaction();
FnTxC_RemoteStopTransaction();
FnTxC_ReserveNow();
FnTxC_Reset();
FnTxC_SendLocalList();
FnTxC_SetChargingProfile();
FnTxC_SetDisplayMessage();
FnTxC_SetMonitoringBase();
FnTxC_SetMonitoringLevel();
FnTxC_SetNetworkProfile();
FnTxC_SetVariables();
FnTxC_TriggerMessage();
FnTxC_UnlockConnector();
FnTxC_UnpublishFirmware();
FnTxC_UpdateFirmware();
FnTxC_RemoteStartTransaction();
FnTxC_GetConfiguration();
TransmitPeriodicHeartbeat();
TransmitPeriodicBootNotification();
//Display Hnadling Functions//
UpdateVPDataBufftoEEPandAssignvaluetoVP();
InitializeDisplayParameters();
UpdateStartStopChargingIcon();
UpdateCurrent_Voltage_Power();
UpdateTime();
UpdateNetworkStatus();
//UpdateandCheckOTP();
//UpdateandCheckSettingUserIDPassword();
UpdateCheckIpMode();
updateFaultTable();
UploadFaultTableData();
updateTradeLogsTable();
UploadTLTableData();
StartChargingDisplayUpdate();
StopChargingDisplayUpdate();
StopChargingA();
StopChargingB();
StopChargingC();
StartChargingGunA();
StartChargingGunB();
StartChargingGunC();
UpdateRTCTimetoDisplay();
UpdateRTCTimefromDisplay();
CalculateSessionDurationAllGun();
UpdatePicNumber();
UpdateCostParamtodisplayA();
UpdateCostParamtodisplayB();
UpdateCostParamtodisplayC();
UpdateRealtimeCostGunA();
UpdateRealtimeCostGunB();
UpdateRealtimeCostGunC();
ChargingAnimationPicshow();
GetPFCFaults(); //Uncomment Later
FaultDisplay();
WriteFaultDataToDisplay();
OV_OC_faults(); //Uncomment Later
UpdateFaultToServer();
TxMeterValueA();
TxMeterValueB();
TxMeterValueC();
RealTimeUpdateSDCardFaults();
RealTimeUpdateSDCardTL();
//GSM Modem
ProcessModemATRxbuff();
ProcessModemUartRxPack();
ProcessModemUartRxPack2();
StateMachineModemATCommunication();
ModemResesetOnRetries();
StartModemCommAfterReset();
HanshakeProcess();
TurnModuleOnOff();
ModuleReset();
GetSignalStrengthTx();
ProcessStatusNotificationPeriodic();
if(TimerFlags.Bit.FunctionCodeProcessTimeflag==1)
{
TimerFlags.Bit.FunctionCodeProcessTimeflag=0;
Fc_B_C02_Authorization_StartButton_Con1();
Fc_B_C02_Authorization_StartButton_Con2();
Fc_B_C02_Authorization_StartButton_Con3();
Fc_B_C05_Authorization_CSMS_ConAll();
Fc_B_F03_RemoteStopTransaction_CSMS_ConAll();
StopFaultTxInit();
Fc_B_E06_FaultStop_CSMS_ConAll();
}
HandleMultiStart();
HandleMultiStop();
CheckModemServerComm();
if(g_iState == STATE_NOT_CONNECTED)
{
TCP_ConnectionStatus = e_TCP_Disconnected;
}
else
{
TCP_ConnectionStatus = e_TCP_Connected;
}
}
}
//*****************************************************************************
//Author: Pradeep Kumar
//Date: 06/01/2021 Time: 19:37
//Function void Transmit_Data(void)
//Input Parameters: None
//Description:This Function will be called in while Loop
//This is the main Function to transmit Data to Ethernet
//*****************************************************************************
void Transmit_DataForCallResult(void)
{
if(g_iState==STATE_CONNECTED_IDLE)
{
if(EthResetRequired==1)
{
//EthClientTCPDisconnect();
EthResetRequired=0;
Soft_Reset();
}
}
//if((ProcessTransmit.TransmitFlag[e_IdCallResult]==0)||(ProcessTransmit.TransmitFlag[e_IdCall]==0))return;
//if(ProcessTransmit.Tx_Inprogress[e_IdCallResult]==1)return; //Uncomment Later , This will Block packet if Server Did not Respond//
if(WaitEthReconnect>0)return;
if((WebSocketflags.HanshakeStatus ==1)&&(WebSocketflags.HandshakeInprogress==0))
{
if(g_iState==STATE_CONNECTED_IDLE)
{
if(ProcessTransmit.TransmitFlag[e_IdCallResult]==1)
{
//EthClientReset();
//Return 1 if packet send successfully otherwise return 0
if(WeatherForecast(iWSrcOpenWeatherMap,g_psCityInfo[0].pcName,&g_psCityInfo[0].sReport,WeatherEvent)==0)
{
g_iState=STATE_WAIT_DATA;
}
ProcessTransmit.TransmitFlag[e_IdCallResult]=0;
ProcessTransmit.Tx_Inprogress[e_IdCallResult]=1;
Time_Sec = 10; //10 Sec
}
else if(ProcessTransmit.TransmitFlag[e_IdCall]==1)
{
if(WeatherForecast(iWSrcOpenWeatherMap,g_psCityInfo[0].pcName,&g_psCityInfo[0].sReport,WeatherEvent)==0)
{
g_iState=STATE_CONNECTED_IDLE;
}
ProcessTransmit.TransmitFlag[e_IdCall]=0;
ProcessTransmit.Tx_Inprogress[e_IdCall]=1;
Time_Sec = 10; //10 Sec
}
}
}
else if((WebSocketflags.HanshakeStatus ==0)&&(WebSocketflags.HandshakeInprogress==0))
{
WebSocketflags.FlagProcessHandshake=1;
}
}
void Transmit_DataForCall(void)
{
if( ProcessTransmit.TransmitFlag[e_IdCall]==0)return;
if(ProcessTransmit.Tx_Inprogress[e_IdCall]==1)return; //Uncomment Later , This will Block packet if Server Did not Respond//
if(WaitEthReconnect>0)return;
if((WebSocketflags.HanshakeStatus ==1)&&(WebSocketflags.HandshakeInprogress==0))
{
if(g_iState==STATE_CONNECTED_IDLE)
{
//EthClientReset();
//Return 1 if packet send successfully otherwise return 0
if(WeatherCurrent(iWSrcOpenWeatherMap,g_psCityInfo[0].pcName,&g_psCityInfo[0].sReport,WeatherEvent)==0)
{
g_iState=STATE_CONNECTED_IDLE;
restore();
// g_sEnet.eState = 8;
}
ProcessTransmit.TransmitFlag[e_IdCall]=0;
ProcessTransmit.Tx_Inprogress[e_IdCall]=1;
Time_Sec = 10; //10 Sec
}
}
}
//*****************************************************************************
//Author: Pradeep Kumar
//Date: 06/01/2021 Time: 19:37
//Function void HandleConnectionsServerStates(void)
//Input Parameters: None
//Description:This Function will be called in while Loop
//This Function Handles and gives Connection Status
//*****************************************************************************
void HandleConnectionsServerStates(void)
{
if(g_iState == STATE_WAIT_DATA)
{
if(Time_Sec == 0)
{
//
// Close out the current connection.
//
// EthClientTCPDisconnect();
//
// If DHCP has already been started, we need to clear the IPs and
// switch to static. This forces the LWIP to get new IP address
// and retry the DHCP connection.
//
//lwIPNetworkConfigChange(0, 0, 0, IPADDR_USE_STATIC);
//
// Restart the DHCP connection.
//
// lwIPNetworkConfigChange(0, 0, 0, IPADDR_USE_DHCP);
//EthClientReset();
//EthClientInit(EnetEvents);
g_iState = STATE_NOT_CONNECTED;
TCP_ConnectionStatus = e_TCP_NotResponding;
Time_Sec = 10; //Retry Delay
}
return;
}
if(g_iState == STATE_NOT_CONNECTED)
{
if(TCP_ConnectionStatus==e_TCP_NotResponding)
{
if(Time_Sec == 0)
{
// WeatherForecast1(iWSrcOpenWeatherMap,
// g_psCityInfo[0].pcName,
// &g_psCityInfo[0].sReport,
// WeatherEvent);
// This Condition Should not Occurr//
//
// Restart the DHCP connection.
//
//lwIPNetworkConfigChange(0, 0, 0, IPADDR_USE_DHCP);
//EthClientReset();
// EthClientInit(EnetEvents);
//
g_iState=STATE_NOT_CONNECTED;
ProcessTransmit.TransmitFlag[e_IdCallResult]=0;
ProcessTransmit.TransmitFlag[e_IdCall]=0;
Time_Sec = 10; //10 Sec
TCP_ConnectionStatus = e_TCP_Disconnected;
// g_iState= STATE_CONNECTED_IDLE;
}
}
else
{
TCP_ConnectionStatus = e_TCP_Disconnected;
}
}
else
{
TCP_ConnectionStatus = e_TCP_Connected;
}
}
void ProcessMcuLed(void)
{
if(TimerFlags.Bit.MCU_Led_Flag_1sec==0)return;
TimerFlags.Bit.MCU_Led_Flag_1sec=0;
if(ROM_GPIOPinRead(GPIO_PORTK_BASE ,MCU_LED )==0) ROM_GPIOPinWrite(GPIO_PORTK_BASE, MCU_LED, MCU_LED);
else ROM_GPIOPinWrite(GPIO_PORTK_BASE, MCU_LED, 0);
ProcessChargingTimeout();
// IndicationPower();
ChargingLEDAIndication();
ChargingLEDBIndication();
ChargingLEDCIndication();
FaultIndication();
}
void SendHandshake(void)
{
//if(ProcessTransmit.Tx_Inprogress[e_IdCallResult]==0)return;
if(WebSocketflags.FlagProcessHandshake==0)return;
if(WaitEthReconnect>0)return;
if(g_iState==STATE_CONNECTED_IDLE)
{
WebSocketflags.FlagProcessHandshake=0;
WebSocketflags.HandshakeInprogress=1;
//EthClientReset();
//Return 1 if packet send successfully otherwise return 0
if(WeatherForecast(iWSrcOpenWeatherMap,g_psCityInfo[0].pcName,&g_psCityInfo[0].sReport,WeatherEvent)==0)
{
g_iState=STATE_WAIT_DATA;
}
Time_Sec = 10; //10 Sec
}
}
当我尝试使用 enet_weather 示例时、也会发生同样的情况。