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
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
Terminal example completed
  • Loading branch information
antohaUa committed Feb 24, 2019
commit f84f246cd91b6d9912ece85bec3ed7e6aaf73881
23 changes: 13 additions & 10 deletions blynklib.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,10 @@ def _get_msg_id(self):
self._msg_id += 1
return self._msg_id if self._msg_id <= 0xFFFF else 1

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
def _pack_msg(self, msg_type, *args, **kwargs):
msg_id = kwargs['msg_id'] if 'msg_id' in kwargs else self._get_msg_id()
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, expected_msg_type=None):
msg_args = []
Expand All @@ -100,8 +101,11 @@ def heartbeat_msg(self):
def login_msg(self, token):
return self._pack_msg(self._MSG_LOGIN, token)

def ping_reply_msg(self, msg_id, status):
return self._pack_msg(self._MSG_RSP, msg_id, status)
def ping_msg(self):
return self._pack_msg(self._MSG_PING)

def response_msg(self, *args, **kwargs):
return self._pack_msg(self._MSG_RSP, *args, **kwargs)

def virtual_write_msg(self, v_pin, *val):
return self._pack_msg(self._MSG_HW, 'vw', v_pin, *val)
Expand Down Expand Up @@ -185,10 +189,10 @@ def is_server_alive(self):
receive_delta = now - self._last_receive_time
ping_delta = now - self._last_ping_time
send_delta = now - self._last_send_time
if receive_delta > heartbeat_ms * 1.5:
if receive_delta > heartbeat_ms + (heartbeat_ms // 2):
return False
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))
if (ping_delta > heartbeat_ms // 10) and (send_delta > heartbeat_ms or receive_delta > heartbeat_ms):
self.send(self.ping_msg())
print('Heartbeat time: {}'.format(now))
self._last_ping_time = now
return True
Expand Down Expand Up @@ -315,7 +319,6 @@ def __in 10000 it__(self, func):
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

Expand All @@ -333,7 +336,7 @@ def process(self, msg_type, msg_id, msg_len, msg_args):
if msg_type == self._MSG_RSP:
print(msg_len)
elif msg_type == self._MSG_PING:
self.send(self.ping_reply_msg(msg_id, self._STATUS_SUCCESS))
self.send(self.response_msg(self._STATUS_SUCCESS, msg_id=msg_id))
elif msg_type in (self._MSG_HW, self._MSG_BRIDGE):
if len(msg_args) >= 2:
if msg_args[0] == 'vw':
Expand Down
102 changes: 84 additions & 18 deletions examples/06_terminal_widget.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,97 @@
# todo add caption and finish
"""
[TERMINAL WIDGET EXAMPLE] ==========================================================================================

Environment prepare:
In your Blynk App project:
- add "Terminal" widget,
- bind it to Virtual Pin V6,
- add input line option in widget settings
- Run the App (green triangle in the upper right corner).
- define your auth token for current example
- optionally you can define your own "ALLOWED_COMMANDS_LIST"
- run current example


This started program will periodically call and execute event handler "write_virtual_pin_handler".
In App Terminal widget you can type commands. If command present in allowed list, script will try
to execute it in current running environment and will send back to terminal execution results.
Additionally can be used 'help' command to get in terminal list of available commands.

Schema:
=====================================================================================================================
+-----+ +-----------+ +--------------+ +--------------+
| | | | | | | |
| env | | blynk lib | | blynk server | | blynk app |
| | | | | virtual pin | | |
| | | | | | | |
+--+--+ +-----+-----+ +------+-------+ +-------+------+
| | | |
| | | write command from terminal widget |
| | | |
| | +<-----------------------------------+
| event handler | write event to hw from server | |
| (user function) | | |
| exec +-----------<------------------------------------+ |
+<----------+ | | |
| | | write cmd out back to pin | |
+---------->+--------->------------------------------------->+ |
| | | was pin updated? |
| | +<-----------------------------------+
| | | |
| | | |
| | | take vpin data to widget output |
| | | |
| | +----------------------------------->+
| | | |
+ + + +

=====================================================================================================================
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 time
import blynklib
import subprocess

BLYNK_AUTH = 'YourAuthToken'
USB_DEV_PATTERN = 'Linux'

blynk = blynklib.Blynk(BLYNK_AUTH)

# last command in example - just to show error handling
ALLOWED_COMMANDS_LIST = ['ls', 'lsusb', 'ip a', 'ip abc']

@blynk.handle_event("connect")
def connect_handler():
print('smth')
blynk.virtual_write(22, 'Command22:')
blynk = blynklib.Blynk(BLYNK_AUTH)


@blynk.handle_event('write V22')
@blynk.handle_event('write V6')
def write_handler(pin, values):
if values and values[0] == u'lsusb':
found_usb_dev = subprocess.check_output("lsusb")
dev_list = found_usb_dev.split('\n')
target_dev_list = [dev_rec for dev_rec in dev_list if USB_DEV_PATTERN in dev_rec]
print('{}'.format(target_dev_list))
print('=' * 20)
# todo understand why this is not working always
blynk.virtual_write(22, 'USB: 123\n')
header = ''
result = ''
delimiter = '{}\n'.format('=' * 30)
if values and values[0] in ALLOWED_COMMANDS_LIST:
cmd_params = values[0].split(' ')
try:
result = subprocess.check_output(cmd_params).decode('utf-8')
header = '[output]\n'
except subprocess.CalledProcessError as exe_err:
header = '[error]\n'
result = 'Return Code: {}\n'.format(exe_err.returncode)
except Exception as g_err:
print("Command caused '{}'".format(g_err))
elif values and values[0] == 'help':
header = '[help -> allowed commands]\n'
result = '{}\n'.format('\n'.join(ALLOWED_COMMANDS_LIST))

# communicate with terminal if help or some allowed command
if result:
output = '{}{}{}{}'.format(header, delimiter, result, delimiter)
print(output)
blynk.virtual_write(pin, output)
blynk.virtual_write(pin, '\n')


###########################################################
Expand Down
0