For mbed OS-5 version for WIZnet Ethernet Interface, this is Library using Hardware TCP/IP chip, W5500 and TCP/IP Offload Engine, W7500.
Warning
- If you want to use existing codes, you need to change the class used as EthernetInterface to WIZnetInterface.
This is WIZnet Ethernet Interface using Hardware TCP/IP chip, W5500 and TCP/IP Offload Engine, W7500.
- WIZwiki_W7500 : /platforms/WIZwiki-W7500/
- WIZwiki_W7500P : /platforms/WIZwiki-W7500P/
- WIZwiki_W7500ECO : /platforms/WIZwiki-W7500ECO/
- W5500 Ethernet Shield : /components/W5500-Ethernet-Kit-for-IoT/
This library is an Ethernet Interface library port-based on [EthernetInterface](https://developer.mbed.org/users/mbed_official/code/EthernetInterface/docs/tip/).
For more detail, visit http://embeddist.blogspot.kr/2015/06/wiznetinterface-for-armmbed.html
Revision 0:d4c8fe4d9b29, committed 2017-09-04
- Comitter:
- justinkim
- Date:
- Mon Sep 04 00:23:04 2017 +0000
- Commit message:
- mbed OS 5 version migration...
Changed in this revision
diff -r 000000000000 -r d4c8fe4d9b29 Socket/DHCPClient.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/DHCPClient.cpp Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,211 @@ +// DHCPClient.cpp 2013/4/10 +#include "mbed.h" +#include "mbed_debug.h" +#include "WIZnet_UDPSocket.h" +#include "DHCPClient.h" + +#define DBG_DHCP 0 + +#if DBG_DHCP +#define DBG(...) do{debug("[%s:%d]", __PRETTY_FUNCTION__,__LINE__);debug(__VA_ARGS__);} while(0); +#define DBG_HEX(A,B) do{debug("[%s:%d]\r\n", __PRETTY_FUNCTION__,__LINE__);debug_hex(A,B);} while(0); +#else +#define DBG(...) while(0); +#define DBG_HEX(A,B) while(0); +#endif + +int DHCPClient::discover() +{ + m_pos = 0; + const uint8_t header[] = {0x01,0x01,0x06,0x00}; + add_buf((uint8_t*)header, sizeof(header)); + uint32_t x = time(NULL) + rand(); + xid[0] = x>>24; xid[1] = x>>16; xid[2] = x>>8; xid[3] = x; + add_buf(xid, 4); + fill_buf(20, 0x00); + add_buf(chaddr, 6); + fill_buf(10+192, 0x00); + const uint8_t options[] = {0x63,0x82,0x53,0x63, // magic cookie + 53,1,DHCPDISCOVER, // DHCP option 53: DHCP Discover + 55,4,1,3,15,6, + 255}; + add_buf((uint8_t*)options, sizeof(options)); + return m_pos; +} + +int DHCPClient::request() +{ + m_pos = 0; + const uint8_t header[] = {0x01,0x01,0x06,0x00}; + add_buf((uint8_t*)header, sizeof(header)); + add_buf(xid, 4); + fill_buf(12, 0x00); + add_buf(siaddr, 4); + fill_buf(4, 0x00); // giaddr + add_buf(chaddr, 6); + fill_buf(10+192, 0x00); + const uint8_t options[] = {0x63,0x82,0x53,0x63, // magic cookie + 53,1,DHCPREQUEST, // DHCP option 53: DHCP Request + 55,4,1,3,15,6, // DHCP option 55: + }; + add_buf((uint8_t*)options, sizeof(options)); + add_option(50, yiaddr, 4); + add_option(54, siaddr, 4); + add_option(255); + return m_pos; +} + +int DHCPClient::offer(uint8_t buf[], int size) { + memcpy(yiaddr, buf+DHCP_OFFSET_YIADDR, 4); + memcpy(siaddr, buf+DHCP_OFFSET_SIADDR, 4); + uint8_t *p; + int msg_type = -1; + p = buf + DHCP_OFFSET_OPTIONS; + while(*p != 255 && p < (buf+size)) { + uint8_t code = *p++; + if (code == 0) { // Pad Option + continue; + } + int len = *p++; + + DBG("DHCP option: %d\r\n", code); + DBG_HEX(p, len); + + switch(code) { + case 53: + msg_type = *p; + break; + case 1: + memcpy(netmask, p, 4); // Subnet mask address + break; + case 3: + memcpy(gateway, p, 4); // Gateway IP address + break; + case 6: // DNS server + memcpy(dnsaddr, p, 4); + break; + case 51: // IP lease time + break; + case 54: // DHCP server + memcpy(siaddr, p, 4); + break; + } + p += len; + } + return msg_type; +} + +bool DHCPClient::verify(uint8_t buf[], int len) { + if (len < DHCP_OFFSET_OPTIONS) { + return false; + } + if (buf[DHCP_OFFSET_OP] != 0x02) { + return false; + } + if (memcmp(buf+DHCP_OFFSET_XID, xid, 4) != 0) { + return false; + } + return true; +} + +void DHCPClient::callback() +{ + Endpoint host; + int recv_len = m_udp->receiveFrom(host, (char*)m_buf, sizeof(m_buf)); + if (recv_len < 0) { + return; + } + if (!verify(m_buf, recv_len)) { + return; + } + int r = offer(m_buf, recv_len); + if (r == DHCPOFFER) { + int send_size = request(); + m_udp->sendTo(m_server, (char*)m_buf, send_size); + } else if (r == DHCPACK) { + exit_flag = true; + } +} + +void DHCPClient::add_buf(uint8_t c) +{ + m_buf[m_pos++] = c; +} + +void DHCPClient::add_buf(uint8_t* buf, int len) +{ + for(int i = 0; i < len; i++) { + add_buf(buf[i]); + } +} + +void DHCPClient::fill_buf(int len, uint8_t data) +{ + while(len-- > 0) { + add_buf(data); + } +} + +void DHCPClient::add_option(uint8_t code, uint8_t* buf, int len) +{ + add_buf(code); + if (len > 0) { + add_buf((uint8_t)len); + add_buf(buf, len); + } +} + +int DHCPClient::setup(int timeout_ms) +{ + eth = WIZnet_Chip::getInstance(); + if (eth == NULL) { + return -1; + } + eth->reg_rd_mac(SHAR, chaddr); + int interval_ms = 5*1000; // 5000msec + if (timeout_ms < interval_ms) { + interval_ms = timeout_ms; + } + m_udp = new WIZnet_UDPSocket; + m_udp->init(); + m_udp->set_blocking(false); + eth->reg_wr<uint32_t>(SIPR, 0x00000000); // local ip "0.0.0.0" + m_udp->bind(68); // local port + m_server.set_address("255.255.255.255", 67); // DHCP broadcast + exit_flag = false; + int err = 0; + int seq = 0; + int send_size; + while(!exit_flag) { + switch(seq) { + case 0: + m_retry = 0; + seq++; + break; + case 1: + send_size = discover(); + m_udp->sendTo(m_server, (char*)m_buf, send_size); + m_interval.reset(); + m_interval.start(); + seq++; + break; + case 2: + callback(); + if (m_interval.read_ms() > interval_ms) { + DBG("m_retry: %d\n", m_retry); + if (++m_retry >= (timeout_ms/interval_ms)) { + err = -1; + exit_flag = true; + } + seq--; + } + break; + } + } + DBG("m_retry: %d, m_interval: %d\n", m_retry, m_interval.read_ms()); + delete m_udp; + return err; +} + +DHCPClient::DHCPClient() { +}
diff -r 000000000000 -r d4c8fe4d9b29 Socket/DHCPClient.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/DHCPClient.h Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,54 @@ +// DHCPClient.h 2013/4/10 +#ifndef DHCPCLIENT_H +#define DHCPCLIENT_H +#include "eth_arch.h" +#include "WIZnet_UDPSocket.h" + +#define DHCP_OFFSET_OP 0 +#define DHCP_OFFSET_XID 4 +#define DHCP_OFFSET_YIADDR 16 +#define DHCP_OFFSET_SIADDR 20 +#define DHCP_OFFSET_OPTIONS 240 +#define DHCP_MAX_PACKET_SIZE 600 + +// DHCP Message Type +#define DHCPDISCOVER 1 +#define DHCPOFFER 2 +#define DHCPREQUEST 3 +#define DHCPDECLINE 4 +#define DHCPACK 5 +#define DHCPNAK 6 +#define DHCPRELEASE 7 +#define DHCPINFORM 8 + +class DHCPClient { +public: + DHCPClient(); + int setup(int timeout_ms = 15*1000); + uint8_t chaddr[6]; // MAC + uint8_t yiaddr[4]; // IP + uint8_t dnsaddr[4]; // DNS + uint8_t gateway[4]; + uint8_t netmask[4]; + uint8_t siaddr[4]; +private: + int discover(); + int request(); + int offer(uint8_t buf[], int size); + void add_buf(uint8_t* buf, int len); + void fill_buf(int len, uint8_t data = 0x00); + void add_buf(uint8_t c); + void add_option(uint8_t code, uint8_t* buf = NULL, int len = 0); + bool verify(uint8_t buf[], int len); + void callback(); + WIZnet_UDPSocket* m_udp; + Endpoint m_server; + uint8_t xid[4]; + bool exit_flag; + Timer m_interval; + int m_retry; + uint8_t m_buf[DHCP_MAX_PACKET_SIZE]; + int m_pos; + WIZnet_Chip* eth; +}; +#endif //DHCPCLIENT_H
diff -r 000000000000 -r d4c8fe4d9b29 Socket/DNSClient.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/DNSClient.cpp Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,173 @@ +// DNSClient.cpp 2013/8/27 +#include "mbed.h" +#include "mbed_debug.h" +#include "DNSClient.h" +#include "WIZnet_UDPSocket.h" +#include "dnsname.h" +#include "eth_arch.h" + +#define DBG_DNS 0 + +#if DBG_DNS +#define DBG2(...) do{debug("[DNS]%p %d %s ", this,__LINE__,__PRETTY_FUNCTION__); debug(__VA_ARGS__); } while(0); +#else +#define DBG2(...) while(0); +#endif + +DNSClient::DNSClient(const char* hostname) : m_state(MYNETDNS_START), m_udp(NULL) { + m_hostname = hostname; +} + +DNSClient::DNSClient(Endpoint* pHost) : m_state(MYNETDNS_START), m_udp(NULL) { +} + +DNSClient::~DNSClient() { + if (m_udp) { + delete m_udp; + } +} + +void DNSClient::callback() +{ + uint8_t buf[512]; + Endpoint host; + int len = m_udp->receiveFrom(host, (char*)buf, sizeof(buf)); + if (len < 0) { + return; + } + if (memcmp(buf+0, m_id, 2) != 0) { //verify + return; + } + int rcode = response(buf, len); + if (rcode == 0) { + m_state = MYNETDNS_OK; + } else { + m_state = MYNETDNS_NOTFOUND; + } +} + +int DNSClient::response(uint8_t buf[], int size) { + int rcode = buf[3] & 0x0f; + if (rcode != 0) { + return rcode; + } + int qdcount = buf[4]<<8|buf[5]; + int ancount = buf[6]<<8|buf[7]; + int pos = 12; + while(qdcount-- > 0) { + dnsname qname(buf); + pos = qname.decode(pos); // qname + pos += 4; // qtype qclass + } + while(ancount-- > 0) { + dnsname name(buf); + pos = name.decode(pos); // name + int type = buf[pos]<<8|buf[pos+1]; + pos += 8; // type class TTL + int rdlength = buf[pos]<<8|buf[pos+1]; pos += 2; + int rdata_pos = pos; + pos += rdlength; + if (type == 1) { // A record + ip = (buf[rdata_pos]<<24) | (buf[rdata_pos+1]<<16) | (buf[rdata_pos+2]<<8) | buf[rdata_pos+3]; + } +#if DBG_DNS + printf("%s", name.str.c_str()); + if (type == 1) { + printf(" A %d.%d.%d.%d\n", + buf[rdata_pos],buf[rdata_pos+1],buf[rdata_pos+2],buf[rdata_pos+3]); + } else if (type == 5) { + dnsname rdname(buf); + rdname.decode(rdata_pos); + printf(" CNAME %s\n", rdname.str.c_str()); + } else { + printf(" TYPE:%d", type); + printfBytes(" RDATA:", &buf[rdata_pos], rdlength); + } +#endif + } + return rcode; +} + +int DNSClient::query(uint8_t buf[], int size, const char* hostname) { + const uint8_t header[] = { + 0x00,0x00,0x01,0x00, // id=0x0000 QR=0 rd=1 opcode=0 rcode=0 + 0x00,0x01,0x00,0x00, // qdcount=1 ancount=0 + 0x00,0x00,0x00,0x00};// nscount=0 arcount=0 + const uint8_t tail[] = {0x00,0x01,0x00,0x01}; // qtype=A qclass=IN + memcpy(buf, header, sizeof(header)); + int t = rand(); + m_id[0] = t>>8; + m_id[1] = t; + memcpy(buf, m_id, 2); + dnsname qname(buf); + int pos = qname.encode(sizeof(header), (char*)hostname); + memcpy(buf+pos, tail, sizeof(tail)); + pos += sizeof(tail); + return pos; +} + +void DNSClient::resolve(const char* hostname) { + if (m_udp == NULL) { + m_udp = new WIZnet_UDPSocket; + } + m_udp->init(); + m_udp->set_blocking(false); + Endpoint server; + server.set_address("8.8.8.8", 53); // DNS + m_udp->bind(rand()&0x7fff); + uint8_t buf[256]; + int size = query(buf, sizeof(buf), hostname); +#if DBG_DNS + printf("hostname:[%s]\n", hostname); + printHex(buf, size); +#endif + m_udp->sendTo(server, (char*)buf, size); + m_interval.reset(); + m_interval.start(); +} + +void DNSClient::poll() { +#if DBG_DNS + printf("%p m_state: %d, m_udp: %p\n", this, m_state, m_udp); + wait_ms(400); +#endif + switch(m_state) { + case MYNETDNS_START: + m_retry = 0; + resolve(m_hostname); + m_state = MYNETDNS_PROCESSING; + break; + case MYNETDNS_PROCESSING: + break; + case MYNETDNS_NOTFOUND: + break; + case MYNETDNS_ERROR: + break; + case MYNETDNS_OK: + DBG2("m_retry=%d, m_interval=%d\n", m_retry, m_interval.read_ms()); + break; + } + if (m_interval.read_ms() > 1000) { + m_interval.stop(); + DBG2("timeout m_retry=%d\n", m_retry); + if (++m_retry >= 2) { + m_state = MYNETDNS_ERROR; + } else { + resolve(m_hostname); + m_state = MYNETDNS_PROCESSING; + } + } +} + +bool DNSClient::lookup(const char* hostname) { + m_hostname = hostname; + m_state = MYNETDNS_START; + while(1) { + poll(); + callback(); + if (m_state != MYNETDNS_PROCESSING) { + break; + } + } + return m_state == MYNETDNS_OK; +}
diff -r 000000000000 -r d4c8fe4d9b29 Socket/DNSClient.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/DNSClient.h Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,34 @@ +// DNSClient.h 2013/4/5 +#pragma once + +#include "WIZnet_UDPSocket.h" + +class DNSClient { +public: + DNSClient(const char* hostname = NULL); + DNSClient(Endpoint* pHost); + virtual ~DNSClient(); + bool lookup(const char* hostname = NULL); + uint32_t ip; +protected: + void poll(); + void callback(); + int response(uint8_t buf[], int size); + int query(uint8_t buf[], int size, const char* hostname); + void resolve(const char* hostname); + uint8_t m_id[2]; + Timer m_interval; + int m_retry; + const char* m_hostname; +private: + enum MyNetDnsState + { + MYNETDNS_START, + MYNETDNS_PROCESSING, //Req has not completed + MYNETDNS_NOTFOUND, + MYNETDNS_ERROR, + MYNETDNS_OK + }; + MyNetDnsState m_state; + WIZnet_UDPSocket *m_udp; +};
diff -r 000000000000 -r d4c8fe4d9b29 Socket/Endpoint.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/Endpoint.cpp Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,60 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#include "WIZnet_Socket.h" +#include "Endpoint.h" + +Endpoint::Endpoint() +{ + //printf("reset_address\r\n"); + reset_address(); +} +Endpoint::~Endpoint() {} + +void Endpoint::reset_address(void) +{ + _ipAddress[0] = '\0'; + _port = 0; +} + +int Endpoint::set_address(const char* host, const int port) +{ + //Resolve DNS address or populate hard-coded IP address + WIZnet_Chip* eth = WIZnet_Chip::getInstance(); + if (eth == NULL) { + error("Endpoint constructor error: no WIZnet chip instance available!\r\n"); + return -1; + } + uint32_t addr; + if (!eth->gethostbyname(host, &addr)) { + error("DNS error : Cannot get url from DNS server\r\n"); + return -1; + } + snprintf(_ipAddress, sizeof(_ipAddress), "%d.%d.%d.%d", (addr>>24)&0xff, (addr>>16)&0xff, (addr>>8)&0xff, addr&0xff); + _port = port; + return 0; +} + +char* Endpoint::get_address() +{ + return _ipAddress; +} + +int Endpoint::get_port() +{ + return _port; +}
diff -r 000000000000 -r d4c8fe4d9b29 Socket/Endpoint.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/Endpoint.h Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,64 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#ifndef ENDPOINT_H +#define ENDPOINT_H + +#include "eth_arch.h" + +class WIZnet_UDPSocket; + +/** +IP Endpoint (address, port) +*/ +class Endpoint { + friend class WIZnet_UDPSocket; + +public: + /** IP Endpoint (address, port) + */ + Endpoint(void); + + ~Endpoint(void); + + /** Reset the address of this endpoint + */ + void reset_address(void); + + /** Set the address of this endpoint + \param host The endpoint address (it can either be an IP Address or a hostname that will be resolved with DNS). + \param port The endpoint port + \return 0 on success, -1 on failure (when an hostname cannot be resolved by DNS). + */ + int set_address(const char* host, const int port); + + /** Get the IP address of this endpoint + \return The IP address of this endpoint. + */ + char* get_address(void); + + /** Get the port of this endpoint + \return The port of this endpoint + */ + int get_port(void); + +protected: + char _ipAddress[16]; + int _port; +}; + +#endif
diff -r 000000000000 -r d4c8fe4d9b29 Socket/TCPSocketConnection.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/TCPSocketConnection.cpp Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,146 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "TCPSocketConnection.h" +#include <cstring> + +using std::memset; +using std::memcpy; + +// not a big code. +// refer from EthernetInterface by mbed official driver +TCPSocketConnection::TCPSocketConnection() : + _is_connected(false) +{ +} + +int TCPSocketConnection::connect(const char* host, const int port) +{ + if (_sock_fd < 0) { + _sock_fd = eth->new_socket(); + if (_sock_fd < 0) { + return -1; + } + } + if (set_address(host, port) != 0) { + return -1; + } + if (!eth->connect(_sock_fd, get_address(), port)) { + return -1; + } + set_blocking(false); + // add code refer from EthernetInterface. + _is_connected = true; + + return 0; +} + +bool TCPSocketConnection::is_connected(void) +{ + // force update recent state. + _is_connected = eth->is_connected(_sock_fd); + return _is_connected; +} + +int TCPSocketConnection::send(char* data, int length) +{ + if((_sock_fd<0) || !(eth->is_connected(_sock_fd))) + return -1; + + int size = eth->wait_writeable(_sock_fd, _blocking ? -1 : _timeout); + if (size < 0) + return -1; + + if (size > length) + size = length; + + return eth->send(_sock_fd, data, size); +} + +// -1 if unsuccessful, else number of bytes written +int TCPSocketConnection::send_all(char* data, int length) +{ + int writtenLen = 0; + + if(_sock_fd<0) + return -1; + + while (writtenLen < length) { + + if(!(eth->is_connected(_sock_fd))) + return -1; + + int size = eth->wait_writeable(_sock_fd, _blocking ? -1 : _timeout); + if (size < 0) { + return -1; + } + if (size > (length-writtenLen)) { + size = (length-writtenLen); + } + int ret = eth->send(_sock_fd, data + writtenLen, size); + if (ret < 0) { + return -1; + } + writtenLen += ret; + } + return writtenLen; +} + +// -1 if unsuccessful, else number of bytes received +int TCPSocketConnection::receive(char* data, int length) +{ + if((_sock_fd<0) || !(eth->is_connected(_sock_fd))) + return -1; + + int size = eth->wait_readable(_sock_fd, _blocking ? -1 : _timeout); + if (size < 0) { + return -1; + } + if (size > length) { + size = length; + } + return eth->recv(_sock_fd, data, size); +} + +// -1 if unsuccessful, else number of bytes received +int TCPSocketConnection::receive_all(char* data, int length) +{ + if(_sock_fd<0) + return -1; + + int readLen = 0; + while (readLen < length) { + + if(!(eth->is_connected(_sock_fd))) + return -1; + + int size = eth->wait_readable(_sock_fd, _blocking ? -1 :_timeout); + if (size <= 0) { + break; + } + if (size > (length - readLen)) { + size = length - readLen; + } + int ret = eth->recv(_sock_fd, data + readLen, size); + if (ret < 0) { + return -1; + } + readLen += ret; + } + return readLen; +}
diff -r 000000000000 -r d4c8fe4d9b29 Socket/TCPSocketConnection.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/TCPSocketConnection.h Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,80 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef TCPSOCKETCONNECTION_H +#define TCPSOCKETCONNECTION_H + +#include "WIZnet_Socket.h" +#include "Endpoint.h" + +/** +TCP socket connection +*/ +class TCPSocketConnection: public WIZnet_Socket, public Endpoint { + friend class TCPSocketServer; + +public: + /** TCP socket connection + */ + TCPSocketConnection(); + + /** Connects this TCP socket to the server + \param host The host to connect to. It can either be an IP Address or a hostname that will be resolved with DNS. + \param port The host's port to connect to. + \return 0 on success, -1 on failure. + */ + int connect(const char* host, const int port); + + /** Check if the socket is connected + \return true if connected, false otherwise. + */ + bool is_connected(void); + + /** Send data to the remote host. + \param data The buffer to send to the host. + \param length The length of the buffer to send. + \return the number of written bytes on success (>=0) or -1 on failure + */ + int send(char* data, int length); + + /** Send all the data to the remote host. + \param data The buffer to send to the host. + \param length The length of the buffer to send. + \return the number of written bytes on success (>=0) or -1 on failure + */ + int send_all(char* data, int length); + + /** Receive data from the remote host. + \param data The buffer in which to store the data received from the host. + \param length The maximum length of the buffer. + \return the number of received bytes on success (>=0) or -1 on failure + */ + int receive(char* data, int length); + + /** Receive all the data from the remote host. + \param data The buffer in which to store the data received from the host. + \param length The maximum length of the buffer. + \return the number of received bytes on success (>=0) or -1 on failure + */ + int receive_all(char* data, int length); + +private: + bool _is_connected; +}; + +#endif
diff -r 000000000000 -r d4c8fe4d9b29 Socket/TCPSocketServer.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/TCPSocketServer.cpp Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,98 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "TCPSocketServer.h" + +TCPSocketServer::TCPSocketServer() {} + +// Server initialization +int TCPSocketServer::bind(int port) +{ + // set the listen_port for next connection. + listen_port = port; + if (_sock_fd < 0) { + _sock_fd = eth->new_socket(); + if (_sock_fd < 0) { + return -1; + } + } + // set TCP protocol + eth->setProtocol(_sock_fd, WIZnet_Chip::TCP); + // set local port + eth->sreg<uint16_t>(_sock_fd, Sn_PORT, port); + // connect the network + eth->scmd(_sock_fd, WIZnet_Chip::OPEN); + return 0; +} + +int TCPSocketServer::listen(int backlog) +{ + if (_sock_fd < 0) { + return -1; + } + if (backlog != 1) { + return -1; + } + eth->scmd(_sock_fd, WIZnet_Chip::LISTEN); + return 0; +} + + +int TCPSocketServer::accept(TCPSocketConnection& connection) +{ + if (_sock_fd < 0) { + return -1; + } + Timer t; + t.reset(); + t.start(); + while(1) { + if (t.read_ms() > _timeout && _blocking == false) { + return -1; + } + if (eth->sreg<uint8_t>(_sock_fd, Sn_SR) == WIZnet_Chip::SOCK_ESTABLISHED) { + break; + } + } + uint32_t ip = eth->sreg<uint32_t>(_sock_fd, Sn_DIPR); + char host[16]; + snprintf(host, sizeof(host), "%d.%d.%d.%d", (ip>>24)&0xff, (ip>>16)&0xff, (ip>>8)&0xff, ip&0xff); + uint16_t port = eth->sreg<uint16_t>(_sock_fd, Sn_DPORT); + + // change this server socket to connection socket. + connection._sock_fd = _sock_fd; + connection._is_connected = true; + connection.set_address(host, port); + + // and then, for the next connection, server socket should be assigned new one. + _sock_fd = -1; // want to assign new available _sock_fd. + if(bind(listen_port) < 0) { + // modified by Patrick Pollet + error("No more socket for listening, bind error"); + return -1; + } else { + //return -1; + if(listen(1) < 0) { + // modified by Patrick Pollet + error("No more socket for listening, listen error"); + return -1; + } + } + + return 0; +}
diff -r 000000000000 -r d4c8fe4d9b29 Socket/TCPSocketServer.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/TCPSocketServer.h Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,57 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#ifndef TCPSOCKETSERVER_H +#define TCPSOCKETSERVER_H + +#include "WIZnet_Socket.h" +#include "TCPSocketConnection.h" + +/** TCP Server. + */ +class TCPSocketServer : public WIZnet_Socket +{ +public: + /** Instantiate a TCP Server. + */ + TCPSocketServer(); + + /** Bind a socket to a specific port. + \param port The port to listen for incoming connections on. + \return 0 on success, -1 on failure. + */ + int bind(int port); + + /** Start listening for incoming connections. + \param backlog number of pending connections that can be queued up at any + one time [Default: 1]. + \return 0 on success, -1 on failure. + */ + int listen(int backlog=1); + + /** Accept a new connection. + \param connection A TCPSocketConnection instance that will handle the incoming connection. + \return 0 on success, -1 on failure. + */ + int accept(TCPSocketConnection& connection); + +private : + int listen_port; +}; + +#endif +
diff -r 000000000000 -r d4c8fe4d9b29 Socket/WIZnet_Socket.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/WIZnet_Socket.cpp Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,48 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "WIZnet_Socket.h" + +WIZnet_Socket::WIZnet_Socket() : _sock_fd(-1),_blocking(true), _timeout(1500) +{ + eth = WIZnet_Chip::getInstance(); + if (eth == NULL) { + error("Socket constructor error: no W7500 instance available!\r\n"); + } +} + +void WIZnet_Socket::set_blocking(bool blocking, unsigned int timeout) +{ + _blocking = blocking; + _timeout = timeout; +} + +int WIZnet_Socket::close() +{ + // add this code refer from EthernetInterface. + // update by Patrick Pollet + int res; + res = eth->close(_sock_fd); + _sock_fd = -1; + return (res)? 0: -1; +} + +WIZnet_Socket::~WIZnet_Socket() +{ + close(); //Don't want to leak +}
diff -r 000000000000 -r d4c8fe4d9b29 Socket/WIZnet_Socket.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/WIZnet_Socket.h Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,60 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#ifndef WIZnet_SOCKET_H_ +#define WIZnet_SOCKET_H_ + +#include "eth_arch.h" + +#define htons(x) __REV16(x) +#define ntohs(x) __REV16(x) +#define htonl(x) __REV(x) +#define ntohl(x) __REV(x) + +/** Socket file descriptor and select wrapper + */ +class WIZnet_Socket { +public: + /** Socket + */ + WIZnet_Socket(); + + /** Set blocking or non-blocking mode of the socket and a timeout on + blocking socket operations + \param blocking true for blocking mode, false for non-blocking mode. + \param timeout timeout in ms [Default: (1500)ms]. + */ + void set_blocking(bool blocking, unsigned int timeout=1500); + + /** Close the socket file descriptor + */ + int close(); + + ~WIZnet_Socket(); + +protected: + int _sock_fd; + bool _blocking; + int _timeout; + + WIZnet_Chip* eth; +}; + + +#endif /* SOCKET_H_ */ + +
diff -r 000000000000 -r d4c8fe4d9b29 Socket/WIZnet_UDPSocket.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/WIZnet_UDPSocket.cpp Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,110 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "WIZnet_UDPSocket.h" + +static int udp_local_port; + +WIZnet_UDPSocket::WIZnet_UDPSocket() +{ +} +// After init function, bind() should be called. +int WIZnet_UDPSocket::init(void) +{ + if (_sock_fd < 0) { + _sock_fd = eth->new_socket(); + } + if (eth->setProtocol(_sock_fd, WIZnet_Chip::UDP) == false) return -1; + return 0; +} + +// Server initialization +int WIZnet_UDPSocket::bind(int port) +{ + if (_sock_fd < 0) { + _sock_fd = eth->new_socket(); + if (_sock_fd < 0) { + return -1; + } + } + // set local port + if (port != 0) { + eth->sreg<uint16_t>(_sock_fd, Sn_PORT, port); + } else { + udp_local_port++; + eth->sreg<uint16_t>(_sock_fd, Sn_PORT, udp_local_port); + } + // set udp protocol + eth->setProtocol(_sock_fd, WIZnet_Chip::UDP); + eth->scmd(_sock_fd, WIZnet_Chip::OPEN); + return 0; +} + +// -1 if unsuccessful, else number of bytes written +int WIZnet_UDPSocket::sendTo(Endpoint &remote, char *packet, int length) +{ + int size = eth->wait_writeable(_sock_fd, _blocking ? -1 : _timeout, length-1); + if (size < 0) { + return -1; + } + confEndpoint(remote); + int ret = eth->send(_sock_fd, packet, length); + return ret; +} + +// -1 if unsuccessful, else number of bytes received +int WIZnet_UDPSocket::receiveFrom(Endpoint &remote, char *buffer, int length) +{ + uint8_t info[8]; + int size = eth->wait_readable(_sock_fd, _blocking ? -1 : _timeout, sizeof(info)); + if (size < 0) { + return -1; + } + eth->recv(_sock_fd, (char*)info, sizeof(info)); + readEndpoint(remote, info); + int udp_size = info[6]<<8|info[7]; + //TEST_ASSERT(udp_size <= (size-sizeof(info))); + if (udp_size > (size-sizeof(info))) { + return -1; + } + + /* Perform Length check here to prevent buffer overrun */ + /* fixed by Sean Newton (https://developer.mbed.org/users/SeanNewton/) */ + if (udp_size > length) { + //printf("udp_size: %d\n",udp_size); + return -1; + } + return eth->recv(_sock_fd, buffer, udp_size); +} + +void WIZnet_UDPSocket::confEndpoint(Endpoint & ep) +{ + char * host = ep.get_address(); + // set remote host + eth->sreg_ip(_sock_fd, Sn_DIPR, host); + // set remote port + eth->sreg<uint16_t>(_sock_fd, Sn_DPORT, ep.get_port()); +} + +void WIZnet_UDPSocket::readEndpoint(Endpoint & ep, uint8_t info[]) +{ + char addr[17]; + snprintf(addr, sizeof(addr), "%d.%d.%d.%d", info[0], info[1], info[2], info[3]); + uint16_t port = info[4]<<8|info[5]; + ep.set_address(addr, port); +}
diff -r 000000000000 -r d4c8fe4d9b29 Socket/WIZnet_UDPSocket.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/WIZnet_UDPSocket.h Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,68 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef WIZnet_UDPSOCKET_H +#define WIZnet_UDPSOCKET_H + +#include "Endpoint.h" +#include "WIZnet_Socket.h" + +/** +UDP Socket +*/ +class WIZnet_UDPSocket: public WIZnet_Socket { + +public: + /** Instantiate an UDP Socket. + */ + WIZnet_UDPSocket(); + + /** Init the UDP Client Socket without binding it to any specific port + \return 0 on success, -1 on failure. + */ + int init(void); + + /** Bind a UDP Server Socket to a specific port + \param port The port to listen for incoming connections on + \return 0 on success, -1 on failure. + */ + int bind(int port = -1); + + /** Send a packet to a remote endpoint + \param remote The remote endpoint + \param packet The packet to be sent + \param length The length of the packet to be sent + \return the number of written bytes on success (>=0) or -1 on failure + */ + int sendTo(Endpoint &remote, char *packet, int length); + + /** Receive a packet from a remote endpoint + \param remote The remote endpoint + \param buffer The buffer for storing the incoming packet data. If a packet + is too long to fit in the supplied buffer, excess bytes are discarded + \param length The length of the buffer + \return the number of received bytes on success (>=0) or -1 on failure + */ + int receiveFrom(Endpoint &remote, char *buffer, int length); + +private: + void confEndpoint(Endpoint & ep); + void readEndpoint(Endpoint & ep, uint8_t info[]); +}; + +#endif
diff -r 000000000000 -r d4c8fe4d9b29 Socket/dnsname.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/dnsname.h Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,51 @@ +// dnsname.h 2013/8/27 +#pragma once +//#include <string> +#include "pico_string.h" +class dnsname { +public: + uint8_t *buf; + pico_string str; + dnsname(uint8_t *s) { + buf = s; + } + int decode(int pos) { + while(1) { + int len = buf[pos++]; + if (len == 0x00) { + break; + } + if ((len&0xc0) == 0xc0) { //compress + int offset = (len&0x3f)<<8|buf[pos]; + decode(offset); + return pos+1; + } + if (!str.empty()) { + str.append("."); + } + str.append((const char*)(buf+pos), len); + pos += len; + } + return pos; + } + + int encode(int pos, char* s) { + while(*s) { + char *f = strchr(s, '.'); + if (f == NULL) { + int len = strlen(s); + buf[pos++] = len; + memcpy(buf+pos, s, len); + pos += len; + break; + } + int len = f - s; + buf[pos++] = len; + memcpy(buf+pos, s, len); + s = f+1; + pos += len; + } + buf[pos++] = 0x00; + return pos; + } +};
diff -r 000000000000 -r d4c8fe4d9b29 Socket/pico_string.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/Socket/pico_string.h Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,46 @@ +// pico_string.h 2013/8/27 +#pragma once +class pico_string { +public: + pico_string(){ + _len = 0; + _buf = (char*)malloc(1); + if (_buf) { + _buf[0] = '\0'; + } + } + ~pico_string() { + if (_buf) { + free(_buf); + } + } + bool empty() { + return _len == 0; + } + void append(const char* s, int len) { + if (_buf == NULL) { + return; + } + char* p = (char*)malloc(_len+len+1); + if (p == NULL) { + return; + } + memcpy(p, _buf, _len); + memcpy(p+_len, s, len); + p[_len+len] = '\0'; + free(_buf); + _buf = p; + } + void append(const char* s) { + append(s, strlen(s)); + } + char* c_str() { + if (_buf) { + return _buf; + } + return ""; + } +private: + char* _buf; + int _len; +};
diff -r 000000000000 -r d4c8fe4d9b29 WIZnetInterface.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/WIZnetInterface.cpp Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,153 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#include "WIZnetInterface.h" +#include "DHCPClient.h" + +#if (not defined TARGET_WIZwiki_W7500) && (not defined TARGET_WIZwiki_W7500P) && (not defined TARGET_WIZwiki_W7500ECO) +WIZnetInterface::WIZnetInterface(PinName mosi, PinName miso, PinName sclk, PinName cs, PinName reset) : + WIZnet_Chip(mosi, miso, sclk, cs, reset) +{ + ip_set = false; +} + +WIZnetInterface::WIZnetInterface(SPI* spi, PinName cs, PinName reset) : + WIZnet_Chip(spi, cs, reset) +{ + ip_set = false; +} +#endif + +int WIZnetInterface::init() +{ + dhcp = true; + reset(); + + return 0; +} + +int WIZnetInterface::init(uint8_t * mac) +{ + dhcp = true; + // + for (int i =0; i < 6; i++) this->mac[i] = mac[i]; + // + reset(); + + return 0; +} + +int WIZnetInterface::init(uint8_t * mac, const char* ip, const char* mask, const char* gateway) +{ + dhcp = false; + // + for (int i =0; i < 6; i++) this->mac[i] = mac[i]; + // + this->ip = str_to_ip(ip); + strcpy(ip_string, ip); + ip_set = true; + this->netmask = str_to_ip(mask); + this->gateway = str_to_ip(gateway); + reset(); + + // @Jul. 8. 2014 add code. should be called to write chip. + setmac(); + setip(); + + return 0; +} + +// Connect Bring the interface up, start DHCP if needed. +int WIZnetInterface::connect() +{ + if (dhcp) { + int r = IPrenew(); + if (r < 0) { + return r; + } + } + + if (WIZnet_Chip::setip() == false) return -1; + return 0; +} + +// Disconnect Bring the interface down. +int WIZnetInterface::disconnect() +{ + //if (WIZnet_Chip::disconnect() == false) return -1; + return 0; +} + + +char* WIZnetInterface::getIPAddress() +{ + uint32_t ip = reg_rd<uint32_t>(SIPR); + snprintf(ip_string, sizeof(ip_string), "%d.%d.%d.%d", + (uint8_t)((ip>>24)&0xff), + (uint8_t)((ip>>16)&0xff), + (uint8_t)((ip>>8)&0xff), + (uint8_t)(ip&0xff)); + return ip_string; +} + +char* WIZnetInterface::getNetworkMask() +{ + uint32_t ip = reg_rd<uint32_t>(SUBR); + snprintf(mask_string, sizeof(mask_string), "%d.%d.%d.%d", + (uint8_t)((ip>>24)&0xff), + (uint8_t)((ip>>16)&0xff), + (uint8_t)((ip>>8)&0xff), + (uint8_t)(ip&0xff)); + return mask_string; +} + +char* WIZnetInterface::getGateway() +{ + uint32_t ip = reg_rd<uint32_t>(GAR); + snprintf(gw_string, sizeof(gw_string), "%d.%d.%d.%d", + (uint8_t)((ip>>24)&0xff), + (uint8_t)((ip>>16)&0xff), + (uint8_t)((ip>>8)&0xff), + (uint8_t)(ip&0xff)); + return gw_string; +} + +char* WIZnetInterface::getMACAddress() +{ + uint8_t mac[6]; + reg_rd_mac(SHAR, mac); + snprintf(mac_string, sizeof(mac_string), "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + //ethernet_address(mac_string); + return mac_string; + +} + +int WIZnetInterface::IPrenew(int timeout_ms) +{ + DHCPClient dhcp; + int err = dhcp.setup(timeout_ms); + if (err == (-1)) { + return -1; + } +// printf("Connected, IP: %d.%d.%d.%d\n", dhcp.yiaddr[0], dhcp.yiaddr[1], dhcp.yiaddr[2], dhcp.yiaddr[3]); + ip = (dhcp.yiaddr[0] <<24) | (dhcp.yiaddr[1] <<16) | (dhcp.yiaddr[2] <<8) | dhcp.yiaddr[3]; + gateway = (dhcp.gateway[0]<<24) | (dhcp.gateway[1]<<16) | (dhcp.gateway[2]<<8) | dhcp.gateway[3]; + netmask = (dhcp.netmask[0]<<24) | (dhcp.netmask[1]<<16) | (dhcp.netmask[2]<<8) | dhcp.netmask[3]; + dnsaddr = (dhcp.dnsaddr[0]<<24) | (dhcp.dnsaddr[1]<<16) | (dhcp.dnsaddr[2]<<8) | dhcp.dnsaddr[3]; + return 0; +}
diff -r 000000000000 -r d4c8fe4d9b29 WIZnetInterface.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/WIZnetInterface.h Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,91 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#pragma once +#include "eth_arch.h" + /** Interface using Wiznet chip to connect to an IP-based network + * + */ +class WIZnetInterface: public WIZnet_Chip { +public: + +#if (not defined TARGET_WIZwiki_W7500) && (not defined TARGET_WIZwiki_W7500P) && (not defined TARGET_WIZwiki_W7500ECO) + + /** + * Constructor + * + * \param mosi mbed pin to use for SPI + * \param miso mbed pin to use for SPI + * \param sclk mbed pin to use for SPI + * \param cs chip select of the WIZnet_Chip + * \param reset reset pin of the WIZnet_Chip + */ + WIZnetInterface(PinName mosi, PinName miso, PinName sclk, PinName cs, PinName reset); + WIZnetInterface(SPI* spi, PinName cs, PinName reset); +#endif + + /** Initialize the interface with DHCP. + * Initialize the interface and configure it to use DHCP (no connection at this point). + * \return 0 on success, a negative number on failure + */ + int init(); //With DHCP + int init(uint8_t * mac); //With DHCP + + /** Initialize the interface with a static IP address. + * Initialize the interface and configure it with the following static configuration (no connection at this point). + * \param ip the IP address to use + * \param mask the IP address mask + * \param gateway the gateway to use + * \return 0 on success, a negative number on failure + */ + int init(uint8_t * mac, const char* ip, const char* mask, const char* gateway); + + /** Connect + * Bring the interface up, start DHCP if needed. + * \return 0 on success, a negative number on failure + */ + int connect(); + + /** Disconnect + * Bring the interface down + * \return 0 on success, a negative number on failure + */ + int disconnect(); + + /** Get IP address & MAC address + * + * @ returns ip address + */ + char* getIPAddress(); + char* getNetworkMask(); + char* getGateway(); + char* getMACAddress(); + + int IPrenew(int timeout_ms = 15*1000); + +private: + char ip_string[20]; + char mask_string[20]; + char gw_string[20]; + char mac_string[20]; + bool ip_set; +}; + +#include "TCPSocketConnection.h" +#include "TCPSocketServer.h" +#include "WIZnet_UDPSocket.h"
diff -r 000000000000 -r d4c8fe4d9b29 arch/ext/W5500.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/arch/ext/W5500.cpp Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,522 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#include "eth_arch.h" +#if (not defined TARGET_WIZwiki_W7500) && (not defined TARGET_WIZwiki_W7500P) && (not defined TARGET_WIZwiki_W7500ECO) + + + +#include "mbed.h" +#include "mbed_debug.h" +#include "DNSClient.h" + + +//Debug is disabled by default +#if 0 +#define DBG(...) do{debug("%p %d %s ", this,__LINE__,__PRETTY_FUNCTION__); debug(__VA_ARGS__); } while(0); +//#define DBG(x, ...) debug("[W5500:DBG]"x"\r\n", ##__VA_ARGS__); +#define WARN(x, ...) debug("[W5500:WARN]"x"\r\n", ##__VA_ARGS__); +#define ERR(x, ...) debug("[W5500:ERR]"x"\r\n", ##__VA_ARGS__); +#else +#define DBG(x, ...) +#define WARN(x, ...) +#define ERR(x, ...) +#endif + +#if 1 +#define INFO(x, ...) debug("[W5500:INFO]"x"\r\n", ##__VA_ARGS__); +#else +#define INFO(x, ...) +#endif + +#define DBG_SPI 0 + +WIZnet_Chip* WIZnet_Chip::inst; + +WIZnet_Chip::WIZnet_Chip(PinName mosi, PinName miso, PinName sclk, PinName _cs, PinName _reset): + cs(_cs), reset_pin(_reset) +{ + spi = new SPI(mosi, miso, sclk); + cs = 1; + reset_pin = 1; + inst = this; + sock_any_port = SOCK_ANY_PORT_NUM; +} + +WIZnet_Chip::WIZnet_Chip(SPI* spi, PinName _cs, PinName _reset): + cs(_cs), reset_pin(_reset) +{ + this->spi = spi; + cs = 1; + reset_pin = 1; + inst = this; + sock_any_port = SOCK_ANY_PORT_NUM; +} + +bool WIZnet_Chip::setmac() +{ + + for (int i =0; i < 6; i++) reg_wr<uint8_t>(SHAR+i, mac[i]); + + return true; +} + +// Set the IP +bool WIZnet_Chip::setip() +{ + reg_wr<uint32_t>(SIPR, ip); + reg_wr<uint32_t>(GAR, gateway); + reg_wr<uint32_t>(SUBR, netmask); + return true; +} + +bool WIZnet_Chip::setProtocol(int socket, Protocol p) +{ + if (socket < 0) { + return false; + } + sreg<uint8_t>(socket, Sn_MR, p); + return true; +} + +bool WIZnet_Chip::connect(int socket, const char * host, int port, int timeout_ms) +{ + if (socket < 0) { + return false; + } + sreg<uint8_t>(socket, Sn_MR, TCP); + scmd(socket, OPEN); + sreg_ip(socket, Sn_DIPR, host); + sreg<uint16_t>(socket, Sn_DPORT, port); + sreg<uint16_t>(socket, Sn_PORT, new_port()); + scmd(socket, CONNECT); + Timer t; + t.reset(); + t.start(); + while(!is_connected(socket)) { + if (t.read_ms() > timeout_ms) { + return false; + } + } + return true; +} + +bool WIZnet_Chip::gethostbyname(const char* host, uint32_t* ip) +{ + uint32_t addr = str_to_ip(host); + char buf[17]; + snprintf(buf, sizeof(buf), "%d.%d.%d.%d", (addr>>24)&0xff, (addr>>16)&0xff, (addr>>8)&0xff, addr&0xff); + if (strcmp(buf, host) == 0) { + *ip = addr; + return true; + } + DNSClient client; + if(client.lookup(host)) { + *ip = client.ip; + return true; + } + return false; +} + +bool WIZnet_Chip::disconnect() +{ + return true; +} + +bool WIZnet_Chip::is_connected(int socket) +{ + /* + if (sreg<uint8_t>(socket, Sn_SR) == SOCK_ESTABLISHED) { + return true; + } + */ + uint8_t tmpSn_SR; + tmpSn_SR = sreg<uint8_t>(socket, Sn_SR); + // packet sending is possible, when state is SOCK_CLOSE_WAIT. + if ((tmpSn_SR == SOCK_ESTABLISHED) || (tmpSn_SR == SOCK_CLOSE_WAIT)) { + return true; + } + return false; +} + +// Reset the chip & set the buffer +void WIZnet_Chip::reset() +{ +#if defined(USE_WIZ550IO_MAC) + //read the MAC address inside the module + reg_rd_mac(SHAR, mac); +#endif + // hw reset + reset_pin = 1; + reset_pin = 0; + wait_us(500); // 500us (w5500) + reset_pin = 1; + wait_ms(400); // 400ms (w5500) +#if defined(USE_WIZ550IO_MAC) + // write MAC address inside the WZTOE MAC address register + reg_wr_mac(SHAR, mac); +#endif + // set RX and TX buffer size +#if 0 + for (int socket = 0; socket < MAX_SOCK_NUM; socket++) { + sreg<uint8_t>(socket, Sn_RXBUF_SIZE, 2); + sreg<uint8_t>(socket, Sn_TXBUF_SIZE, 2); + } +#endif +} + + +bool WIZnet_Chip::close(int socket) +{ + if (socket < 0) { + return false; + } + // if not connected, return + if (sreg<uint8_t>(socket, Sn_SR) == SOCK_CLOSED) { + return true; + } + if (sreg<uint8_t>(socket, Sn_MR) == TCP) { + scmd(socket, DISCON); + } + scmd(socket, CLOSE); + sreg<uint8_t>(socket, Sn_IR, 0xff); + return true; +} + +int WIZnet_Chip::wait_readable(int socket, int wait_time_ms, int req_size) +{ + if (socket < 0) { + return -1; + } + Timer t; + t.reset(); + t.start(); + while(1) { + //int size = sreg<uint16_t>(socket, Sn_RX_RSR); + // during the reading Sn_RX_RXR, it has the possible change of this register. + // so read twice and get same value then use size information. + int size, size2; + do { + size = sreg<uint16_t>(socket, Sn_RX_RSR); + size2 = sreg<uint16_t>(socket, Sn_RX_RSR); + } while (size != size2); + + if (size > req_size) { + return size; + } + if (wait_time_ms != (-1) && t.read_ms() > wait_time_ms) { + break; + } + } + return -1; +} + +int WIZnet_Chip::wait_writeable(int socket, int wait_time_ms, int req_size) +{ + if (socket < 0) { + return -1; + } + Timer t; + t.reset(); + t.start(); + while(1) { + //int size = sreg<uint16_t>(socket, Sn_TX_FSR); + // during the reading Sn_TX_FSR, it has the possible change of this register. + // so read twice and get same value then use size information. + int size, size2; + do { + size = sreg<uint16_t>(socket, Sn_TX_FSR); + size2 = sreg<uint16_t>(socket, Sn_TX_FSR); + } while (size != size2); + + if (size > req_size) { + return size; + } + if (wait_time_ms != (-1) && t.read_ms() > wait_time_ms) { + break; + } + } + return -1; +} + +int WIZnet_Chip::send(int socket, const char * str, int len) +{ + if (socket < 0) { + return -1; + } + uint16_t ptr = sreg<uint16_t>(socket, Sn_TX_WR); + uint8_t cntl_byte = (0x14 + (socket << 5)); + spi_write(ptr, cntl_byte, (uint8_t*)str, len); + sreg<uint16_t>(socket, Sn_TX_WR, ptr + len); + scmd(socket, SEND); + uint8_t tmp_Sn_IR; + while (( (tmp_Sn_IR = sreg<uint8_t>(socket, Sn_IR)) & INT_SEND_OK) != INT_SEND_OK) { + // @Jul.10, 2014 fix contant name, and udp sendto function. + switch (sreg<uint8_t>(socket, Sn_SR)) { + case SOCK_CLOSED : + close(socket); + return 0; + //break; + case SOCK_UDP : + // ARP timeout is possible. + if ((tmp_Sn_IR & INT_TIMEOUT) == INT_TIMEOUT) { + sreg<uint8_t>(socket, Sn_IR, INT_TIMEOUT); + return 0; + } + break; + default : + break; + } + } + /* + while ((sreg<uint8_t>(socket, Sn_IR) & INT_SEND_OK) != INT_SEND_OK) { + if (sreg<uint8_t>(socket, Sn_SR) == CLOSED) { + close(socket); + return 0; + } + } + */ + sreg<uint8_t>(socket, Sn_IR, INT_SEND_OK); + + return len; +} + +int WIZnet_Chip::recv(int socket, char* buf, int len) +{ + if (socket < 0) { + return -1; + } + uint16_t ptr = sreg<uint16_t>(socket, Sn_RX_RD); + uint8_t cntl_byte = (0x18 + (socket << 5)); + spi_read(ptr, cntl_byte, (uint8_t*)buf, len); + sreg<uint16_t>(socket, Sn_RX_RD, ptr + len); + scmd(socket, RECV); + return len; +} + +int WIZnet_Chip::new_socket() +{ + for(int s = 0; s < MAX_SOCK_NUM; s++) { + if (sreg<uint8_t>(s, Sn_SR) == SOCK_CLOSED) { + return s; + } + } + return -1; +} + +uint16_t WIZnet_Chip::new_port() +{ + uint16_t port = rand(); + port |= 49152; + return port; +} + +bool WIZnet_Chip::link(int wait_time_ms) +{ + Timer t; + t.reset(); + t.start(); + while(1) { + int is_link = ethernet_link(); + + if (is_link) { + return true; + } + if (wait_time_ms != (-1) && t.read_ms() > wait_time_ms) { + break; + } + } + return 0; +} + +void WIZnet_Chip::set_link(PHYMode phymode) +{ + int speed = -1; + int duplex = 0; + + switch(phymode) { + case AutoNegotiate : speed = -1; duplex = 0; break; + case HalfDuplex10 : speed = 0; duplex = 0; break; + case FullDuplex10 : speed = 0; duplex = 1; break; + case HalfDuplex100 : speed = 1; duplex = 0; break; + case FullDuplex100 : speed = 1; duplex = 1; break; + } + + ethernet_set_link(speed, duplex); +} + +void WIZnet_Chip::scmd(int socket, Command cmd) +{ + sreg<uint8_t>(socket, Sn_CR, cmd); + while(sreg<uint8_t>(socket, Sn_CR)); +} + +void WIZnet_Chip::spi_write(uint16_t addr, uint8_t cb, const uint8_t *buf, uint16_t len) +{ + cs = 0; + spi->write(addr >> 8); + spi->write(addr & 0xff); + spi->write(cb); + for(int i = 0; i < len; i++) { + spi->write(buf[i]); + } + cs = 1; + +#if DBG_SPI + debug("[SPI]W %04x(%02x %d)", addr, cb, len); + for(int i = 0; i < len; i++) { + debug(" %02x", buf[i]); + if (i > 16) { + debug(" ..."); + break; + } + } + debug("\r\n"); +#endif +} + +void WIZnet_Chip::spi_read(uint16_t addr, uint8_t cb, uint8_t *buf, uint16_t len) +{ + cs = 0; + spi->write(addr >> 8); + spi->write(addr & 0xff); + spi->write(cb); + for(int i = 0; i < len; i++) { + buf[i] = spi->write(0); + } + cs = 1; + +#if DBG_SPI + debug("[SPI]R %04x(%02x %d)", addr, cb, len); + for(int i = 0; i < len; i++) { + debug(" %02x", buf[i]); + if (i > 16) { + debug(" ..."); + break; + } + } + debug("\r\n"); + if ((addr&0xf0ff)==0x4026 || (addr&0xf0ff)==0x4003) { + wait_ms(200); + } +#endif +} + +uint32_t str_to_ip(const char* str) +{ + uint32_t ip = 0; + char* p = (char*)str; + for(int i = 0; i < 4; i++) { + ip |= atoi(p); + p = strchr(p, '.'); + if (p == NULL) { + break; + } + ip <<= 8; + p++; + } + return ip; +} + +void printfBytes(char* str, uint8_t* buf, int len) +{ + printf("%s %d:", str, len); + for(int i = 0; i < len; i++) { + printf(" %02x", buf[i]); + } + printf("\n"); +} + +void printHex(uint8_t* buf, int len) +{ + for(int i = 0; i < len; i++) { + if ((i%16) == 0) { + printf("%p", buf+i); + } + printf(" %02x", buf[i]); + if ((i%16) == 15) { + printf("\n"); + } + } + printf("\n"); +} + +void debug_hex(uint8_t* buf, int len) +{ + for(int i = 0; i < len; i++) { + if ((i%16) == 0) { + debug("%p", buf+i); + } + debug(" %02x", buf[i]); + if ((i%16) == 15) { + debug("\n"); + } + } + debug("\n"); +} + +int WIZnet_Chip::ethernet_link(void) { + int val = getPHYCFGR(); + return (val&0x01); +} + +void WIZnet_Chip::ethernet_set_link(int speed, int duplex) { + uint32_t val=0; + if((speed < 0) || (speed > 1)) { + val = (PHYCFGR_OPMDC_ALLA)<<3; + } else { + val = (((speed&0x01)<<1)+ (duplex&0x01))<<3; + } + setPHYCFGR((uint8_t)(PHYCFGR_RST&(PHYCFGR_OPMD|val))); + wait(0.2); + setPHYCFGR((uint8_t)((~PHYCFGR_RST)|(PHYCFGR_OPMD|val))); + wait(0.2); +} + + void WIZnet_Chip::reg_rd_mac(uint16_t addr, uint8_t* data) { + spi_read(addr, 0x00, data, 6); + } + + void WIZnet_Chip::reg_wr_ip(uint16_t addr, uint8_t cb, const char* ip) { + uint8_t buf[4]; + char* p = (char*)ip; + for(int i = 0; i < 4; i++) { + buf[i] = atoi(p); + p = strchr(p, '.'); + if (p == NULL) { + break; + } + p++; + } + spi_write(addr, cb, buf, sizeof(buf)); + } + + void WIZnet_Chip::sreg_ip(int socket, uint16_t addr, const char* ip) { + reg_wr_ip(addr, (0x0C + (socket << 5)), ip); + } + + void WIZnet_Chip::reg_rd_ip_byte(uint16_t addr, uint8_t* data) { + spi_read(addr, 0x00, data, 4); + } + + void WIZnet_Chip::reg_wr_ip_byte(uint16_t addr, uint8_t* data) { + spi_write(addr, 0x04, data, 4); + } + + +#endif +
diff -r 000000000000 -r d4c8fe4d9b29 arch/ext/W5500.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/arch/ext/W5500.h Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,1012 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#pragma once + +#include "mbed.h" +#include "mbed_debug.h" + +#define TEST_ASSERT(A) while(!(A)){debug("\n\n%s@%d %s ASSERT!\n\n",__PRETTY_FUNCTION__,__LINE__,#A);exit(1);}; + +#define DEFAULT_WAIT_RESP_TIMEOUT 500 + +#define SOCK_ERROR 0 +#define SOCKERR_SOCKNUM (SOCK_ERROR - 1) ///< Invalid socket number +#define SOCKERR_SOCKOPT (SOCK_ERROR - 2) ///< Invalid socket option +#define SOCKERR_SOCKINIT (SOCK_ERROR - 3) ///< Socket is not initialized +#define SOCKERR_SOCKCLOSED (SOCK_ERROR - 4) ///< Socket unexpectedly closed. +#define SOCKERR_SOCKMODE (SOCK_ERROR - 5) ///< Invalid socket mode for socket operation. +#define SOCKERR_SOCKFLAG (SOCK_ERROR - 6) ///< Invalid socket flag +#define SOCKERR_SOCKSTATUS (SOCK_ERROR - 7) ///< Invalid socket status for socket operation. +#define SOCKERR_ARG (SOCK_ERROR - 10) ///< Invalid argrument. +#define SOCKERR_PORTZERO (SOCK_ERROR - 11) ///< Port number is zero +#define SOCKERR_IPINVALID (SOCK_ERROR - 12) ///< Invalid IP address +#define SOCKERR_TIMEOUT (SOCK_ERROR - 13) ///< Timeout occurred +#define SOCKERR_DATALEN (SOCK_ERROR - 14) ///< Data length is zero or greater than buffer max size. +#define SOCKERR_BUFFER (SOCK_ERROR - 15) ///< Socket buffer is not enough for data communication. + +#define SOCK_ANY_PORT_NUM 0xC000; + + +#define MAX_SOCK_NUM 8 + +#define MR 0x0000 +#define GAR 0x0001 +#define SUBR 0x0005 +#define SHAR 0x0009 +#define SIPR 0x000f +#define IR 0x0015 +#define IMR 0x0016 +#define SIR 0x0017 +#define SIMR 0x0018 +#define RTR 0x0019 +#define RCR 0x001b +#define UIPR 0x0028 +#define UPORTR 0x002c +#define PHYCFGR 0x002e + +// W5500 socket register +#define Sn_MR 0x0000 +#define Sn_CR 0x0001 +#define Sn_IR 0x0002 +#define Sn_SR 0x0003 +#define Sn_PORT 0x0004 +#define Sn_DHAR 0x0006 +#define Sn_DIPR 0x000c +#define Sn_DPORT 0x0010 +#define Sn_RXBUF_SIZE 0x001e +#define Sn_TXBUF_SIZE 0x001f +#define Sn_TX_FSR 0x0020 +#define Sn_TX_RD 0x0022 +#define Sn_TX_WR 0x0024 +#define Sn_RX_RSR 0x0026 +#define Sn_RX_RD 0x0028 +#define Sn_RX_WR 0x002a +#define Sn_IMR 0x002c + + +//Define for Socket Command register option value +#define Sn_CR_OPEN 0x01 +#define Sn_CR_LISTEN 0x02 +#define Sn_CR_CONNECT 0x04 +#define Sn_CR_DISCON 0x08 +#define Sn_CR_CLOSE 0x10 +#define Sn_CR_SEND 0x20 +#define Sn_CR_SEND_MAC 0x21 +#define Sn_CR_SEND_KEEP 0x22 +#define Sn_CR_RECV 0x40 + + +//Define for Socket Mode register option value +#define Sn_MR_CLOSE 0x00 +#define Sn_MR_TCP 0x01 +#define Sn_MR_UDP 0x02 +#define Sn_MR_MACRAW 0x04 +#define Sn_MR_UCASTB 0x10 +#define Sn_MR_ND 0x20 +#define Sn_MR_BCASTB 0x40 +#define Sn_MR_MULTI 0x80 + +#define Sn_IR_SENDOK 0x10 + +//Sn_IR values + +#define Sn_IR_TIMEOUT 0x08 +#define Sn_IR_RECV 0x04 +#define Sn_IR_DISCON 0x02 +#define Sn_IR_CON 0x01 + +/* PHYCFGR register value */ +#define PHYCFGR_RST ~(1<<7) //< For PHY reset, must operate AND mask. +#define PHYCFGR_OPMD (1<<6) // Configre PHY with OPMDC value +#define PHYCFGR_OPMDC_ALLA (7<<3) +#define PHYCFGR_OPMDC_PDOWN (6<<3) +#define PHYCFGR_OPMDC_NA (5<<3) +#define PHYCFGR_OPMDC_100FA (4<<3) +#define PHYCFGR_OPMDC_100F (3<<3) +#define PHYCFGR_OPMDC_100H (2<<3) +#define PHYCFGR_OPMDC_10F (1<<3) +#define PHYCFGR_OPMDC_10H (0<<3) +#define PHYCFGR_DPX_FULL (1<<2) +#define PHYCFGR_DPX_HALF (0<<2) +#define PHYCFGR_SPD_100 (1<<1) +#define PHYCFGR_SPD_10 (0<<1) +#define PHYCFGR_LNK_ON (1<<0) +#define PHYCFGR_LNK_OFF (0<<0) + +//PHY status define +#define PHY_CONFBY_HW 0 ///< Configured PHY operation mode by HW pin +#define PHY_CONFBY_SW 1 ///< Configured PHY operation mode by SW register +#define PHY_MODE_MANUAL 0 ///< Configured PHY operation mode with user setting. +#define PHY_MODE_AUTONEGO 1 ///< Configured PHY operation mode with auto-negotiation +#define PHY_SPEED_10 0 ///< Link Speed 10 +#define PHY_SPEED_100 1 ///< Link Speed 100 +#define PHY_DUPLEX_HALF 0 ///< Link Half-Duplex +#define PHY_DUPLEX_FULL 1 ///< Link Full-Duplex +#define PHY_LINK_OFF 0 ///< Link Off +#define PHY_LINK_ON 1 ///< Link On +#define PHY_POWER_NORM 0 ///< PHY power normal mode +#define PHY_POWER_DOWN 1 ///< PHY power down mode + +enum PHYMode { + AutoNegotiate = 0, + HalfDuplex10 = 1, + FullDuplex10 = 2, + HalfDuplex100 = 3, + FullDuplex100 = 4, +}; +class WIZnet_Chip { +public: +enum Protocol { + CLOSED = 0, + TCP = 1, + UDP = 2, +}; + +enum Command { + OPEN = 0x01, + LISTEN = 0x02, + CONNECT = 0x04, + DISCON = 0x08, + CLOSE = 0x10, + SEND = 0x20, + SEND_MAC = 0x21, + SEND_KEEP = 0x22, + RECV = 0x40, + +}; + +enum Interrupt { + INT_CON = 0x01, + INT_DISCON = 0x02, + INT_RECV = 0x04, + INT_TIMEOUT = 0x08, + INT_SEND_OK = 0x10, +}; + +enum Status { + SOCK_CLOSED = 0x00, + SOCK_INIT = 0x13, + SOCK_LISTEN = 0x14, + SOCK_SYNSENT = 0x15, + SOCK_ESTABLISHED = 0x17, + SOCK_CLOSE_WAIT = 0x1c, + SOCK_UDP = 0x22, +}; + + + uint16_t sock_any_port; + + /* + * Constructor + * + * @param spi spi class + * @param cs cs of the W5500 + * @param reset reset pin of the W5500 + */ + WIZnet_Chip(PinName mosi, PinName miso, PinName sclk, PinName cs, PinName reset); + WIZnet_Chip(SPI* spi, PinName cs, PinName reset); + + /* + * Set MAC Address to W5500 + * + * @return true if connected, false otherwise + */ + bool setmac(); + + /* + * Set Network Informations (SrcIP, Netmask, Gataway) + * + * @return true if connected, false otherwise + */ + bool setip(); + + /* + * Disconnect the connection + * + * @ returns true + */ + bool disconnect(); + + /* + * Open a tcp connection with the specified host on the specified port + * + * @param host host (can be either an ip address or a name. If a name is provided, a dns request will be established) + * @param port port + * @ returns true if successful + */ + bool connect(int socket, const char * host, int port, int timeout_ms = 10*1000); + + /* + * Set the protocol (UDP or TCP) + * + * @param p protocol + * @ returns true if successful + */ + bool setProtocol(int socket, Protocol p); + + /* + * Reset the W5500 + */ + void reset(); + + int wait_readable(int socket, int wait_time_ms, int req_size = 0); + + int wait_writeable(int socket, int wait_time_ms, int req_size = 0); + + /* + * Check if an ethernet link is pressent or not. + * + * @returns true if successful + */ + bool link(int wait_time_ms= 3*1000); + + /* + * Sets the speed and duplex parameters of an ethernet link. + * + * @returns true if successful + */ + void set_link(PHYMode phymode); + + /* + * Check if a tcp link is active + * + * @returns true if successful + */ + bool is_connected(int socket); + + /* + * Close a tcp connection + * + * @ returns true if successful + */ + bool close(int socket); + + /* + * @param str string to be sent + * @param len string length + */ + int send(int socket, const char * str, int len); + + int recv(int socket, char* buf, int len); + + /* + * Return true if the module is using dhcp + * + * @returns true if the module is using dhcp + */ + bool isDHCP() { + return dhcp; + } + + bool gethostbyname(const char* host, uint32_t* ip); + + static WIZnet_Chip * getInstance() { + return inst; + }; + + int new_socket(); + uint16_t new_port(); + void scmd(int socket, Command cmd); + + template<typename T> + void sreg(int socket, uint16_t addr, T data) { + reg_wr<T>(addr, (0x0C + (socket << 5)), data); + } + + template<typename T> + T sreg(int socket, uint16_t addr) { + return reg_rd<T>(addr, (0x08 + (socket << 5))); + } + + template<typename T> + void reg_wr(uint16_t addr, T data) { + return reg_wr(addr, 0x04, data); + } + + template<typename T> + void reg_wr(uint16_t addr, uint8_t cb, T data) { + uint8_t buf[sizeof(T)]; + *reinterpret_cast<T*>(buf) = data; + for(int i = 0; i < sizeof(buf)/2; i++) { // Little Endian to Big Endian + uint8_t t = buf[i]; + buf[i] = buf[sizeof(buf)-1-i]; + buf[sizeof(buf)-1-i] = t; + } + spi_write(addr, cb, buf, sizeof(buf)); + } + + template<typename T> + T reg_rd(uint16_t addr) { + return reg_rd<T>(addr, 0x00); + } + + template<typename T> + T reg_rd(uint16_t addr, uint8_t cb) { + uint8_t buf[sizeof(T)]; + spi_read(addr, cb, buf, sizeof(buf)); + for(int i = 0; i < sizeof(buf)/2; i++) { // Big Endian to Little Endian + uint8_t t = buf[i]; + buf[i] = buf[sizeof(buf)-1-i]; + buf[sizeof(buf)-1-i] = t; + } + return *reinterpret_cast<T*>(buf); + } + + void reg_rd_mac(uint16_t addr, uint8_t* data); +/* { + spi_read(addr, 0x00, data, 6); + }*/ + + void reg_wr_ip(uint16_t addr, uint8_t cb, const char* ip); + /* { + uint8_t buf[4]; + char* p = (char*)ip; + for(int i = 0; i < 4; i++) { + buf[i] = atoi(p); + p = strchr(p, '.'); + if (p == NULL) { + break; + } + p++; + } + spi_write(addr, cb, buf, sizeof(buf)); + } + */ + void sreg_ip(int socket, uint16_t addr, const char* ip); +/* { + reg_wr_ip(addr, (0x0C + (socket << 5)), ip); + }*/ + + void reg_rd_ip_byte(uint16_t addr, uint8_t* data); +/* { + spi_read(addr, 0x00, data, 4); + }*/ + + void reg_wr_ip_byte(uint16_t addr, uint8_t* data); +/* { + spi_write(addr, 0x04, data, 4); + }*/ + +///////////////////////////////// +// Common Register I/O function // +///////////////////////////////// +/** + * @ingroup Common_register_access_function + * @brief Set Mode Register + * @param (uint8_t)mr The value to be set. + * @sa getMR() + */ + void setMR(uint8_t mr) { + reg_wr<uint8_t>(MR,mr); + } + + +/** + * @ingroup Common_register_access_function + * @brief Get Mode Register + * @return uint8_t. The value of Mode register. + * @sa setMR() + */ + uint8_t getMR() { + return reg_rd<uint8_t>(MR); + } + +/** + * @ingroup Common_register_access_function + * @brief Set gateway IP address + * @param (uint8_t*)gar Pointer variable to set gateway IP address. It should be allocated 4 bytes. + * @sa getGAR() + */ + void setGAR(uint8_t * gar) { + reg_wr_ip_byte(GAR,gar); + } + +/** + * @ingroup Common_register_access_function + * @brief Get gateway IP address + * @param (uint8_t*)gar Pointer variable to get gateway IP address. It should be allocated 4 bytes. + * @sa setGAR() + */ + void getGAR(uint8_t * gar) { + reg_rd_ip_byte(GAR,gar); + } + +/** + * @ingroup Common_register_access_function + * @brief Set subnet mask address + * @param (uint8_t*)subr Pointer variable to set subnet mask address. It should be allocated 4 bytes. + * @sa getSUBR() + */ + void setSUBR(uint8_t * subr) { + reg_wr_ip_byte(SUBR, subr); + } + + +/** + * @ingroup Common_register_access_function + * @brief Get subnet mask address + * @param (uint8_t*)subr Pointer variable to get subnet mask address. It should be allocated 4 bytes. + * @sa setSUBR() + */ + void getSUBR(uint8_t * subr) { + reg_rd_ip_byte(SUBR, subr); + } + +/** + * @ingroup Common_register_access_function + * @brief Set local MAC address + * @param (uint8_t*)shar Pointer variable to set local MAC address. It should be allocated 6 bytes. + * @sa getSHAR() + */ + void setSHAR(uint8_t * shar) { + reg_wr_mac(SHAR, shar); + } + +/** + * @ingroup Common_register_access_function + * @brief Get local MAC address + * @param (uint8_t*)shar Pointer variable to get local MAC address. It should be allocated 6 bytes. + * @sa setSHAR() + */ + void getSHAR(uint8_t * shar) { + reg_rd_mac(SHAR, shar); + } + +/** + * @ingroup Common_register_access_function + * @brief Set local IP address + * @param (uint8_t*)sipr Pointer variable to set local IP address. It should be allocated 4 bytes. + * @sa getSIPR() + */ + void setSIPR(uint8_t * sipr) { + reg_wr_ip_byte(SIPR, sipr); + } + +/** + * @ingroup Common_register_access_function + * @brief Get local IP address + * @param (uint8_t*)sipr Pointer variable to get local IP address. It should be allocated 4 bytes. + * @sa setSIPR() + */ + void getSIPR(uint8_t * sipr) { + reg_rd_ip_byte(SIPR, sipr); + } + +/** + * @ingroup Common_register_access_function + * @brief Set @ref IR register + * @param (uint8_t)ir Value to set @ref IR register. + * @sa getIR() + */ + void setIR(uint8_t ir) { + reg_wr<uint8_t>(IR, (ir & 0xF0)); + } + +/** + * @ingroup Common_register_access_function + * @brief Get @ref IR register + * @return uint8_t. Value of @ref IR register. + * @sa setIR() + */ + uint8_t getIR() { + return reg_rd<uint8_t>(IR & 0xF0); + } + +/** + * @ingroup Common_register_access_function + * @brief Set @ref IMR register + * @param (uint8_t)imr Value to set @ref IMR register. + * @sa getIMR() + */ + void setIMR(uint8_t imr) { + reg_wr<uint8_t>(IMR, imr); + } + +/** + * @ingroup Common_register_access_function + * @brief Get @ref IMR register + * @return uint8_t. Value of @ref IMR register. + * @sa setIMR() + */ + uint8_t getIMR() { + return reg_rd<uint8_t>(IMR); + } + + +/** + * @ingroup Common_register_access_function + * @brief Set @ref SIR register + * @param (uint8_t)sir Value to set @ref SIR register. + * @sa getSIR() + */ + void setSIR(uint8_t sir) { + reg_wr<uint8_t>(SIR, sir); + } + +/** + * @ingroup Common_register_access_function + * @brief Get @ref SIR register + * @return uint8_t. Value of @ref SIR register. + * @sa setSIR() + */ + uint8_t getSIR() { + return reg_rd<uint8_t>(SIR); + } +/** + * @ingroup Common_register_access_function + * @brief Set @ref SIMR register + * @param (uint8_t)simr Value to set @ref SIMR register. + * @sa getSIMR() + */ + void setSIMR(uint8_t simr) { + reg_wr<uint8_t>(SIMR, simr); + } + +/** + * @ingroup Common_register_access_function + * @brief Get @ref SIMR register + * @return uint8_t. Value of @ref SIMR register. + * @sa setSIMR() + */ + uint8_t getSIMR() { + return reg_rd<uint8_t>(SIMR); + } + +/** + * @ingroup Common_register_access_function + * @brief Set @ref RTR register + * @param (uint16_t)rtr Value to set @ref RTR register. + * @sa getRTR() + */ + void setRTR(uint16_t rtr) { + reg_wr<uint16_t>(RTR, rtr); + } + +/** + * @ingroup Common_register_access_function + * @brief Get @ref RTR register + * @return uint16_t. Value of @ref RTR register. + * @sa setRTR() + */ + uint16_t getRTR() { + return reg_rd<uint16_t>(RTR); + } + +/** + * @ingroup Common_register_access_function + * @brief Set @ref RCR register + * @param (uint8_t)rcr Value to set @ref RCR register. + * @sa getRCR() + */ + void setRCR(uint8_t rcr) { + reg_wr<uint8_t>(RCR, rcr); + } + +/** + * @ingroup Common_register_access_function + * @brief Get @ref RCR register + * @return uint8_t. Value of @ref RCR register. + * @sa setRCR() + */ + uint8_t getRCR() { + return reg_rd<uint8_t>(RCR); + } + +//================================================== test done =========================================================== + +/** + * @ingroup Common_register_access_function + * @brief Set @ref PHYCFGR register + * @param (uint8_t)phycfgr Value to set @ref PHYCFGR register. + * @sa setPHYCFGR() + */ + void setPHYCFGR(uint8_t phycfgr) { + reg_wr<uint8_t>(PHYCFGR, phycfgr); + } + +/** + * @ingroup Common_register_access_function + * @brief Get @ref PHYCFGR register + * @return uint8_t. Value of @ref PHYCFGR register. + * @sa getPHYCFGR() + */ + uint8_t getPHYCFGR() { + return reg_rd<uint8_t>(PHYCFGR); + } + + +///////////////////////////////////// + +/////////////////////////////////// +// Socket N register I/O function // +/////////////////////////////////// +/** + * @ingroup Socket_register_access_function + * @brief Set @ref Sn_MR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @param (uint8_t)mr Value to set @ref Sn_MR + * @sa getSn_MR() + */ + void setSn_MR(uint8_t sn, uint8_t mr) { + sreg<uint8_t>(sn, MR, mr); + } + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_MR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint8_t. Value of @ref Sn_MR. + * @sa setSn_MR() + */ + uint8_t getSn_MR(uint8_t sn) { + return sreg<uint8_t>(sn, Sn_MR); + } + +/** + * @ingroup Socket_register_access_function + * @brief Set @ref Sn_CR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @param (uint8_t)cr Value to set @ref Sn_CR + * @sa getSn_CR() + */ + void setSn_CR(uint8_t sn, uint8_t cr) { + sreg<uint8_t>(sn, Sn_CR, cr); + } + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_CR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint8_t. Value of @ref Sn_CR. + * @sa setSn_CR() + */ + uint8_t getSn_CR(uint8_t sn) { + return sreg<uint8_t>(sn, Sn_CR); + } + +/** + * @ingroup Socket_register_access_function + * @brief Set @ref Sn_IR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @param (uint8_t)ir Value to set @ref Sn_IR + * @sa getSn_IR() + */ + void setSn_IR(uint8_t sn, uint8_t ir) { + sreg<uint8_t>(sn, Sn_IR, (ir & 0x1F)); + } + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_IR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint8_t. Value of @ref Sn_IR. + * @sa setSn_IR() + */ + uint8_t getSn_IR(uint8_t sn) { + return (sreg<uint8_t>(sn, Sn_IR)) & 0x1F; + } + +/** + * @ingroup Socket_register_access_function + * @brief Set @ref Sn_IMR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @param (uint8_t)imr Value to set @ref Sn_IMR + * @sa getSn_IMR() + */ + void setSn_IMR(uint8_t sn, uint8_t imr) { + sreg<uint8_t>(sn, Sn_IMR, (imr & 0x1F)); + } + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_IMR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint8_t. Value of @ref Sn_IMR. + * @sa setSn_IMR() + */ + uint8_t getSn_IMR(uint8_t sn) { + return (sreg<uint8_t>(sn, Sn_IMR)) & 0x1F; + } + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_SR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint8_t. Value of @ref Sn_SR. + */ + uint8_t getSn_SR(uint8_t sn) { + return sreg<uint8_t>(sn, Sn_SR); + } + +/** + * @ingroup Socket_register_access_function + * @brief Set @ref Sn_PORT register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @param (uint16_t)port Value to set @ref Sn_PORT. + * @sa getSn_PORT() + */ + void setSn_PORT(uint8_t sn, uint16_t port) { + sreg<uint16_t>(sn, Sn_PORT, port ); + } + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_PORT register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint16_t. Value of @ref Sn_PORT. + * @sa setSn_PORT() + */ + uint16_t getSn_PORT(uint8_t sn) { + return sreg<uint16_t>(sn, Sn_PORT); + } + +/** + * @ingroup Socket_register_access_function + * @brief Set @ref Sn_DHAR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @param (uint8_t*)dhar Pointer variable to set socket n destination hardware address. It should be allocated 6 bytes. + * @sa getSn_DHAR() + */ + void setSn_DHAR(uint8_t sn, uint8_t * dhar) { + spi_write(Sn_DHAR, (0x0C + (sn << 5)), dhar, 6); + } + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_MR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @param (uint8_t*)dhar Pointer variable to get socket n destination hardware address. It should be allocated 6 bytes. + * @sa setSn_DHAR() + */ + void getSn_DHAR(uint8_t sn, uint8_t * dhar) { + spi_read(Sn_DHAR, (0x08 + (sn << 5)), dhar, 6); + } + +/** + * @ingroup Socket_register_access_function + * @brief Set @ref Sn_DIPR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @param (uint8_t*)dipr Pointer variable to set socket n destination IP address. It should be allocated 4 bytes. + * @sa getSn_DIPR() + */ + void setSn_DIPR(uint8_t sn, uint8_t * dipr) { + spi_write(Sn_DIPR, (0x0C + (sn << 5)), dipr, 4); + } + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_DIPR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @param (uint8_t*)dipr Pointer variable to get socket n destination IP address. It should be allocated 4 bytes. + * @sa SetSn_DIPR() + */ + void getSn_DIPR(uint8_t sn, uint8_t * dipr) { + spi_read(Sn_DIPR, (0x08 + (sn << 5)), dipr, 4); + } + +/** + * @ingroup Socket_register_access_function + * @brief Set @ref Sn_DPORT register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @param (uint16_t)dport Value to set @ref Sn_DPORT + * @sa getSn_DPORT() + */ + void setSn_DPORT(uint8_t sn, uint16_t dport) { + sreg<uint16_t>(sn, Sn_DPORT, dport); + } + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_DPORT register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint16_t. Value of @ref Sn_DPORT. + * @sa setSn_DPORT() + */ + uint16_t getSn_DPORT(uint8_t sn) { + return sreg<uint16_t>(sn, Sn_DPORT); + } + + +/** + * @ingroup Socket_register_access_function + * @brief Set @ref Sn_RXBUF_SIZE register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @param (uint8_t)rxbufsize Value to set @ref Sn_RXBUF_SIZE + * @sa getSn_RXBUF_SIZE() + */ + void setSn_RXBUF_SIZE(uint8_t sn, uint8_t rxbufsize) { + sreg<uint8_t>(sn, Sn_RXBUF_SIZE ,rxbufsize); + } + + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_RXBUF_SIZE register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint8_t. Value of @ref Sn_RXBUF_SIZE. + * @sa setSn_RXBUF_SIZE() + */ + uint8_t getSn_RXBUF_SIZE(uint8_t sn) { + return sreg<uint8_t>(sn, Sn_RXBUF_SIZE); + } + +/** + * @ingroup Socket_register_access_function + * @brief Set @ref Sn_TXBUF_SIZE register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @param (uint8_t)txbufsize Value to set @ref Sn_TXBUF_SIZE + * @sa getSn_TXBUF_SIZE() + */ + void setSn_TXBUF_SIZE(uint8_t sn, uint8_t txbufsize) { + sreg<uint8_t>(sn, Sn_TXBUF_SIZE, txbufsize); + } + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_TXBUF_SIZE register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint8_t. Value of @ref Sn_TXBUF_SIZE. + * @sa setSn_TXBUF_SIZE() + */ + uint8_t getSn_TXBUF_SIZE(uint8_t sn) { + return sreg<uint8_t>(sn, Sn_TXBUF_SIZE); + } + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_TX_FSR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint16_t. Value of @ref Sn_TX_FSR. + */ + uint16_t getSn_TX_FSR(uint8_t sn) { + return sreg<uint16_t>(sn, Sn_TX_FSR); + } + + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_TX_RD register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint16_t. Value of @ref Sn_TX_RD. + */ + uint16_t getSn_TX_RD(uint8_t sn) { + return sreg<uint16_t>(sn, Sn_TX_RD); + } + +/** + * @ingroup Socket_register_access_function + * @brief Set @ref Sn_TX_WR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @param (uint16_t)txwr Value to set @ref Sn_TX_WR + * @sa GetSn_TX_WR() + */ + void setSn_TX_WR(uint8_t sn, uint16_t txwr) { + sreg<uint16_t>(sn, Sn_TX_WR, txwr); + } + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_TX_WR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint16_t. Value of @ref Sn_TX_WR. + * @sa setSn_TX_WR() + */ + uint16_t getSn_TX_WR(uint8_t sn) { + return sreg<uint16_t>(sn, Sn_TX_WR); + } + + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_RX_RSR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint16_t. Value of @ref Sn_RX_RSR. + */ + uint16_t getSn_RX_RSR(uint8_t sn) { + return sreg<uint16_t>(sn, Sn_RX_RSR); + } + + +/** + * @ingroup Socket_register_access_function + * @brief Set @ref Sn_RX_RD register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @param (uint16_t)rxrd Value to set @ref Sn_RX_RD + * @sa getSn_RX_RD() + */ + void setSn_RX_RD(uint8_t sn, uint16_t rxrd) { + sreg<uint16_t>(sn, Sn_RX_RD, rxrd); + } + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_RX_RD register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @regurn uint16_t. Value of @ref Sn_RX_RD. + * @sa setSn_RX_RD() + */ + uint16_t getSn_RX_RD(uint8_t sn) { + return sreg<uint16_t>(sn, Sn_RX_RD); + } + +/** + * @ingroup Socket_register_access_function + * @brief Get @ref Sn_RX_WR register + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint16_t. Value of @ref Sn_RX_WR. + */ + uint16_t getSn_RX_WR(uint8_t sn) { + return sreg<uint16_t>(sn, Sn_RX_WR); + } + + +////////////////////////////////////// + +///////////////////////////////////// +// Sn_TXBUF & Sn_RXBUF IO function // +///////////////////////////////////// +/** + * @brief Gets the max buffer size of socket sn passed as parameter. + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint16_t. Value of Socket n RX max buffer size. + */ + uint16_t getSn_RxMAX(uint8_t sn) { + return (getSn_RXBUF_SIZE(sn) << 10); + } + +/** + * @brief Gets the max buffer size of socket sn passed as parameters. + * @param (uint8_t)sn Socket number. It should be <b>0 ~ 7</b>. + * @return uint16_t. Value of Socket n TX max buffer size. + */ +//uint16_t getSn_TxMAX(uint8_t sn); + uint16_t getSn_TxMAX(uint8_t sn) { + return (getSn_TXBUF_SIZE(sn) << 10); + } + + + int ethernet_link(void); + void ethernet_set_link(int speed, int duplex); +protected: + uint8_t mac[6]; + uint32_t ip; + uint32_t netmask; + uint32_t gateway; + uint32_t dnsaddr; + bool dhcp; + + void spi_write(uint16_t addr, uint8_t cb, const uint8_t *buf, uint16_t len); + void spi_read(uint16_t addr, uint8_t cb, uint8_t *buf, uint16_t len); + SPI* spi; + DigitalOut cs; + DigitalOut reset_pin; + static WIZnet_Chip* inst; + + void reg_wr_mac(uint16_t addr, uint8_t* data) { + spi_write(addr, 0x04, data, 6); + } + +}; + + +extern uint32_t str_to_ip(const char* str); +extern void printfBytes(char* str, uint8_t* buf, int len); +extern void printHex(uint8_t* buf, int len); +extern void debug_hex(uint8_t* buf, int len);
diff -r 000000000000 -r d4c8fe4d9b29 arch/int/W7500x_toe.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/arch/int/W7500x_toe.cpp Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,558 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ +#include "eth_arch.h" +#if defined(TARGET_WIZwiki_W7500) || defined(TARGET_WIZwiki_W7500P) || defined(TARGET_WIZwiki_W7500ECO) + + +#include "mbed.h" +#include "mbed_debug.h" +#include "DNSClient.h" + + +/* + * MDIO via GPIO + * mdio via gpio is supported and related functions as follows. + * - mdio_init(),mdio_read(),mdio_write() + * - input_MDIO(),output_MDIO(),turnaroud_MDIO(),idle_MDIO() + * called by ethernet_link() and ethernet_set_link() + */ + +#if defined (TARGET_WIZwiki_W7500) || defined(TARGET_WIZwiki_W7500ECO) + +#define MDIO GPIO_Pin_14 +#define MDC GPIO_Pin_15 +#define GPIO_MDC GPIOB +#define PHY_ADDR_IP101G 0x07 +#define PHY_ADDR PHY_ADDR_IP101G +#define SVAL 0x2 //right shift val = 2 +#define PHYREG_CONTROL 0x0 //Control Register address (Contorl basic register) +#define PHYREG_STATUS 0x1 //Status Register address (Status basic register) +#define CNTL_DUPLEX (0x01ul<< 7) +#define CNTL_AUTONEGO (0x01ul<<11) +#define CNTL_SPEED (0x01ul<<12) +#define MDC_WAIT (1) + +#elif defined (TARGET_WIZwiki_W7500P) + +#define MDIO GPIO_Pin_15 +#define MDC GPIO_Pin_14 +#define GPIO_MDC GPIOB +#define PHY_ADDR_IP101G 0x01 +#define PHY_ADDR PHY_ADDR_IP101G +#define SVAL 0x2 //right shift val = 2 +#define PHYREG_CONTROL 0x0 //Control Register address (Contorl basic register) +#define PHYREG_STATUS 0x1 //Status Register address (Status basic register) +#define CNTL_DUPLEX (0x01ul<< 8) +#define CNTL_AUTONEGO (0x01ul<<12) +#define CNTL_SPEED (0x01ul<<13) +#define MDC_WAIT (1) + +#endif + +void mdio_init(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin_MDC, uint16_t GPIO_Pin_MDIO); +void mdio_write(GPIO_TypeDef* GPIOx, uint32_t PhyRegAddr, uint32_t val); +uint32_t mdio_read(GPIO_TypeDef* GPIOx, uint32_t PhyRegAddr); + +WIZnet_Chip* WIZnet_Chip::inst; + +WIZnet_Chip::WIZnet_Chip() +{ + inst = this; +} + +bool WIZnet_Chip::setmac() +{ + reg_wr_mac(SHAR, mac); + return true; +} + +// Set the IP +bool WIZnet_Chip::setip() +{ + reg_wr<uint32_t>(SIPR, ip); + reg_wr<uint32_t>(GAR, gateway); + reg_wr<uint32_t>(SUBR, netmask); + return true; +} + +bool WIZnet_Chip::setProtocol(int socket, Protocol p) +{ + if (socket < 0) { + return false; + } + sreg<uint8_t>(socket, Sn_MR, p); + return true; +} + +bool WIZnet_Chip::connect(int socket, const char * host, int port, int timeout_ms) +{ + if (socket < 0) { + return false; + } + sreg<uint8_t>(socket, Sn_MR, TCP); + scmd(socket, OPEN); + sreg_ip(socket, Sn_DIPR, host); + sreg<uint16_t>(socket, Sn_DPORT, port); + sreg<uint16_t>(socket, Sn_PORT, new_port()); + scmd(socket, CONNECT); + Timer t; + t.reset(); + t.start(); + while(!is_connected(socket)) { + if (t.read_ms() > timeout_ms) { + return false; + } + } + return true; +} + +bool WIZnet_Chip::gethostbyname(const char* host, uint32_t* ip) +{ + uint32_t addr = str_to_ip(host); + char buf[17]; + snprintf(buf, sizeof(buf), "%d.%d.%d.%d", + (uint8_t)((addr>>24)&0xff), + (uint8_t)((addr>>16)&0xff), + (uint8_t)((addr>>8)&0xff), + (uint8_t)(addr&0xff)); + if (strcmp(buf, host) == 0) { + *ip = addr; + return true; + } + DNSClient client; + if(client.lookup(host)) { + *ip = client.ip; + return true; + } + return false; +} + + +bool WIZnet_Chip::is_connected(int socket) +{ + /* + if (sreg<uint8_t>(socket, Sn_SR) == SOCK_ESTABLISHED) { + return true; + } + */ + uint8_t tmpSn_SR; + tmpSn_SR = sreg<uint8_t>(socket, Sn_SR); + // packet sending is possible, when state is SOCK_CLOSE_WAIT. + if ((tmpSn_SR == SOCK_ESTABLISHED) || (tmpSn_SR == SOCK_CLOSE_WAIT)) { + return true; + } + return false; +} +// Reset the chip & set the buffer +void WIZnet_Chip::reset() +{ + /* S/W Reset PHY */ + mdio_write(GPIO_MDC, PHYREG_CONTROL, 0x8000); + wait_ms(10);//for S/W reset + wait_ms(10);//for MDC I/F RDY + + mdio_init(GPIO_MDC, MDC, MDIO); + + /* S/W Reset WZTOE */ + reg_wr<uint8_t>(MR, MR_RST); + // set PAD strengh and pull-up for TXD[3:0] and TXE +#ifdef __DEF_USED_IC101AG__ //For using IC+101AG + +#if defined(TARGET_WIZwiki_W7500) || defined(TARGET_WIZwiki_W7500ECO) + + *(volatile uint32_t *)(0x41003068) = 0x64; //TXD0 + *(volatile uint32_t *)(0x4100306C) = 0x64; //TXD1 + *(volatile uint32_t *)(0x41003070) = 0x64; //TXD2 + *(volatile uint32_t *)(0x41003074) = 0x64; //TXD3 + *(volatile uint32_t *)(0x41003050) = 0x64; //TXE +#endif + +#endif + + // set ticker counter + reg_wr<uint32_t>(TIC100US, (SystemCoreClock/10000)); + // write MAC address inside the WZTOE MAC address register + reg_wr_mac(SHAR, mac); + /* + * set RX and TX buffer size + * for (int socket = 0; socket < MAX_SOCK_NUM; socket++) { + * sreg<uint8_t>(socket, Sn_RXBUF_SIZE, 2); + * sreg<uint8_t>(socket, Sn_TXBUF_SIZE, 2); + * } + */ +} + + +bool WIZnet_Chip::close(int socket) +{ + if (socket < 0) { + return false; + } + // if SOCK_CLOSED, return + if (sreg<uint8_t>(socket, Sn_SR) == SOCK_CLOSED) { + return true; + } + // if SOCK_ESTABLISHED, send FIN-Packet to peer + if (sreg<uint8_t>(socket, Sn_MR) == TCP) { + scmd(socket, DISCON); + } + // close socket + scmd(socket, CLOSE); + // clear Socket Interrupt Register + sreg<uint8_t>(socket, Sn_ICR, 0xff); + return true; +} + +int WIZnet_Chip::wait_readable(int socket, int wait_time_ms, int req_size) +{ + if (socket < 0) { + return -1; + } + Timer t; + t.reset(); + t.start(); + while(1) { + int size = sreg<uint16_t>(socket, Sn_RX_RSR); + if (size > req_size) { + return size; + } + if (wait_time_ms != (-1) && t.read_ms() > wait_time_ms) { + break; + } + } + return -1; +} + +int WIZnet_Chip::wait_writeable(int socket, int wait_time_ms, int req_size) +{ + if (socket < 0) { + return -1; + } + Timer t; + t.reset(); + t.start(); + while(1) { + int size = sreg<uint16_t>(socket, Sn_TX_FSR); + if (size > req_size) { + return size; + } + if (wait_time_ms != (-1) && t.read_ms() > wait_time_ms) { + break; + } + } + return -1; +} + +int WIZnet_Chip::send(int socket, const char * str, int len) +{ + if (socket < 0) { + return -1; + } + + uint16_t ptr = sreg<uint16_t>(socket, Sn_TX_WR); + uint32_t sn_tx_base = W7500x_TXMEM_BASE + (uint32_t)(socket<<18); + + for(int i=0; i<len; i++) + *(volatile uint8_t *)(sn_tx_base + ((ptr+i)&0xFFFF)) = str[i]; + + sreg<uint16_t>(socket, Sn_TX_WR, ptr + len); + scmd(socket, SEND); + + uint8_t tmp_Sn_IR; + while (( (tmp_Sn_IR = sreg<uint8_t>(socket, Sn_IR)) & INT_SEND_OK) != INT_SEND_OK) { + // @Jul.10, 2014 fix contant name, and udp sendto function. + switch (sreg<uint8_t>(socket, Sn_SR)) { + case SOCK_CLOSED : + close(socket); + return 0; + //break; + case SOCK_UDP : + // ARP timeout is possible. + if ((tmp_Sn_IR & INT_TIMEOUT) == INT_TIMEOUT) { + sreg<uint8_t>(socket, Sn_ICR, INT_TIMEOUT); + return 0; + } + break; + default : + break; + } + } + + sreg<uint8_t>(socket, Sn_ICR, INT_SEND_OK); + + return len; +} + +int WIZnet_Chip::recv(int socket, char* buf, int len) +{ + if (socket < 0) { + return -1; + } + uint16_t ptr = sreg<uint16_t>(socket, Sn_RX_RD); + uint32_t sn_rx_base = W7500x_RXMEM_BASE + (uint32_t)(socket<<18); + + for(int i=0; i<len; i++) + buf[i] = *(volatile uint8_t *)(sn_rx_base + ((ptr+i)&0xFFFF)); + + sreg<uint16_t>(socket, Sn_RX_RD, ptr + len); + scmd(socket, RECV); + + return len; +} + +int WIZnet_Chip::new_socket() +{ + for(int s = 0; s < MAX_SOCK_NUM; s++) { + if (sreg<uint8_t>(s, Sn_SR) == SOCK_CLOSED) { + return s; + } + } + return -1; +} + +uint16_t WIZnet_Chip::new_port() +{ + uint16_t port = rand(); + port |= 49152; + return port; +} + +bool WIZnet_Chip::link(int wait_time_ms) +{ + Timer t; + t.reset(); + t.start(); + while(1) { + int is_link = ethernet_link(); + + if (is_link) { + return true; + } + if (wait_time_ms != (-1) && t.read_ms() > wait_time_ms) { + break; + } + } + return 0; +} + +void WIZnet_Chip::set_link(PHYMode phymode) +{ + int speed = -1; + int duplex = 0; + + switch(phymode) { + case AutoNegotiate : speed = -1; duplex = 0; break; + case HalfDuplex10 : speed = 0; duplex = 0; break; + case FullDuplex10 : speed = 0; duplex = 1; break; + case HalfDuplex100 : speed = 1; duplex = 0; break; + case FullDuplex100 : speed = 1; duplex = 1; break; + } + + ethernet_set_link(speed, duplex); +} + +uint32_t str_to_ip(const char* str) +{ + uint32_t ip = 0; + char* p = (char*)str; + for(int i = 0; i < 4; i++) { + ip |= atoi(p); + p = strchr(p, '.'); + if (p == NULL) { + break; + } + ip <<= 8; + p++; + } + return ip; +} + +void printfBytes(char* str, uint8_t* buf, int len) +{ + printf("%s %d:", str, len); + for(int i = 0; i < len; i++) { + printf(" %02x", buf[i]); + } + printf("\n"); +} + +void printHex(uint8_t* buf, int len) +{ + for(int i = 0; i < len; i++) { + if ((i%16) == 0) { + printf("%p", buf+i); + } + printf(" %02x", buf[i]); + if ((i%16) == 15) { + printf("\n"); + } + } + printf("\n"); +} + +void debug_hex(uint8_t* buf, int len) +{ + for(int i = 0; i < len; i++) { + if ((i%16) == 0) { + debug("%p", buf+i); + } + debug(" %02x", buf[i]); + if ((i%16) == 15) { + debug("\n"); + } + } + debug("\n"); +} + +void WIZnet_Chip::scmd(int socket, Command cmd) +{ + sreg<uint8_t>(socket, Sn_CR, cmd); + while(sreg<uint8_t>(socket, Sn_CR)); +} + + +void mdio_init(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin_MDC, uint16_t GPIO_Pin_MDIO) +{ + /* Set GPIOs for MDIO and MDC */ + GPIO_InitTypeDef MDIO_InitDef; + HAL_PAD_AFConfig(PAD_PB, GPIO_Pin_MDIO, PAD_AF1); + HAL_PAD_AFConfig(PAD_PB, GPIO_Pin_MDC, PAD_AF1); + MDIO_InitDef.GPIO_Pin = GPIO_Pin_MDC | GPIO_Pin_MDIO; + MDIO_InitDef.GPIO_Mode = GPIO_Mode_OUT; + HAL_GPIO_Init(GPIOx, &MDIO_InitDef); +} + +void output_MDIO(GPIO_TypeDef* GPIOx, uint32_t val, uint32_t n) +{ + for(val <<= (32-n); n; val<<=1, n--) + { + if(val & 0x80000000) + HAL_GPIO_SetBits(GPIOx, MDIO); + else + HAL_GPIO_ResetBits(GPIOx, MDIO); + + wait_ms(MDC_WAIT); + HAL_GPIO_SetBits(GPIOx, MDC); + wait_ms(MDC_WAIT); + HAL_GPIO_ResetBits(GPIOx, MDC); + } +} + +uint32_t input_MDIO( GPIO_TypeDef* GPIOx ) +{ + uint32_t i, val=0; + for(i=0; i<16; i++) + { + val <<=1; + HAL_GPIO_SetBits(GPIOx, MDC); + wait_ms(MDC_WAIT); + HAL_GPIO_ResetBits(GPIOx, MDC); + wait_ms(MDC_WAIT); + val |= HAL_GPIO_ReadInputDataBit(GPIOx, MDIO); + } + return (val); +} + +void turnaround_MDIO( GPIO_TypeDef* GPIOx) +{ + GPIOx->OUTENCLR = MDIO ; + HAL_GPIO_SetBits(GPIOx, MDC); + wait_ms(MDC_WAIT); + HAL_GPIO_ResetBits(GPIOx, MDC); + wait_ms(MDC_WAIT); +} + +void idle_MDIO( GPIO_TypeDef* GPIOx ) +{ + GPIOx->OUTENSET = MDIO ; + HAL_GPIO_SetBits(GPIOx,MDC); + wait_ms(MDC_WAIT); + HAL_GPIO_ResetBits(GPIOx, MDC); + wait_ms(MDC_WAIT); +} + +uint32_t mdio_read(GPIO_TypeDef* GPIOx, uint32_t PhyRegAddr) +{ + output_MDIO(GPIOx, 0xFFFFFFFF, 32); + output_MDIO(GPIOx, 0x06, 4); + output_MDIO(GPIOx, PHY_ADDR, 5); + output_MDIO(GPIOx, PhyRegAddr, 5); + turnaround_MDIO(GPIOx); + uint32_t val = input_MDIO(GPIOx ); + idle_MDIO(GPIOx); + return val; +} + +void mdio_write(GPIO_TypeDef* GPIOx, uint32_t PhyRegAddr, uint32_t val) +{ + output_MDIO(GPIOx, 0xFFFFFFFF, 32); + output_MDIO(GPIOx, 0x05, 4); + output_MDIO(GPIOx, PHY_ADDR, 5); + output_MDIO(GPIOx, PhyRegAddr, 5); + output_MDIO(GPIOx, 0x02, 2); + output_MDIO(GPIOx, val, 16); + idle_MDIO(GPIOx); +} + +int WIZnet_Chip::ethernet_link(void) { + return ((mdio_read(GPIO_MDC, PHYREG_STATUS)>>SVAL)&0x01); +} + +void WIZnet_Chip::ethernet_set_link(int speed, int duplex) { + uint32_t val=0; + if((speed < 0) || (speed > 1)) { + val = CNTL_AUTONEGO; + } else { + val = ((CNTL_SPEED&(speed<<11))|(CNTL_DUPLEX&(duplex<<7))); + } + mdio_write(GPIO_MDC, PHYREG_CONTROL, val); +} + + void WIZnet_Chip::reg_rd_mac(uint16_t addr, uint8_t* data) + { + data[0] = *(volatile uint8_t *)(W7500x_WZTOE_BASE + (uint32_t)(addr+3)); + data[1] = *(volatile uint8_t *)(W7500x_WZTOE_BASE + (uint32_t)(addr+2)); + data[2] = *(volatile uint8_t *)(W7500x_WZTOE_BASE + (uint32_t)(addr+1)); + data[3] = *(volatile uint8_t *)(W7500x_WZTOE_BASE + (uint32_t)(addr+0)); + data[4] = *(volatile uint8_t *)(W7500x_WZTOE_BASE + (uint32_t)(addr+7)); + data[5] = *(volatile uint8_t *)(W7500x_WZTOE_BASE + (uint32_t)(addr+6)); + } + + void WIZnet_Chip::reg_wr_ip(uint16_t addr, uint8_t cb, const char* ip) + { + uint8_t buf[4]={0,}; + uint32_t wr_ip = 0; + char* p = (char*)ip; + + for(int i = 0; i < 4; i++) { + wr_ip = (wr_ip<<8); + buf[i] = atoi(p); + wr_ip |= buf[i]; + p = strchr(p, '.'); + if (p == NULL) break; + p++; + } + *(volatile uint32_t *)(W7500x_WZTOE_BASE + (uint32_t)((cb<<16)+addr)) = wr_ip; + } + + void WIZnet_Chip::sreg_ip(int socket, uint16_t addr, const char* ip) { + reg_wr_ip(addr, (uint8_t)(0x01+(socket<<2)), ip); + } + +#endif + +
diff -r 000000000000 -r d4c8fe4d9b29 arch/int/W7500x_toe.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/arch/int/W7500x_toe.h Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,300 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +#pragma once + +#include "mbed.h" +#include "mbed_debug.h" + +#define TEST_ASSERT(A) while(!(A)){debug("\n\n%s@%d %s ASSERT!\n\n",__PRETTY_FUNCTION__,__LINE__,#A);exit(1);}; + +#define DEFAULT_WAIT_RESP_TIMEOUT 500 + + +#define MAX_SOCK_NUM 8 + +// Peripheral base address +#define W7500x_WZTOE_BASE (0x46000000) +#define W7500x_TXMEM_BASE (W7500x_WZTOE_BASE + 0x00020000) +#define W7500x_RXMEM_BASE (W7500x_WZTOE_BASE + 0x00030000) +// Common register +#define MR (0x2300) +#define GAR (0x6008) +#define SUBR (0x600C) +#define SHAR (0x6000) +#define SIPR (0x6010) + +// Added Common register @W7500 +#define TIC100US (0x2000) + +// Socket register +#define Sn_MR (0x0000) +#define Sn_CR (0x0010) +#define Sn_IR (0x0020) //--Sn_ISR +#define Sn_SR (0x0030) +#define Sn_PORT (0x0114) +#define Sn_DIPR (0x0124) +#define Sn_DPORT (0x0120) +#define Sn_RXBUF_SIZE (0x0200) +#define Sn_TXBUF_SIZE (0x0220) +#define Sn_TX_FSR (0x0204) +#define Sn_TX_WR (0x020C) +#define Sn_RX_RSR (0x0224) +#define Sn_RX_RD (0x0228) +// added Socket register @W7500 +#define Sn_ICR (0x0028) +enum PHYMode { + AutoNegotiate = 0, + HalfDuplex10 = 1, + FullDuplex10 = 2, + HalfDuplex100 = 3, + FullDuplex100 = 4, +}; + +//bool plink(int wait_time_ms= 3*1000); + +class WIZnet_Chip { +public: +enum Protocol { + CLOSED = 0, + TCP = 1, + UDP = 2, +}; + +enum Command { + OPEN = 0x01, + LISTEN = 0x02, + CONNECT = 0x04, + DISCON = 0x08, + CLOSE = 0x10, + SEND = 0x20, + SEND_MAC = 0x21, + SEND_KEEP = 0x22, + RECV = 0x40, + +}; + +enum Interrupt { + INT_CON = 0x01, + INT_DISCON = 0x02, + INT_RECV = 0x04, + INT_TIMEOUT = 0x08, + INT_SEND_OK = 0x10, +}; +enum Status { + SOCK_CLOSED = 0x00, + SOCK_INIT = 0x13, + SOCK_LISTEN = 0x14, + SOCK_SYNSENT = 0x15, + SOCK_ESTABLISHED = 0x17, + SOCK_CLOSE_WAIT = 0x1c, + SOCK_UDP = 0x22, +}; +enum Mode { + MR_RST = 0x80, + MR_WOL = 0x20, + MR_PB = 0x10, + MR_FARP = 0x02, +}; + + WIZnet_Chip(); + + /* + * Set MAC Address to W7500x_TOE + * + * @return true if connected, false otherwise + */ + bool setmac(); + + /* + * Connect the W7500 WZTOE to the ssid contained in the constructor. + * + * @return true if connected, false otherwise + */ + bool setip(); + + + /* + * Open a tcp connection with the specified host on the specified port + * + * @param host host (can be either an ip address or a name. If a name is provided, a dns request will be established) + * @param port port + * @ returns true if successful + */ + bool connect(int socket, const char * host, int port, int timeout_ms = 10*1000); + + /* + * Set the protocol (UDP or TCP) + * + * @param p protocol + * @ returns true if successful + */ + bool setProtocol(int socket, Protocol p); + + /* + * Reset the W7500 WZTOE + */ + void reset(); + + int wait_readable(int socket, int wait_time_ms, int req_size = 0); + + int wait_writeable(int socket, int wait_time_ms, int req_size = 0); + + /* + * Check if an ethernet link is pressent or not. + * + * @returns true if successful + */ + bool link(int wait_time_ms= 3*1000); + + /* + * Sets the speed and duplex parameters of an ethernet link. + * + * @returns true if successful + */ + void set_link(PHYMode phymode); + + /* + * Check if a tcp link is active + * + * @returns true if successful + */ + bool is_connected(int socket); + + /* + * Close a tcp connection + * + * @ returns true if successful + */ + bool close(int socket); + + /* + * @param str string to be sent + * @param len string length + */ + int send(int socket, const char * str, int len); + + int recv(int socket, char* buf, int len); + + /* + * Return true if the module is using dhcp + * + * @returns true if the module is using dhcp + */ + bool isDHCP() { + return dhcp; + } + + bool gethostbyname(const char* host, uint32_t* ip); + + static WIZnet_Chip * getInstance() { + return inst; + }; + + int new_socket(); + uint16_t new_port(); + + void scmd(int socket, Command cmd); + + template<typename T> + void sreg(int socket, uint16_t addr, T data) { + reg_wr<T>(addr, (uint8_t)(0x01+(socket<<2)), data); + } + + template<typename T> + T sreg(int socket, uint16_t addr) { + return reg_rd<T>(addr, (uint8_t)(0x01+(socket<<2))); + } + + template<typename T> + void reg_wr(uint16_t addr, T data) { + return reg_wr(addr, 0x00, data); + } + + template<typename T> + void reg_wr(uint16_t addr, uint8_t cb, T data) { + uint8_t buf[sizeof(T)]; + *reinterpret_cast<T*>(buf) = data; + /* + for(int i = 0; i < sizeof(buf)/2; i++) { // Little Endian to Big Endian + uint8_t t = buf[i]; + buf[i] = buf[sizeof(buf)-1-i]; + buf[sizeof(buf)-1-i] = t; + } + */ + for(int i = 0; i < sizeof(buf); i++) { // Little Endian to Big Endian + *(volatile uint8_t *)(W7500x_WZTOE_BASE + (uint32_t)((cb<<16)+addr)+i) = buf[i]; + } + } + + template<typename T> + T reg_rd(uint16_t addr) { + return reg_rd<T>(addr, (uint8_t)(0x00)); + } + + template<typename T> + T reg_rd(uint16_t addr, uint8_t cb) { + uint8_t buf[sizeof(T)] = {0,}; + for(int i = 0; i < sizeof(buf); i++) { // Little Endian to Big Endian + buf[i] = *(volatile uint8_t *)(W7500x_WZTOE_BASE + (uint32_t)((cb<<16)+addr)+i); + } + /* + for(int i = 0; i < sizeof(buf)/2; i++) { // Big Endian to Little Endian + uint8_t t = buf[i]; + buf[i] = buf[sizeof(buf)-1-i]; + buf[sizeof(buf)-1-i] = t; + } + */ + return *reinterpret_cast<T*>(buf); + } + + void reg_rd_mac(uint16_t addr, uint8_t* data); + + void reg_wr_ip(uint16_t addr, uint8_t cb, const char* ip); + + void sreg_ip(int socket, uint16_t addr, const char* ip); + + int ethernet_link(void); + + void ethernet_set_link(int speed, int duplex); + + +protected: + uint8_t mac[6]; + uint32_t ip; + uint32_t netmask; + uint32_t gateway; + uint32_t dnsaddr; + bool dhcp; + + static WIZnet_Chip* inst; + + void reg_wr_mac(uint16_t addr, uint8_t* data) { + *(volatile uint8_t *)(W7500x_WZTOE_BASE + (uint32_t)(addr+3)) = data[0] ; + *(volatile uint8_t *)(W7500x_WZTOE_BASE + (uint32_t)(addr+2)) = data[1] ; + *(volatile uint8_t *)(W7500x_WZTOE_BASE + (uint32_t)(addr+1)) = data[2] ; + *(volatile uint8_t *)(W7500x_WZTOE_BASE + (uint32_t)(addr+0)) = data[3] ; + *(volatile uint8_t *)(W7500x_WZTOE_BASE + (uint32_t)(addr+7)) = data[4] ; + *(volatile uint8_t *)(W7500x_WZTOE_BASE + (uint32_t)(addr+6)) = data[5] ; + } +}; + +extern uint32_t str_to_ip(const char* str); +extern void printfBytes(char* str, uint8_t* buf, int len); +extern void printHex(uint8_t* buf, int len); +extern void debug_hex(uint8_t* buf, int len);
diff -r 000000000000 -r d4c8fe4d9b29 eth_arch.h --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/eth_arch.h Mon Sep 04 00:23:04 2017 +0000 @@ -0,0 +1,35 @@ +/* Copyright (C) 2012 mbed.org, MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software + * and associated documentation files (the "Software"), to deal in the Software without restriction, + * including without limitation the rights to use, copy, modify, merge, publish, distribute, + * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or + * substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING + * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ + +#pragma once + +#if defined(TARGET_WIZwiki_W7500) || defined(TARGET_WIZwiki_W7500ECO) + +#include "W7500x_toe.h" +#define __DEF_USED_IC101AG__ //For using IC+101AG@WIZwiki-W7500 + +#elif defined(TARGET_WIZwiki_W7500P) + +#include "W7500x_toe.h" + +#else +#include "W5500.h" // W5500 Ethernet Shield +//#define USE_WIZ550IO_MAC // WIZ550io; using the MAC address + +#endif