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 set_property and notify
  • Loading branch information
antohaUa committed Feb 21, 2019
commit 12322cd857dec743a4b0b052663769b0622c98b0
61 changes: 31 additions & 30 deletions blynklib.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,14 @@

VERSION = '0.2.2'

# todo change globally logging
# todo separate in log re-connect
# todo to think about logging globally
# todo separate in log re-connect events
# todo print list of registered events
# todo add to examples config call with logger
# todo notification event
# todo tweet call
# todo notify call
# 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'
# for itm in [MPY_SUPPORT_INSTRUCTION_1]:
# try:
# exec itm
# except ImportError:
# continue
# except AttributeError:
# pass

# micropython compatibility
try:
import socket
Expand Down Expand Up @@ -60,7 +47,7 @@ class BlynkException(Exception):

class Protocol(object):
# todo const should be added according
# https: // docs.micropython.org / en / latest / reference / constrained.html # execution-phase
# https://docs.micropython.org/en/latest/reference/constrained.html#execution-phase
MSG_RSP = 0
MSG_LOGIN = 2
MSG_PING = 6
Expand Down Expand Up @@ -124,7 +111,6 @@ def ping_reply_msg(self, msg_id, status):
def virtual_write_msg(self, v_pin, *val):
return self._pack_msg(self.MSG_HW, 'vw', v_pin, *val)

# todo check multiple values support
def virtual_sync_msg(self, *pins):
return self._pack_msg(self.MSG_HW_SYNC, 'vr', *pins)

Expand All @@ -134,6 +120,9 @@ def email_msg(self, to, subject, body):
def notify_msg(self, msg):
return self._pack_msg(self.MSG_NOTIFY, msg)

def set_property_msg(self, pin, prop, *val):
return self._pack_msg(self.MSG_PROPERTY, pin, prop, *val)


class Connection(Protocol):
SOCK_MAX_TIMEOUT = 5 # 5 seconds, must be < self.HEARTBEAT_PERIOD
Expand All @@ -149,6 +138,7 @@ class Connection(Protocol):
RETRIES_TX_DELAY = 2
RETRIES_TX_MAX_NUM = 3
TASK_PERIOD_RES = 50 # 50ms
SOCK_TIMEOUT_MSG = 'timed out'

token = None
server = None
Expand All @@ -175,11 +165,9 @@ def send(self, data):
curr_retry_num += 1
self._last_send_time = ticks_ms()
return self.socket.send(data)
except OSError as os_err:
# todo add other errors handling aka subclass of socket err
except (IOError, OSError):
sleep_ms(self.RETRIES_TX_DELAY)

# todo think about error handling
def receive(self, length, timeout=0.0):
try:
rcv_buffer = b''
Expand All @@ -188,15 +176,11 @@ def receive(self, length, timeout=0.0):
if len(rcv_buffer) >= length:
rcv_buffer = rcv_buffer[:length]
return rcv_buffer
except OSError as os_err:
# todo add as constant
if str(os_err) == 'timed out':
except (IOError, OSError) as err:
if str(err) == self.SOCK_TIMEOUT_MSG:
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):
if isinstance(err, int):
if int(err) in (self.ERR_EAGAIN, self.ERR_ETIMEDOUT):
return b''
raise

Expand Down Expand Up @@ -356,14 +340,32 @@ def virtual_sync(self, *v_pin):

def email(self, to, subject, body):
"""
Send email from your hardware to any address.
Send email from hardware to any address.
@param to: destination email address
@param subject: email subject
@param body: email body
@return: Returns the number of bytes sent
"""
return self.send(self.email_msg(to, subject, body))

def notify(self, msg):
"""
Send notification from hardware to App
@param msg: notification message
@return: Returns the number of bytes sent
"""
return self.send(self.notify_msg(msg))

def set_property(self, v_pin, property_name, *val):
"""
Set virtual pin property eg. "color", "label" etc
@param v_pin: pin number
@param property_name: name of target property
@param val: values that should be assigned for target property
@retu 8000 rn: Returns the number of bytes sent
"""
return self.send(self.set_property_msg(v_pin, property_name, *val))

def handle_event(blynk, event_name):
class Decorator(object):
def __init__(self, func):
Expand Down Expand Up @@ -404,7 +406,6 @@ def process(self, msg_type, msg_id, msg_len, msg_args):
if len(msg_args) >= 2:
self.call_handler("{}{}".format(self.INTERNAL_EVENT_BASENAME, msg_args[1]), msg_args[2:])

# todo KeyboardInterrupt handle on all layers?
def run(self):
"""
This function should be called frequently to process incoming commands
Expand Down
10 changes: 2 additions & 8 deletions examples/02_read_virtual_pin.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,7 @@
"""

import blynklib

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

BLYNK_AUTH = 'YourAuthToken'

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


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

import blynklib

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

BLYNK_AUTH = 'YourAuthToken'

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

import blynklib

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

BLYNK_AUTH = 'YourAuthToken'
TARGET_EMAIL = 'YourTargetEmail'
Expand Down
86 changes: 86 additions & 0 deletions examples/05_set_property_notify.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
"""
[SET_PROPERTY/NOTIFY EXAMPLE] ==========================================================================================

Environment prepare:
In your Blynk App project:
- add "Slider" widget,
- bind it to Virtual Pin V5,
- set values range 0-255
- add "LED" widget and assign Virtual Pin V5 to it
- add "Notification" widget to be allowed receive notifications in App
- Run the App (green triangle in the upper right corner).
- define your auth token for current example and run it


This started program will periodically call and execute event handler "write_virtual_pin_handler".
In app you can move slider that will cause LED brightness change and will send virtual write event
to current running example. Handler will set random color for virtual pin and will send notification
event to App. Virtual pin property 'color' change will cause color changes for "Slider" and "LED" widgets

Schema:
=====================================================================================================================
+-----------+ +--------------+ +--------------+
| | | | | |
| blynk lib | | blynk server | | blynk app |
| | | virtual pin | | |
| | | | | |
+-----+-----+ +------+-------+ +-------+------+
| | |
| | write event from "Slider" widget |
| | |
| +<-----------------------------------+
| | |
| | |
| | |
| | |
event handler | write event to hw from server | |
(user function) | | |
+-----------<------------------------------------+ |
| | | |
| | pin set property | pin property changed msg |
+-----+--->------------------------------------->------------------------------------>+
| | | |
| | send notification | notification widget present? |
+--->------------------------------------->------------------------------------>+
| | |
| | yes |
| +<-----------------------------------+
| | |
| | |
| +----------------------------------->+
+ + notification delivery +

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

BLYNK_AUTH = 'YourAuthToken'
blynk = blynklib.Blynk(BLYNK_AUTH)

NOTIFY_MSG = "['COLOR' = '{}']"
colors = {'#FF00FF': 'Magenta', '#00FF00': 'Lime'}


@blynk.handle_event('write V5')
def write_handler(pin, value):
current_color = random.choice(colors.keys())
blynk.set_property(pin, 'color', random.choice(colors.keys()))
blynk.notify(NOTIFY_MSG.format(colors[current_color]))
print(NOTIFY_MSG.format(colors[current_color]))


###########################################################
# infinite loop that waits for event
###########################################################
while True:
blynk.run()
0