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
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 8000
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 on_connect/on_disconnect events and example; changed module nam…
…e to be aligned with pep8
  • Loading branch information
antohaUa committed Feb 17, 2019
commit a8604e1de3240534cb312f1522dd28decd82b21d
118 changes: 72 additions & 46 deletions BlynkLib.py → blynklib.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,19 @@
import time
import sys

VERSION = '0.2.1'
VERSION = '0.2.2'


# todo change globally logging
# todo separate in log re-connect
# todo print list of registered events
# todo add to examples config call with logger
# todo notification event
# todo on connect event
# todo on disconnect event
# todo MSG_REDIRECT = 41 ??
# todo MSG_DBG_PRINT = 55 ??
# todo add debug response statuses parse operation

# todo think about why this is needed
# MPY_SUPPORT_INSTRUCTION_1 = 'import machine'
Expand Down Expand Up @@ -54,12 +63,12 @@ class Protocol(object):
MSG_PROPERTY = 19
MSG_HW = 20
MSG_EVENT_LOG = 64
# MSG_REDIRECT = 41 # TODO: not implemented
# MSG_DBG_PRINT = 55 # TODO: not implemented

MSG_HEAD_LEN = 5
STATUS_SUCCESS = 200
HEARTBEAT_PERIOD = 10
MAX_CMD_BUFFER = 1024
VIRTUAL_PIN_MAX_NUM = 32

_vr_pins = {}
_msg_id = 1
Expand Down Expand Up @@ -124,7 +133,6 @@ class Connection(Protocol):
RETRIES_TX_DELAY = 2
RETRIES_TX_MAX_NUM = 3
TASK_PERIOD_RES = 50 # 50ms
CONNECT_CALL_TIMEOUT = 30 # 30sec

token = None
server = None
Expand All @@ -136,7 +144,6 @@ class Connection(Protocol):
_last_ping_time = 0
_last_send_time = 0

# todo maybe add Blynk Error or some other return 0?
def send(self, data):
curr_retry_num = 0
while curr_retry_num <= self.RETRIES_TX_MAX_NUM:
Expand Down Expand Up @@ -215,40 +222,6 @@ def _set_heartbeat(self):
raise BlynkException('Heartbeat operation status= {}'.format(status))
print("Heartbeat period = {} seconds. Happy Blynking!\n".format(self.HEARTBEAT_PERIOD))

def connect(self, timeout=CONNECT_CALL_TIMEOUT):
"""
Function will continue trying to connect to Blynk server.
@param timeout: global function retry timeout. Default value = 30 seconds
@return: connection status
"""
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()
return True
except BlynkException as b_exc:
self.disconnect(b_exc)
sleep_ms(self.TASK_PERIOD_RES)
finally:
if time.time() >= end_time:
return False

def disconnect(self, err_msg=None):
"""
Disconnects hardware from Blynk server
@param err_msg: error message to print. Optional parameter
@return: None
"""
if isinstance(self.socket, socket.socket):
self.socket.close()
self.state = self.STATE_DISCONNECTED
if err_msg:
print('Error: {}. Connection closed'.format(err_msg))
time.sleep(self.SOCK_RECONNECT_DELAY)

def connected(self):
"""
Returns true when hardware is connected to Blynk Server, false if there is no active connection to Blynk server.
Expand All @@ -260,6 +233,16 @@ def connected(self):
class Blynk(Connection):
BLYNK_SERVER = "blynk-cloud.com"
BLYNK_HTTP_PORT = 80
CONNECT_CALL_TIMEOUT = 30 # 30sec

VPIN_WILDCARD = '*'
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 = READ_VPIN_EVENT_BASENAME + VPIN_WILDCARD
WRITE_ALL_VPIN_EVENT = WRITE_VPIN_EVENT_BASENAME + VPIN_WILDCARD

def __init__(self, token, server=BLYNK_SERVER, port=BLYNK_HTTP_PORT, ssl=True):
self.token = token
Expand Down Expand Up @@ -288,6 +271,42 @@ def config(self, token, server=BLYNK_SERVER, port=BLYNK_HTTP_PORT, ssl=False):
self.port = port
self.ssl = ssl

def connect(self, timeout=CONNECT_CALL_TIMEOUT):
"""
Function will continue trying to connect to Blynk server.
@param timeout: global function retry timeout. Default value = 30 seconds
@return: connection status
"""
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.call_handler(self.CONNECT_EVENT)
return True
except BlynkException as b_exc:
self.disconnect(b_exc)
sleep_ms(self.TASK_PERIOD_RES)
finally:
if time.time() >= end_time:
return False

def disconnect(self, err_msg=None):
"""
Disconnects hardware from Blynk server
@param err_msg: error message to print. Optional parameter
@return: None
"""
if isinstance(self.socket, socket.socket):
self.socket.close()
self.state = self.STATE_DISCONNECTED
if err_msg:
print('Error: {}. Connection closed'.format(err_msg))
time.sleep(self.SOCK_RECONNECT_DELAY)
self.call_handler(self.DISCONNECT_EVENT)

def virtual_write(self, v_pin, *val):
"""
Write data to virtual pin
Expand All @@ -300,7 +319,7 @@ def virtual_write(self, v_pin, *val):
def virtual_sync(self, *v_pin):
# todo change description
"""
Sync virtual pin/pins to get actual data. For HW this is equal to read data from virtual pin/pins operation
Sync virtual pin/pins to get actual data.
@param v_pin: single pin or multiple pins number
@return: Returns the number of bytes sent
"""
Expand All @@ -310,7 +329,14 @@ def handle_event(blynk, event_name):
class Decorator(object):
def __init__(self, func):
self.func = func
blynk.events[event_name] = func
# wildcard 'read V*' and 'write V*' events handling
if str(event_name) 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
print('Registered {}{}'.format(event_base_name, i))
else:
blynk.events[str(event_name)] = func

def __call__(self):
return self.func()
Expand All @@ -331,19 +357,19 @@ 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':
# todo think about V* values
self.call_handler("write V{}".format(msg_args[1]), msg_args[1], msg_args[2:])
self.call_handler("{}{}".format(self.WRITE_VPIN_EVENT_BASENAME, 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])
self.call_handler("{}{}".format(self.READ_VPIN_EVENT_BASENAME, msg_args[1]), msg_args[1])
elif msg_type == self.MSG_INTERNAL:
if len(msg_args) >= 2:
self.call_handler("internal_{}".format(msg_args[1]), msg_args[2:])
self.call_handler("{}{}".format(self.INTERNAL_EVENT_BASENAME, 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:
@return: None
"""
if not self.connected():
self.connect()
Expand Down
83 changes: 83 additions & 0 deletions examples/connect_disconnect_events.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
"""
[CONNECT/DISCONNECT EVENTS EXAMPLE] =================================================================

Environment prepare:
- define your auth token for current example and run it


This started program after successful connect operation will call and execute "connect event handler"
Within handler after short sleep delay blynk disconnect call will be performed that will trigger
"disconnect event handler" execution.

Schema:
=====================================================================================================
+-----------+ +--------------+
| | | |
| blynk lib | | blynk server |
| | | virtual pin |
| | | |
+-----+-----+ +------+-------+
| |
| connect/authenticate request |
+------------------------------------>+
connect handler | |
(user function) | connected successfully |
+-----------<------------------------------------+
| | |
| | disconnect request |
+--------->------------------------------------->+
| |
| |
disconnect handler | |
(user function) | disconnected successfully |
+-----------<------------------------------------+
| | |
| | |
+--------->+ |
| reconnect request |
| performed by lib automatically |
+------------------------------------>+
+ +


====================================================================================================
Additional info about blynk you can find by examining such resources:

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
=====================================================================================================
"""

import blynklib
import time

BLYNK_AUTH = 'YourAuthToken'

# initialize blynk
blynk = blynklib.Blynk(BLYNK_AUTH)

CONNECT_PRINT_MSG = """[CONNECT_EVENT]"""
DISCONNECT_PRINT_MSG = """[DISCONNECT_EVENT]"""


@blynk.handle_event("connect") 10000
def connect_handler():
print(CONNECT_PRINT_MSG)
print('Sleeping 2 sec in connect handler...')
time.sleep(2)
blynk.disconnect()


@blynk.handle_event("disconnect")
def connect_handler():
print(DISCONNECT_PRINT_MSG)
print('Sleeping 4 sec in disconnect handler...')
time.sleep(4)


# infinite loop that waits for event
while True:
blynk.run()
4 changes: 2 additions & 2 deletions examples/read_virtual_pin.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,13 @@
=====================================================================================================
"""

import BlynkLib
import blynklib
import random

BLYNK_AUTH = 'YourAuthToken'

# initialize blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH)
blynk = blynklib.Blynk(BLYNK_AUTH)

READ_PRINT_MSG = """[READ_VIRTUAL_PIN_EVENT] Pin: V{}"""

Expand Down
4 changes: 2 additions & 2 deletions examples/write_virtual_pin.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,12 @@
====================================================================================================
"""

import BlynkLib
import blynklib

BLYNK_AUTH = 'YourAuthToken'

# initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH)
blynk = blynklib.Blynk(BLYNK_AUTH)

WRITE_EVENT_PRINT_MSG = """[WRITE_VIRTUAL_PIN_EVENT] Pin: V{} Value: '{}'"""

Expand Down
0