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 from development
Mar 4, 2019
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
Added heartbeat and max_cmd_buffer to init
  • Loading branch information
antohaUa committed Feb 26, 2019
commit e91597b0bbde790ad6e324c5b593cfbf983805fb
23 changes: 13 additions & 10 deletions DOCS.txt
Original file line number Diff line number Diff line change
@@ -1,27 +1,23 @@

# todo set heartbeat
# todo set input buffer max
# todo to think about logging globally
# todo separate in log re-connect events
# todo print list of registered events

# todo tweet call
# todo MSG_REDIRECT = 41 ??
# todo MSG_DBG_PRINT = 55 ??
# todo add debug response statuses parse operation
# todo lowercase for event names

# todo add status handling maybe for process RSP message
# todo add ssl support
# todo remove heartbeat printing and event printing

# todo virtual_write/read pin should be int


# todo add invalid auth token STA_INVALID_TOKEN =(9)
# def _authenticate(self):
# todo eval certain repetitive expressions
# review constants
# todo review error handling in user callbacks


# todo MSG_EVENT_LOG = 64
# todo MSG_REDIRECT = 41 ??
# todo MSG_DBG_PRINT = 55 ??
######################################################################################################
# https://docs.micropython.org/en/latest/reference/constrained.html#execution-phase

Expand All @@ -45,6 +41,13 @@ gc.mem_free()
10843
6338

# todo do we need config call ?
#============================================================================
def config(self, token, server=BLYNK_SERVER, port=BLYNK_HTTP_PORT, ssl=False):
self.token = token
self.server = server
self.port = port
self.ssl = ssl

#=============================================================================
# def connected(self):
Expand Down
96 changes: 41 additions & 55 deletions blynklib.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,22 @@
VERSION = '0.2.2'

try:
from micropython import const
import usocket as socket
import utime as time
import ustruct as struct
import uselect as select
from micropython import const

IOError = OSError
except ImportError:
const = lambda x: x
import socket
import time
import struct
import select

try:
type(IOError)
except NameError:
IOError = OSError


def ticks_ms():
return getattr(time, 'ticks_ms', lambda: int(time.time() * 1000))()


def sleep_ms(m_sec):
return getattr(time, 'sleep_ms', lambda x: time.sleep(x // 1000))(m_sec)

const = lambda x: x
ticks_ms = lambda: int(time.time() * 1000)
sleep_ms = lambda m_sec: time.sleep(m_sec // 1000)

LOGO = """
___ __ __
Expand Down Expand Up @@ -57,15 +48,13 @@ class Protocol(object):
_MSG_HEAD_LEN = const(5)
_STATUS_INVALID_TOKEN = const(9)
_STATUS_SUCCESS = const(200)
_HEARTBEAT_PERIOD = const(10)
_MAX_CMD_BUFFER = const(1024)
_VIRTUAL_PIN_MAX_NUM = const(32)

_msg_id = 1

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

def _get_msg_id(self):
self._msg_id += 1
Expand All @@ -76,12 +65,12 @@ def _pack_msg(self, msg_type, *args, **kwargs):
data = ('\0'.join([str(curr_arg) for curr_arg in args])).encode('utf8')
return struct.pack('!BHH', msg_type, msg_id, len(data)) + data

def parse_response(self, rsp_data):
def parse_response(self, rsp_data, max_msg_buffer):
msg_args = []
msg_type, msg_id, h_data = struct.unpack('!BHH', rsp_data[:self._MSG_HEAD_LEN])
if msg_id == 0:
raise BlynkException('invalid msg_id == 0')
elif h_data >= self._MAX_CMD_BUFFER:
elif h_data >= max_msg_buffer:
raise BlynkException('Command too long. Length = {}'.format(h_data))
elif msg_type in (self._MSG_RSP, self._MSG_PING, self._MSG_INTERNAL):
pass
Expand All @@ -91,9 +80,9 @@ def parse_response(self, rsp_data):
raise BlynkException("Unknown message type: '{}'".format(msg_type))
return msg_type, msg_id, h_data, msg_args

def heartbeat_msg(self):
return self._pack_msg(self._MSG_INTERNAL, 'ver', VERSION, 'buff-in', self._MAX_CMD_BUFFER, 'h-beat',
self._HEARTBEAT_PERIOD, 'dev', 'python')
def heartbeat_msg(self, heartbeat, max_msg_buffer):
return self._pack_msg(self._MSG_INTERNAL, 'ver', VERSION, 'buff-in', max_msg_buffer, 'h-beat', heartbeat,
'dev', 'python')

def login_msg(self, token):
return self._pack_msg(self._MSG_LOGIN, token)
Expand Down Expand Up @@ -180,9 +169,9 @@ def receive(self, length, timeout=0.0):
return b''
raise

def is_server_alive(self):
def is_server_alive(self, heartbeat):
now = ticks_ms()
heartbeat_ms = self._HEARTBEAT_PERIOD * 1000
heartbeat_ms = heartbeat * 1000
receive_delta = now - self._last_receive_time
ping_delta = now - self._last_ping_time
send_delta = now - self._last_send_time
Expand All @@ -204,32 +193,32 @@ def _get_socket(self, ssl_flag):
self._set_socket_timeout(self._SOCK_CONNECTION_TIMEOUT)
print('\nNew connection socket created')
except Exception as g_exc:
raise BlynkException('Connection with the Blynk servers failed: {}'.format(g_exc))
raise BlynkException('Connection with the Blynk server failed: {}'.format(g_exc))

def _authenticate(self):
def _authenticate(self, max_msg_buffer):
print('Authenticating device...')
self.state = self._STATE_AUTHENTICATING
self.send(self.login_msg(self.token))
rsp_data = self.receive(self._MAX_CMD_BUFFER, timeout=self._SOCK_MAX_TIMEOUT)
rsp_data = self.receive(max_msg_buffer, timeout=self._SOCK_MAX_TIMEOUT)
if not rsp_data:
raise BlynkException('Auth stage timed out')
_, _, status, _ = self.parse_response(rsp_data)
raise BlynkException('Auth stage timeout')
_, _, status, _ = self.parse_response(rsp_data, max_msg_buffer)
if status != self._STATUS_SUCCESS:
if status == self._STATUS_INVALID_TOKEN:
raise BlynkException('Invalid Auth Token')
raise BlynkException('Auth stage failed. Status={}'.format(status))
self.state = self._STATE_AUTHENTICATED
print('Access granted.')

def _set_heartbeat(self):
self.send(self.heartbeat_msg())
rsp_data = self.receive(self._MAX_CMD_BUFFER, timeout=self._SOCK_MAX_TIMEOUT)
def _set_heartbeat(self, heartbeat, max_msg_buffer):
self.send(self.heartbeat_msg(heartbeat, max_msg_buffer))
rsp_data = self.receive(max_msg_buffer, timeout=self._SOCK_MAX_TIMEOUT)
if not rsp_data:
raise BlynkException('Heartbeat reply timeout')
_, _, status, _ = self.parse_response(rsp_data)
_, _, status, _ = self.parse_response(rsp_data, max_msg_buffer)
if status != self._STATUS_SUCCESS:
raise BlynkException('Set heartbeat reply code= {}'.format(status))
print("Heartbeat period = {} sec.\nHappy Blynking!\n".format(self._HEARTBEAT_PERIOD))
print("Heartbeat = {} sec. Max cmd buffer = {} bytes.".format(heartbeat, max_msg_buffer))

def connected(self):
return True if self.state == self._STATE_AUTHENTICATED else False
Expand All @@ -241,18 +230,20 @@ class Blynk(Connection):
CONNECT_CALL_TIMEOUT = const(30) # 30sec

VPIN_WILDCARD = '*'
READ_VPIN_EVENT_BASENAME = 'read V'
WRITE_VPIN_EVENT_BASENAME = 'write V'
READ_VPIN_EVENT_BASENAME = 'read v'
WRITE_VPIN_EVENT_BASENAME = 'write v'
INTERNAL_EVENT_BASENAME = 'internal_'
CONNECT_EVENT = 'connect'
DISCONNECT_EVENT = 'disconnect'
READ_ALL_VPIN_EVENT = '{}{}'.format(READ_VPIN_EVENT_BASENAME, VPIN_WILDCARD)
WRITE_ALL_VPIN_EVENT = '{}{}'.format(WRITE_VPIN_EVENT_BASENAME, VPIN_WILDCARD)

def __init__(self, token, server=BLYNK_SERVER, port=BLYNK_HTTP_PORT, ssl=False):
def __init__(self, token, server=BLYNK_SERVER, port=BLYNK_HTTP_PORT, heartbeat=10, max_msg_buffer=1024, ssl=False):
self.token = token
self.server = server
self.port = port
self.heartbeat = heartbeat
self.max_msg_buffer = max_msg_buffer
self.ssl = ssl
self.state = self._STATE_DISCONNECTED
self._start_time = ticks_ms()
Expand All @@ -262,20 +253,15 @@ def __init__(self, token, server=BLYNK_SERVER, port=BLYNK_HTTP_PORT, ssl=False):
self.events = {}
print(LOGO)

def config(self, token, server=BLYNK_SERVER, port=BLYNK_HTTP_PORT, ssl=False):
self.token = token
self.server = server
self.port = port
self.ssl = ssl

def connect(self, timeout=CONNECT_CALL_TIMEOUT):
end_time = time.time() + timeout
while not self.connected():
try:
if self.state == self._STATE_DISCONNECTED:
self._get_socket(self.ssl_flag)
self._authenticate()
self._set_heartbeat()
self._authenticate(self.max_msg_buffer)
self._set_heartbeat(self.heartbeat, self.max_msg_buffer)
print('Registered events:\n{}\nHappy Blynking!\n'.format(self.events.keys()))
self.call_handler(self.CONNECT_EVENT)
return True
except BlynkException as b_exc:
Expand Down Expand Up @@ -314,21 +300,21 @@ class Decorator(object):
def __init__(self, func):
self.func = func
# wildcard 'read V*' and 'write V*' events handling
if str(event_name) in (blynk.READ_ALL_VPIN_EVENT, blynk.WRITE_ALL_VPIN_EVENT):
if str(event_name).lower() in (blynk.READ_ALL_VPIN_EVENT, blynk.WRITE_ALL_VPIN_EVENT):
event_base_name = str(event_name).split(blynk.VPIN_WILDCARD)[0]
for i in range(1, blynk._VIRTUAL_PIN_MAX_NUM + 1):
blynk.events['{}{}'.format(event_base_name, i)] = func
blynk.events['{}{}'.format(event_base_name.lower(), i)] = func
else:
blynk.events[str(event_name)] = func
blynk.events[str(event_name).lower()] = func

def __call__(self):
return self.func()

return Decorator

def call_handler(self, event, *args, **kwargs):
print("Event: ['{}'] -> {}".format(event, args))
if event in self.events.keys():
print("Event: ['{}'] -> {}".format(event, args))
self.events[event](*args, **kwargs)

def process(self, msg_type, msg_id, msg_len, msg_args):
Expand All @@ -339,10 +325,10 @@ def process(self, msg_type, msg_id, msg_len, msg_args):
elif msg_type in (self._MSG_HW, self._MSG_BRIDGE):
if len(msg_args) >= 2:
if msg_args[0] == 'vw':
self.call_handler("{}{}".format(self.WRITE_VPIN_EVENT_BASENAME, msg_args[1]), msg_args[1],
self.call_handler("{}{}".format(self.WRITE_VPIN_EVENT_BASENAME, msg_args[1]), int(msg_args[1]),
msg_args[2:])
elif msg_args[0] == 'vr':
self.call_handler("{}{}".format(self.READ_VPIN_EVENT_BASENAME, msg_args[1]), msg_args[1])
self.call_handler("{}{}".format(self.READ_VPIN_EVENT_BASENAME, msg_args[1]), int(msg_args[1]))
elif msg_type == self._MSG_INTERNAL:
if len(msg_args) >= 2:
self.call_handler("{}{}".format(self.INTERNAL_EVENT_BASENAME, msg_args[1]), msg_args[2:])
Expand All @@ -352,12 +338,12 @@ def run(self):
self.connect()
else:
try:
rsp_data = self.receive(self._MAX_CMD_BUFFER, self._SOCK_CONNECTION_TIMEOUT)
rsp_data = self.receive(self.max_msg_buffer, self._SOCK_CONNECTION_TIMEOUT)
self._last_receive_time = ticks_ms()
if rsp_data:
msg_type, msg_id, h_data, msg_args = self.parse_response(rsp_data)
msg_type, msg_id, h_data, msg_args = self.parse_response(rsp_data, self.max_msg_buffer)
self.process(msg_type, msg_id, h_data, msg_args)
if not self.is_server_alive():
if not self.is_server_alive(self.heartbeat):
self.disconnect('Blynk server is offline')
except KeyboardInterrupt:
raise
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# -*- coding: utf-8 -*-
"""
[WEATHER STATION EXAMPLE (DHT22; BMP180 sensors) PI3b+] =============================================================

Expand Down Expand Up @@ -123,11 +124,11 @@ class Counter:


BLYNK_AUTH = 'YourAuthToken'
blynk = blynklib.Blynk(BLYNK_AUTH)
blynk = blynklib.Blynk(BLYNK_AUTH, heartbeat=15, max_msg_buffer=512)

T_CRI_VALUE = 20.0 # 20.0°C
T_CRI_COLOR = '#c0392b'
T_CRI_MSG = 'Low TEMP!!!'
T_CRI_COLOR = '#c0392b'

T_COLOR = '#f5b041'
H_COLOR = '#85c1e9'
Expand Down
0