10000 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 'handle_event' decorator support
  • Loading branch information
antohaUa committed Feb 14, 2019
commit 1fb6dc49c21a951f6bee81ee0c37f3c5afe1c07d
119 changes: 43 additions & 76 deletions BlynkLib.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ def ticks_ms():
return getattr(time, 'ticks_ms', lambda: int(time.time() * 1000))()


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


LOGO = """
Expand All @@ -41,12 +41,6 @@ class BlynkException(Exception):
pass


class VrPin:
def __init__(self, read=None, write=None):
self.read = read
self.write = write


class Protocol(object):
MSG_RSP = 0
MSG_LOGIN = 2
Expand Down Expand Up @@ -78,20 +72,26 @@ 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])
if msg_id == 0:
raise BlynkException('invalid msg_id == 0')
elif h_data >= self.MAX_CMD_BUFFER:
raise BlynkException('Command too long. Length = {}'.format(h_data))
elif expected_msg_type is not None and msg_type != expected_msg_type:
raise BlynkException('Not expected msg_type={} captured'.format(msg_type))
elif msg_type in (self.MSG_RSP, self.MSG_PING, self.MSG_HW, self.MSG_BRIDGE, self.MSG_INTERNAL):
elif msg_type in (self.MSG_RSP, self.MSG_PING, self.MSG_INTERNAL):
pass
elif msg_type in (self.MSG_HW, self.MSG_BRIDGE):
msg_args = self._parse_msg_body(rsp_data[self.MSG_HEAD_LEN: self.MSG_HEAD_LEN + h_data])
else:
raise BlynkException('Unknown message type received "{}"'.format(msg_type))
extra_data = rsp_data[self.MSG_HEAD_LEN: self.MSG_HEAD_LEN + h_data]
return msg_type, msg_id, h_data, extra_data
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',
Expand All @@ -109,30 +109,6 @@ def virtual_write_msg(self, v_pin, *val):
def virtual_sync_msg(self, *pins):
return self._pack_msg(self.MSG_HW_SYNC, 'vr', *pins)

# todo review
# def VIRTUAL_READ(blynk, pin):
# class Decorator:
# def __init__(self, func):
# self.func = func
# blynk._vr_pins[pin] = VrPin(func, None)
#
# def __call__(self):
# return self.func()
#
# return Decorator

# todo review
# def VIRTUAL_WRITE(blynk, pin):
# class Decorator:
# def __init__(self, func):
# self.func = func
# blynk._vr_pins[pin] = VrPin(None, func)
#
# def __call__(self):
# return self.func()
#
# return Decorator


class Connection(Protocol):
SOCK_MIN_TIMEOUT = 1 # 1 second
Expand Down Expand Up @@ -198,7 +174,7 @@ def is_server_alive(self):
if (ping_delta > heartbeat_ms / 10) and (send_delta > heartbeat_ms or receive_delta > heartbeat_ms):
self.send(self.ping_reply_msg(self._get_msg_id(), 0))
# todo remove
print('Ping {}-{}'.format(now, self._last_ping_time))
print('Heartbeat time: {}'.format(now))
self._last_ping_time = now
return True

Expand All @@ -223,7 +199,7 @@ def _authenticate(self):
rsp_data = self.receive(self.MAX_CMD_BUFFER, timeout=self.SOCK_MAX_TIMEOUT)
if not rsp_data:
raise BlynkException('Blynk authentication timed out')
msg_type, msg_id, status, _ = self.parse_response(rsp_data, expected_msg_type=self.MSG_RSP)
_, _, status, _ = self.parse_response(rsp_data, expected_msg_type=self.MSG_RSP)
if status != self.STATUS_SUCCESS:
raise BlynkException('Blynk authentication failed')
self.state = self.STATE_AUTHENTICATED
Expand All @@ -234,7 +210,7 @@ def _set_heartbeat(self):
rsp_data = self.receive(self.MAX_CMD_BUFFER, timeout=self.SOCK_MAX_TIMEOUT)
if not rsp_data:
raise BlynkException('Heartbeat reply timeout')
msg_type, msg_id, status, _ = self.parse_response(rsp_data, expected_msg_type=self.MSG_RSP)
_, _, status, _ = self.parse_response(rsp_data, expected_msg_type=self.MSG_RSP)
if status != self.STATUS_SUCCESS:
raise BlynkException('Heartbeat operation status= {}'.format(status))
print("Heartbeat period = {} seconds. Happy Blynking!\n".format(self.HEARTBEAT_PERIOD))
Expand Down Expand Up @@ -266,7 +242,7 @@ def disconnect(self, err_msg=None):
@param err_msg: error message to print. Optional parameter
@return: None
"""
if type(self.socket) == socket.socket:
if isinstance(self.socket, socket.socket):
self.socket.close()
self.state = self.STATE_DISCONNECTED
if err_msg:
Expand Down Expand Up @@ -295,6 +271,7 @@ def __init__(self, token, server=BLYNK_SERVER, port=BLYNK_HTTP_PORT, ssl=True):
self._last_receive_time = self._start_time
self._last_send_time = self._start_time
self._last_ping_time = self._start_time
self.events = {}
print(LOGO)

def config(self, token, server=BLYNK_SERVER, port=BLYNK_HTTP_PORT, ssl=False):
Expand Down Expand Up @@ -328,38 +305,54 @@ def virtual_sync(self, *v_pin):
"""
return self.send(self.virtual_sync_msg(*v_pin))

# todo think about name
def process(self, msg_type, msg_id, msg_len, extra_data):
def handle_event(blynk, event_name):
class Decorator(object):
def __init__(self, func):
self.func = func
blynk.events[event_name] = func

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

return Decorator

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

def process(self, msg_type, msg_id, msg_len, msg_args):
if msg_type == self.MSG_RSP:
# todo add status handling maybe
print(msg_len)
elif msg_type == self.MSG_PING:
self.send(self.ping_reply_msg(msg_id, self.STATUS_SUCCESS))
elif msg_type in (self.MSG_HW, self.MSG_BRIDGE):
if extra_data:
# todo here put real logic
print('Captured data {}'.format(extra_data))
# self._handle_hw(rsp_data)
if len(msg_args) >= 2:
if msg_args[0] == 'vw':
# todo think about V* values
self.call_handler("write V{}".format(msg_args[1]), msg_args[1], msg_args[2:])
elif msg_args[0] == 'vr':
self.call_handler("read V{}".format(msg_args[1]), msg_args[1])
elif msg_type == self.MSG_INTERNAL:
pass
if len(msg_args) >= 2:
self.call_handler("internal_{}".format(msg_args[1]), msg_args[2:])

def run(self):
"""
This function should be called frequently to process incoming commands
and perform housekeeping of Blynk connection.
@return:
"""
# todo out queue and input queues
# todo add keyboard interrupt
if not self.connected():
self.connect()
else:
try:
rsp_data = self.receive(self.MAX_CMD_BUFFER, self.SOCK_CONNECTION_TIMEOUT)
self._last_receive_time = ticks_ms()
if rsp_data:
msg_type, msg_id, h_data, extra_data = self.parse_response(rsp_data)
self.process(msg_type, msg_id, h_data, extra_data)
msg_type, msg_id, h_data, msg_args = self.parse_response(rsp_data)
self.process(msg_type, msg_id, h_data, msg_args)
if not self.is_server_alive():
self.disconnect('Blynk server is offline')
except KeyboardInterrupt:
Expand All @@ -368,29 +361,3 @@ def run(self):
except Exception as g_exc:
print(g_exc)
self.disconnect(g_exc)

# todo remove
# def run1(self):
# self.connect(timeout=20)
# self.virtual_write(4, 127)
# val = self.virtual_sync(4)
# print(val)
# rsp_data = self.receive(self.MAX_CMD_BUFFER, 10)
# if rsp_data:
# msg_type, msg_id, h_data, extra_data = self.parse_response(rsp_data)
# print(msg_type, msg_id, h_data, extra_data)


# todo remove this test block after all
if __name__ == "__main__":
with open('TOKEN.txt') as t_file:
auth_t = t_file.readline().strip()
BLYNK = Blynk(auth_t, port=80, ssl=False)
BLYNK.config(auth_t, server="blynk-cloud.com", port=80, ssl=False)
# BLYNK.connect(timeout=10)
# print(BLYNK.connected())
# BLYNK.disconnect('Testing disconnect')
# print(BLYNK.connected())
while True:
BLYNK.run()
# BLYNK.run1()
36 changes: 36 additions & 0 deletions examples/write_virtual_pin_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""
Blynk is a platform with iOS and Android apps to control
Arduino, Raspberry Pi and the likes over the Internet.
You can easily build graphic interfaces for all your
projects by simply dragging and dropping widgets.
Downloads, docs, tutorials: http://www.blynk.cc
Sketch generator: http://examples.blynk.cc
Blynk community: http://community.blynk.cc
Social networks: http://www.fb.com/blynkapp
http://twitter.com/blynk_app
This example shows how to display custom data on the widget.
In your Blynk App project:
Add a Value Display widget,
bind it to Virtual Pin V2,
set the read frequency to 1 second.
Run the App (green triangle in the upper right corner).
It will automagically call v2_read_handler.
Calling virtual_write updates widget value.
"""

import BlynkLib

BLYNK_AUTH = 'YourAuthToken'

# initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH)


# register handler for virtual pins
@blynk.handle_event("write V11")
def write_vpin_handler(pin, value):
print("{}\n[USER_WRITE_HANDLER] Pin: V{} Value: {}\n{}".format("=" * 50, pin, value, "=" * 50))


while True:
blynk.run()
0