network_wiznet5k.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. /*
  2. * This file is part of the MicroPython project, http://micropython.org/
  3. *
  4. * The MIT License (MIT)
  5. *
  6. * Copyright (c) 2014-2018 Damien P. George
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. #include <stdio.h>
  27. #include "py/runtime.h"
  28. #include "py/mphal.h"
  29. #include "spi.h"
  30. #include "modnetwork.h"
  31. #if MICROPY_PY_WIZNET5K && MICROPY_PY_LWIP
  32. #include "drivers/wiznet5k/ethernet/socket.h"
  33. #include "lwip/err.h"
  34. #include "lwip/dns.h"
  35. #include "lwip/dhcp.h"
  36. #include "netif/etharp.h"
  37. /*******************************************************************************/
  38. // Wiznet5k Ethernet driver in MACRAW mode
  39. typedef struct _wiznet5k_obj_t {
  40. mod_network_nic_type_t base;
  41. mp_uint_t cris_state;
  42. const spi_t *spi;
  43. mp_hal_pin_obj_t cs;
  44. mp_hal_pin_obj_t rst;
  45. uint8_t eth_frame[1514];
  46. struct netif netif;
  47. struct dhcp dhcp_struct;
  48. } wiznet5k_obj_t;
  49. // Global object holding the Wiznet5k state
  50. STATIC wiznet5k_obj_t wiznet5k_obj;
  51. STATIC void wiznet5k_lwip_init(wiznet5k_obj_t *self);
  52. STATIC void wiznet5k_lwip_poll(void *self_in, struct netif *netif);
  53. STATIC void wiz_cris_enter(void) {
  54. wiznet5k_obj.cris_state = MICROPY_BEGIN_ATOMIC_SECTION();
  55. }
  56. STATIC void wiz_cris_exit(void) {
  57. MICROPY_END_ATOMIC_SECTION(wiznet5k_obj.cris_state);
  58. }
  59. STATIC void wiz_cs_select(void) {
  60. mp_hal_pin_low(wiznet5k_obj.cs);
  61. }
  62. STATIC void wiz_cs_deselect(void) {
  63. mp_hal_pin_high(wiznet5k_obj.cs);
  64. }
  65. STATIC void wiz_spi_read(uint8_t *buf, uint32_t len) {
  66. HAL_StatusTypeDef status = HAL_SPI_Receive(wiznet5k_obj.spi->spi, buf, len, 5000);
  67. (void)status;
  68. }
  69. STATIC void wiz_spi_write(const uint8_t *buf, uint32_t len) {
  70. HAL_StatusTypeDef status = HAL_SPI_Transmit(wiznet5k_obj.spi->spi, (uint8_t*)buf, len, 5000);
  71. (void)status;
  72. }
  73. STATIC void wiznet5k_init(void) {
  74. // SPI configuration
  75. SPI_InitTypeDef *init = &wiznet5k_obj.spi->spi->Init;
  76. init->Mode = SPI_MODE_MASTER;
  77. init->Direction = SPI_DIRECTION_2LINES;
  78. init->DataSize = SPI_DATASIZE_8BIT;
  79. init->CLKPolarity = SPI_POLARITY_LOW; // clock is low when idle
  80. init->CLKPhase = SPI_PHASE_1EDGE; // data latched on first edge, which is rising edge for low-idle
  81. init->NSS = SPI_NSS_SOFT;
  82. init->BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2; // clock freq = f_PCLK / this_prescale_value; Wiz820i can do up to 80MHz
  83. init->FirstBit = SPI_FIRSTBIT_MSB;
  84. init->TIMode = SPI_TIMODE_DISABLED;
  85. init->CRCCalculation = SPI_CRCCALCULATION_DISABLED;
  86. init->CRCPolynomial = 7; // unused
  87. spi_init(wiznet5k_obj.spi, false);
  88. mp_hal_pin_output(wiznet5k_obj.cs);
  89. mp_hal_pin_output(wiznet5k_obj.rst);
  90. // Reset the chip
  91. mp_hal_pin_low(wiznet5k_obj.rst);
  92. mp_hal_delay_ms(1); // datasheet says 2us
  93. mp_hal_pin_high(wiznet5k_obj.rst);
  94. mp_hal_delay_ms(150); // datasheet says 150ms
  95. // Set physical interface callbacks
  96. reg_wizchip_cris_cbfunc(wiz_cris_enter, wiz_cris_exit);
  97. reg_wizchip_cs_cbfunc(wiz_cs_select, wiz_cs_deselect);
  98. reg_wizchip_spi_cbfunc(wiz_spi_read, wiz_spi_write);
  99. // Configure 16k buffers for fast MACRAW
  100. uint8_t sn_size[16] = {16, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, 0, 0, 0, 0, 0};
  101. ctlwizchip(CW_INIT_WIZCHIP, sn_size);
  102. // Seems we need a small delay after init
  103. mp_hal_delay_ms(250);
  104. // Hook the Wiznet into lwIP
  105. wiznet5k_lwip_init(&wiznet5k_obj);
  106. }
  107. STATIC void wiznet5k_deinit(void) {
  108. for (struct netif *netif = netif_list; netif != NULL; netif = netif->next) {
  109. if (netif == &wiznet5k_obj.netif) {
  110. netif_remove(netif);
  111. netif->flags = 0;
  112. break;
  113. }
  114. }
  115. }
  116. STATIC void wiznet5k_get_mac_address(wiznet5k_obj_t *self, uint8_t mac[6]) {
  117. (void)self;
  118. getSHAR(mac);
  119. }
  120. STATIC void wiznet5k_send_ethernet(wiznet5k_obj_t *self, size_t len, const uint8_t *buf) {
  121. uint8_t ip[4] = {1, 1, 1, 1}; // dummy
  122. int ret = WIZCHIP_EXPORT(sendto)(0, (byte*)buf, len, ip, 11); // dummy port
  123. if (ret != len) {
  124. printf("wiznet5k_send_ethernet: fatal error %d\n", ret);
  125. netif_set_link_down(&self->netif);
  126. netif_set_down(&self->netif);
  127. }
  128. }
  129. // Stores the frame in self->eth_frame and returns number of bytes in the frame, 0 for no frame
  130. STATIC uint16_t wiznet5k_recv_ethernet(wiznet5k_obj_t *self) {
  131. uint16_t len = getSn_RX_RSR(0);
  132. if (len == 0) {
  133. return 0;
  134. }
  135. byte ip[4];
  136. uint16_t port;
  137. int ret = WIZCHIP_EXPORT(recvfrom)(0, self->eth_frame, 1514, ip, &port);
  138. if (ret <= 0) {
  139. printf("wiznet5k_lwip_poll: fatal error len=%u ret=%d\n", len, ret);
  140. netif_set_link_down(&self->netif);
  141. netif_set_down(&self->netif);
  142. return 0;
  143. }
  144. return ret;
  145. }
  146. /*******************************************************************************/
  147. // Wiznet5k lwIP interface
  148. STATIC err_t wiznet5k_netif_output(struct netif *netif, struct pbuf *p) {
  149. wiznet5k_obj_t *self = netif->state;
  150. pbuf_copy_partial(p, self->eth_frame, p->tot_len, 0);
  151. wiznet5k_send_ethernet(self, p->tot_len, self->eth_frame);
  152. return ERR_OK;
  153. }
  154. STATIC err_t wiznet5k_netif_init(struct netif *netif) {
  155. netif->linkoutput = wiznet5k_netif_output;
  156. netif->output = etharp_output;
  157. netif->mtu = 1500;
  158. netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP | NETIF_FLAG_ETHERNET | NETIF_FLAG_IGMP;
  159. wiznet5k_get_mac_address(netif->state, netif->hwaddr);
  160. netif->hwaddr_len = sizeof(netif->hwaddr);
  161. int ret = WIZCHIP_EXPORT(socket)(0, Sn_MR_MACRAW, 0, 0);
  162. if (ret != 0) {
  163. printf("WIZNET fatal error in netifinit: %d\n", ret);
  164. return ERR_IF;
  165. }
  166. // Enable MAC filtering so we only get frames destined for us, to reduce load on lwIP
  167. setSn_MR(0, getSn_MR(0) | Sn_MR_MFEN);
  168. return ERR_OK;
  169. }
  170. STATIC void wiznet5k_lwip_init(wiznet5k_obj_t *self) {
  171. ip_addr_t ipconfig[4];
  172. ipconfig[0].addr = 0;
  173. ipconfig[1].addr = 0;
  174. ipconfig[2].addr = 0;
  175. ipconfig[3].addr = 0;
  176. netif_add(&self->netif, &ipconfig[0], &ipconfig[1], &ipconfig[2], self, wiznet5k_netif_init, ethernet_input);
  177. self->netif.name[0] = 'e';
  178. self->netif.name[1] = '0';
  179. netif_set_default(&self->netif);
  180. dns_setserver(0, &ipconfig[3]);
  181. dhcp_set_struct(&self->netif, &self->dhcp_struct);
  182. // Setting NETIF_FLAG_UP then clearing it is a workaround for dhcp_start and the
  183. // LWIP_DHCP_CHECK_LINK_UP option, so that the DHCP client schedules itself to
  184. // automatically start when the interface later goes up.
  185. self->netif.flags |= NETIF_FLAG_UP;
  186. dhcp_start(&self->netif);
  187. self->netif.flags &= ~NETIF_FLAG_UP;
  188. }
  189. STATIC void wiznet5k_lwip_poll(void *self_in, struct netif *netif) {
  190. wiznet5k_obj_t *self = self_in;
  191. uint16_t len;
  192. while ((len = wiznet5k_recv_ethernet(self)) > 0) {
  193. struct pbuf *p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL);
  194. if (p != NULL) {
  195. pbuf_take(p, self->eth_frame, len);
  196. if (self->netif.input(p, &self->netif) != ERR_OK) {
  197. pbuf_free(p);
  198. }
  199. }
  200. }
  201. }
  202. /*******************************************************************************/
  203. // MicroPython bindings
  204. // WIZNET5K([spi, pin_cs, pin_rst])
  205. STATIC mp_obj_t wiznet5k_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
  206. // check arguments
  207. mp_arg_check_num(n_args, n_kw, 3, 3, false);
  208. const spi_t *spi = spi_from_mp_obj(args[0]);
  209. mp_hal_pin_obj_t cs = pin_find(args[1]);
  210. mp_hal_pin_obj_t rst = pin_find(args[2]);
  211. // Access the existing object, if it has been constructed with the same hardware interface
  212. if (wiznet5k_obj.base.base.type == &mod_network_nic_type_wiznet5k) {
  213. if (!(wiznet5k_obj.spi == spi && wiznet5k_obj.cs == cs && wiznet5k_obj.rst == rst
  214. && wiznet5k_obj.netif.flags != 0)) {
  215. wiznet5k_deinit();
  216. }
  217. }
  218. // Init the wiznet5k object
  219. wiznet5k_obj.base.base.type = &mod_network_nic_type_wiznet5k;
  220. wiznet5k_obj.base.poll_callback = wiznet5k_lwip_poll;
  221. wiznet5k_obj.cris_state = 0;
  222. wiznet5k_obj.spi = spi;
  223. wiznet5k_obj.cs = cs;
  224. wiznet5k_obj.rst = rst;
  225. // Return wiznet5k object
  226. return MP_OBJ_FROM_PTR(&wiznet5k_obj);
  227. }
  228. STATIC mp_obj_t wiznet5k_regs(mp_obj_t self_in) {
  229. (void)self_in;
  230. printf("Wiz CREG:");
  231. for (int i = 0; i < 0x50; ++i) {
  232. if (i % 16 == 0) {
  233. printf("\n %04x:", i);
  234. }
  235. #if MICROPY_PY_WIZNET5K == 5200
  236. uint32_t reg = i;
  237. #else
  238. uint32_t reg = _W5500_IO_BASE_ | i << 8;
  239. #endif
  240. printf(" %02x", WIZCHIP_READ(reg));
  241. }
  242. for (int sn = 0; sn < 4; ++sn) {
  243. printf("\nWiz SREG[%d]:", sn);
  244. for (int i = 0; i < 0x30; ++i) {
  245. if (i % 16 == 0) {
  246. printf("\n %04x:", i);
  247. }
  248. #if MICROPY_PY_WIZNET5K == 5200
  249. uint32_t reg = WIZCHIP_SREG_ADDR(sn, i);
  250. #else
  251. uint32_t reg = _W5500_IO_BASE_ | i << 8 | WIZCHIP_SREG_BLOCK(sn) << 3;
  252. #endif
  253. printf(" %02x", WIZCHIP_READ(reg));
  254. }
  255. }
  256. printf("\n");
  257. return mp_const_none;
  258. }
  259. STATIC MP_DEFINE_CONST_FUN_OBJ_1(wiznet5k_regs_obj, wiznet5k_regs);
  260. STATIC mp_obj_t wiznet5k_isconnected(mp_obj_t self_in) {
  261. wiznet5k_obj_t *self = MP_OBJ_TO_PTR(self_in);
  262. return mp_obj_new_bool(
  263. wizphy_getphylink() == PHY_LINK_ON
  264. && (self->netif.flags & NETIF_FLAG_UP)
  265. && self->netif.ip_addr.addr != 0
  266. );
  267. }
  268. STATIC MP_DEFINE_CONST_FUN_OBJ_1(wiznet5k_isconnected_obj, wiznet5k_isconnected);
  269. STATIC mp_obj_t wiznet5k_active(size_t n_args, const mp_obj_t *args) {
  270. wiznet5k_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  271. if (n_args == 1) {
  272. return mp_obj_new_bool(self->netif.flags & NETIF_FLAG_UP);
  273. } else {
  274. if (mp_obj_is_true(args[1])) {
  275. if (!(self->netif.flags & NETIF_FLAG_UP)) {
  276. wiznet5k_init();
  277. netif_set_link_up(&self->netif);
  278. netif_set_up(&self->netif);
  279. }
  280. } else {
  281. if (self->netif.flags & NETIF_FLAG_UP) {
  282. netif_set_down(&self->netif);
  283. netif_set_link_down(&self->netif);
  284. wiznet5k_deinit();
  285. }
  286. }
  287. return mp_const_none;
  288. }
  289. }
  290. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(wiznet5k_active_obj, 1, 2, wiznet5k_active);
  291. STATIC mp_obj_t wiznet5k_ifconfig(size_t n_args, const mp_obj_t *args) {
  292. wiznet5k_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  293. return mod_network_nic_ifconfig(&self->netif, n_args - 1, args + 1);
  294. }
  295. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(wiznet5k_ifconfig_obj, 1, 2, wiznet5k_ifconfig);
  296. STATIC mp_obj_t wiznet5k_status(size_t n_args, const mp_obj_t *args) {
  297. wiznet5k_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  298. (void)self;
  299. if (n_args == 1) {
  300. // No arguments: return link status
  301. if (self->netif.flags && wizphy_getphylink() == PHY_LINK_ON) {
  302. if ((self->netif.flags & NETIF_FLAG_UP) && self->netif.ip_addr.addr != 0) {
  303. return MP_OBJ_NEW_SMALL_INT(2);
  304. } else {
  305. return MP_OBJ_NEW_SMALL_INT(1);
  306. }
  307. } else {
  308. return MP_OBJ_NEW_SMALL_INT(0);
  309. }
  310. }
  311. mp_raise_ValueError("unknown config param");
  312. }
  313. STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(wiznet5k_status_obj, 1, 2, wiznet5k_status);
  314. STATIC mp_obj_t wiznet5k_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
  315. wiznet5k_obj_t *self = MP_OBJ_TO_PTR(args[0]);
  316. if (kwargs->used == 0) {
  317. // Get config value
  318. if (n_args != 2) {
  319. mp_raise_TypeError("must query one param");
  320. }
  321. switch (mp_obj_str_get_qstr(args[1])) {
  322. case MP_QSTR_mac: {
  323. uint8_t buf[6];
  324. wiznet5k_get_mac_address(self, buf);
  325. return mp_obj_new_bytes(buf, 6);
  326. }
  327. default:
  328. mp_raise_ValueError("unknown config param");
  329. }
  330. } else {
  331. // Set config value(s)
  332. if (n_args != 1) {
  333. mp_raise_TypeError("can't specify pos and kw args");
  334. }
  335. mp_raise_ValueError("unknown config param");
  336. }
  337. }
  338. STATIC MP_DEFINE_CONST_FUN_OBJ_KW(wiznet5k_config_obj, 1, wiznet5k_config);
  339. STATIC mp_obj_t send_ethernet_wrapper(mp_obj_t self_in, mp_obj_t buf_in) {
  340. wiznet5k_obj_t *self = MP_OBJ_TO_PTR(self_in);
  341. mp_buffer_info_t buf;
  342. mp_get_buffer_raise(buf_in, &buf, MP_BUFFER_READ);
  343. wiznet5k_send_ethernet(self, buf.len, buf.buf);
  344. return mp_const_none;
  345. }
  346. STATIC MP_DEFINE_CONST_FUN_OBJ_2(send_ethernet_obj, send_ethernet_wrapper);
  347. STATIC const mp_rom_map_elem_t wiznet5k_locals_dict_table[] = {
  348. { MP_ROM_QSTR(MP_QSTR_regs), MP_ROM_PTR(&wiznet5k_regs_obj) },
  349. { MP_ROM_QSTR(MP_QSTR_isconnected), MP_ROM_PTR(&wiznet5k_isconnected_obj) },
  350. { MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&wiznet5k_active_obj) },
  351. { MP_ROM_QSTR(MP_QSTR_ifconfig), MP_ROM_PTR(&wiznet5k_ifconfig_obj) },
  352. { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&wiznet5k_status_obj) },
  353. { MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&wiznet5k_config_obj) },
  354. { MP_ROM_QSTR(MP_QSTR_send_ethernet), MP_ROM_PTR(&send_ethernet_obj) },
  355. };
  356. STATIC MP_DEFINE_CONST_DICT(wiznet5k_locals_dict, wiznet5k_locals_dict_table);
  357. const mp_obj_type_t mod_network_nic_type_wiznet5k = {
  358. { &mp_type_type },
  359. .name = MP_QSTR_WIZNET5K,
  360. .make_new = wiznet5k_make_new,
  361. .locals_dict = (mp_obj_dict_t*)&wiznet5k_locals_dict,
  362. };
  363. #endif // MICROPY_PY_WIZNET5K && MICROPY_PY_LWIP