8000 Merge to master by antohaUa · Pull Request #1 · blynkkk/lib-python · GitHub
[go: up one dir, main page]

Skip to content
This repository was archived by the owner on May 7, 2025. It is now read-only.

Merge to master #1

Merged
merged 32 commits into
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
eb8cc90
Added initial raw base of python lib
antohaUa Feb 11, 2019
f9bf043
Added protocol error handling
antohaUa Feb 12, 2019
dc11b18
Small changes to decrease get time operations
Feb 13, 2019
5168563
Added license and copyright
antohaUa Feb 13, 2019
a29c4fb
Added virtual_pin_sync and socket timeout
antohaUa Feb 13, 2019
1fb6dc4
Added 'handle_event' decorator support
antohaUa Feb 14, 2019
358d30d
First working examples with docs
antohaUa Feb 15, 2019
817ddfc
Added flow schema to examples
antohaUa Feb 16, 2019
a80da43
Added flow schema to examples
antohaUa Feb 16, 2019
a8604e1
added on_connect/on_disconnect events and example; changed module nam…
antohaUa Feb 17, 2019
a2ff69a
Added email call and example for it.
antohaUa Feb 17, 2019
eb382cb
raw items adding for micropython support
Feb 20, 2019
01716fb
Additions for micropython compatibility
antohaUa Feb 20, 2019
12322cd
Added set_property and notify
antohaUa Feb 21, 2019
66a0f70
Corrections for p2/micropython compatibility; terminal raw example
Feb 22, 2019
2686b9f
Docs placed to separate file
antohaUa Feb 23, 2019
f84f246
Terminal example completed
antohaUa Feb 24, 2019
ef86115
small corrections for print strings
Feb 25, 2019
5f0b35f
Weather station PI3b+ example
antohaUa Feb 25, 2019
ec735c7
added how-to description for weather example
Feb 26, 2019
e91597b
Added heartbeat and max_cmd_buffer to init
antohaUa Feb 26, 2019
84877df
refactoring and optimization
Feb 27, 2019
e11189d
esp32 compatibility
antohaUa Feb 27, 2019
a582aab
Added touch button esp32 test
antohaUa Feb 28, 2019
30bbddc
code compressing
Mar 1, 2019
fb7b237
Started to write project doc
antohaUa Mar 1, 2019
5abd6a0
Added local installer and tester
antohaUa Mar 2, 2019
d3af19f
Added Project documentation
antohaUa Mar 2, 2019
ee5c34a
Added esp32 documentation
antohaUa Mar 3, 2019
b1e0db4
Corrections after review
antohaUa Mar 3, 2019
0ef2327
Added tweet call and test
Mar 4, 2019
e02fee0
Create package create preparations
antohaUa Mar 4, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Additions for micropython compatibility
  • Loading branch information
antohaUa committed Feb 20, 2019
commit 01716fbd461208416bb92192fcfd6af893a166e7
48 changes: 18 additions & 30 deletions blynklib.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ class BlynkException(Exception):


class Protocol(object):
# todo const should be added according
# https: // docs.micropython.org / en / latest / reference / constrained.html # execution-phase
MSG_RSP = 0
MSG_LOGIN = 2
MSG_PING = 6
Expand All @@ -78,9 +80,12 @@ class Protocol(object):
MAX_CMD_BUFFER = 1024
VIRTUAL_PIN_MAX_NUM = 32

_vr_pins = {}
_msg_id = 1

@staticmethod
def _parse_msg_body(msg_body):
return [itm.decode('ascii') for itm in msg_body.split(b'\0')]

def _get_msg_id(self):
self._msg_id += 1
return self._msg_id if self._msg_id <= 0xFFFF else 1
Expand All @@ -89,10 +94,6 @@ def _pack_msg(self, msg_type, *args):
data = ('\0'.join([str(curr_arg) for curr_arg in args])).encode('ascii')
return struct.pack('!BHH', msg_type, self._get_msg_id(), len(data)) + data

@staticmethod
def _parse_msg_body(msg_body):
return [itm.decode('ascii') for itm in msg_body.split(b'\0')]

def parse_response(self, rsp_data, expected_msg_type=None):
msg_args = []
msg_type, msg_id, h_data = struct.unpack('!BHH', rsp_data[:self.MSG_HEAD_LEN])
Expand Down Expand Up @@ -135,7 +136,6 @@ def notify_msg(self, msg):


class Connection(Protocol):
SOCK_MIN_TIMEOUT = 1 # 1 second
SOCK_MAX_TIMEOUT = 5 # 5 seconds, must be < self.HEARTBEAT_PERIOD
SOCK_CONNECTION_TIMEOUT = 0.05
SOCK_RECONNECT_DELAY = 1 # 1 second
Expand Down Expand Up @@ -172,43 +172,33 @@ def send(self, data):
curr_retry_num = 0
while curr_retry_num <= self.RETRIES_TX_MAX_NUM:
try:
curr_retry_num += 1
self._last_send_time = ticks_ms()
return self.socket.send(data)
# except (socket.error, socket.timeout):
except OSError as sock_err:
# todo remove
print(sock_err)
import os
print(os.strerror(sock_err))
except OSError as os_err:
# todo add other errors handling aka subclass of socket err
sleep_ms(self.RETRIES_TX_DELAY)
curr_retry_num += 1

# todo think about error handling
def receive(self, length, timeout=0.0):
try:
rcv_buffer = b''
# self.socket.settimeout(timeout)
self._set_socket_timeout(timeout)
rcv_buffer += self.socket.recv(length)
if len(rcv_buffer) >= length:
rcv_buffer = rcv_buffer[:length]
return rcv_buffer
# except socket.timeout:
except OSError as os_err:
print(os_err)
import os
print(os.strerror(os_err))
# todo we need prove this socket_timeout value form poller?
if int(os_err) in (self.ERR_EAGAIN, self.ERR_ETIMEDOUT):
# todo add as constant
if str(os_err) == 'timed out':
return b''
if isinstance(os_err, int):
# todo we need prove this socket_timeout value from poller?
# todo remove
print("OSError value = {}".format(int(os_err)))
if int(os_err) in (self.ERR_EAGAIN, self.ERR_ETIMEDOUT):
return b''
raise
# if s_err.args[0] == self.SOCK_EAGAIN:
# return b''
# return b''
# except socket.error as s_err:
# if s_err.args[0] == self.SOCK_EAGAIN:
# return b''
# raise

def is_server_alive(self):
now = ticks_ms()
Expand All @@ -233,8 +223,6 @@ def _get_socket(self, ssl_flag):
# todo add ssl support
raise NotImplementedError
self.socket.connect(socket.getaddrinfo(self.server, self.port)[0][4])
# todo add micropython support
# self.socket.settimeout(self.SOCK_CONNECTION_TIMEOUT)
self._set_socket_timeout(self.SOCK_CONNECTION_TIMEOUT)
print('Blynk connection socket created')
except Exception as g_exc:
Expand Down Expand Up @@ -341,7 +329,7 @@ def disconnect(self, err_msg=None):
@param err_msg: error message to print. Optional parameter
@return: None
"""
if isinstance(self.socket, socket.socket):
if self.socket is not None:
self.socket.close()
self.state = self.STATE_DISCONNECTED
if err_msg:
Expand Down
10 changes: 8 additions & 2 deletions examples/02_read_virtual_pin.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,12 @@
"""

import blynklib
import random

try:
import time
except ImportError:
# micropython support
import utime as time

BLYNK_AUTH = 'YourAuthToken'

Expand All @@ -70,7 +75,8 @@
@blynk.handle_event('read V11')
def read_virtual_pin_handler(pin):
print(READ_PRINT_MSG.format(pin))
blynk.virtual_write(pin, random.randint(0, 255))
random_value = int(time.time()) % 256 # 0-255
blynk.virtual_write(pin, random_value)


###########################################################
Expand Down
7 changes: 6 additions & 1 deletion examples/03_connect_disconnect.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,12 @@
"""

import blynklib
import time

try:
import time
except ImportError:
# micropython support
import utime as time

BLYNK_AUTH = 'YourAuthToken'

Expand Down
7 changes: 6 additions & 1 deletion examples/04_email.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,12 @@
"""

import blynklib
import time

try:
import time
except ImportError:
# micropython support
import utime as time

BLYNK_AUTH = 'YourAuthToken'
TARGET_EMAIL = 'YourTargetEmail'
Expand Down
17 changes: 17 additions & 0 deletions test/run_example.sh
53E9
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/usr/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
PROJECT_ROOT=$(readlink -f $DIR/..)
if [ ! -z "$2" ]
then
PYTHON=$1
EXAMPLE=$2
export PYTHONPATH=$PROJECT_ROOT
if [ ! -f "$EXAMPLE" ]
then
echo "'$EXAMPLE' example not found"
exit 1
fi
$PYTHON $EXAMPLE
exit 0
fi
echo "Usage: ${BASH_SOURCE[0]} <python_runnable> <example_base_name>"
0