|
1 | 1 | /*
|
2 | 2 | * This file is part of the Micro Python project, http://micropython.org/
|
3 | 3 | *
|
| 4 | + * Development of the code in this file was sponsored by Microbric Pty Ltd |
| 5 | + * and Mnemote Pty Ltd |
| 6 | + * |
4 | 7 | * The MIT License (MIT)
|
5 | 8 | *
|
6 |
| - * Copyright (c) 2016 Nick Moore |
| 9 | + * Copyright (c) 2016, 2017 Nick Moore @mnemote |
| 10 | + * |
7 | 11 | * Based on extmod/modlwip.c
|
8 | 12 | * Copyright (c) 2013, 2014 Damien P. George
|
9 | 13 | * Copyright (c) 2015 Galen Hazelwood
|
@@ -60,6 +64,11 @@ STATIC mp_obj_t socket_close(const mp_obj_t arg0) {
|
60 | 64 | }
|
61 | 65 | STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_close_obj, socket_close);
|
62 | 66 |
|
| 67 | +static int exception_from_errno(int _errno) { |
| 68 | + // XXX add more specific exceptions |
| 69 | + mp_raise_OSError(_errno); |
| 70 | +} |
| 71 | + |
63 | 72 | static int _socket_getaddrinfo2(const mp_obj_t host, const mp_obj_t portx, struct addrinfo **resp) {
|
64 | 73 | const struct addrinfo hints = {
|
65 | 74 | .ai_family = AF_INET,
|
@@ -167,21 +176,25 @@ STATIC mp_obj_t socket_setblocking(const mp_obj_t arg0, const mp_obj_t arg1) {
|
167 | 176 | }
|
168 | 177 | STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_setblocking_obj, socket_setblocking);
|
169 | 178 |
|
170 |
| -STATIC mp_obj_t socket_recv(const mp_obj_t arg0) { |
| 179 | +STATIC mp_obj_t socket_recv(mp_uint_t n_args, const mp_obj_t *args) { |
171 | 180 | byte buf[1024];
|
172 |
| - socket_obj_t *self = MP_OBJ_TO_PTR(arg0); |
173 |
| - int x = lwip_recvfrom(self->fd, buf, sizeof(buf), 0, NULL, NULL); |
| 181 | + socket_obj_t *self = MP_OBJ_TO_PTR(args[0]); |
| 182 | + size_t len = (n_args > 1) ? MIN(mp_obj_get_int(args[1]), sizeof(buf)) : sizeof(buf); |
| 183 | + int x = lwip_recvfrom(self->fd, buf, len, 0, NULL, NULL); |
174 | 184 | if (x >= 0) return mp_obj_new_bytes(buf, x);
|
175 |
| - return mp_const_none; |
| 185 | + if (errno == EWOULDBLOCK) return b''; |
| 186 | + exception_from_errno(errno); |
176 | 187 | }
|
177 |
| -STATIC MP_DEFINE_CONST_FUN_OBJ_1(socket_recv_obj, socket_recv); |
| 188 | +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_recv_obj, 1, 2, socket_recv); |
178 | 189 |
|
179 | 190 | STATIC mp_obj_t socket_send(const mp_obj_t arg0, const mp_obj_t arg1) {
|
180 | 191 | socket_obj_t *self = MP_OBJ_TO_PTR(arg0);
|
181 | 192 | mp_uint_t datalen;
|
182 | 193 | const char *data = mp_obj_str_get_data(arg1, &datalen);
|
183 | 194 | int x = lwip_write(self->fd, data, datalen);
|
184 |
| - return mp_obj_new_int(x); |
| 195 | + if (x >= 0) return mp_obj_new_int(x); |
| 196 | + if (errno == EWOULDBLOCK) return mp_obj_new_int(0); |
| 197 | + exception_from_errno(errno); |
185 | 198 | }
|
186 | 199 | STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_send_obj, socket_send);
|
187 | 200 |
|
|
0 commit comments