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
small corrections for print strings
  • Loading branch information
amorozenko committed Feb 25, 2019
commit ef86115f139196a6a433b683a13adbc14a3b141e
31 changes: 27 additions & 4 deletions DOCS.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

# todo to think about logging globally
# todo separate in log re-connect events
# todo print list of registered events
Expand All @@ -6,21 +7,43 @@
# 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 status handling maybe for process RSP message
# todo add ssl support
# todo remove heartbeat printing and event printing

# todo const should be added according
# https://docs.micropython.org/en/latest/reference/constrained.html#execution-phase

# 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
######################################################################################################
# https://docs.micropython.org/en/latest/reference/constrained.html#execution-phase

gpio readall
http://wiringpi.com/download-and-install/

https://github.com/adafruit/Adafruit_Python_DHT/blob/master/examples/simpletest.py

git clone https://github.com/micropython/micropython.git
cd micropython/
make
./mpy-cross --help
./mpy-cross <input_py_file>
*.mpy file will be created that can be imported in the same way as common py libs

to use heapsize
import gc
gc.collect()
gc.mem_free()

10843
6338


#=============================================================================
# def connected(self):
"""
Expand Down
38 changes: 18 additions & 20 deletions blynklib.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
# Copyright (c) 2015-2019 Volodymyr Shymanskyy. See the file LICENSE for copying permission.
# Copyright (c) 2019 Anton Morozenko
import sys

VERSION = '0.2.2'

try:
Expand Down Expand Up @@ -36,7 +34,7 @@ def sleep_ms(m_sec):
/ _ )/ /_ _____ / /__
/ _ / / // / _ \\/ '_/
/____/_/\\_, /_//_/_/\\_\\
/___/ for Python v""" + VERSION + "\n"
/___/ for Python v{}\n""".format(VERSION)


class BlynkException(Exception):
Expand All @@ -57,6 +55,7 @@ class Protocol(object):
_MSG_HW = const(20)

_MSG_HEAD_LEN = const(5)
_STATUS_INVALID_TOKEN = const(9)
_STATUS_SUCCESS = const(200)
_HEARTBEAT_PERIOD = const(10)
_MAX_CMD_BUFFER = const(1024)
Expand All @@ -77,21 +76,19 @@ 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, expected_msg_type=None):
def parse_response(self, rsp_data):
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_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))
raise BlynkException("Unknown message type: '{}'".format(msg_type))
return msg_type, msg_id, h_data, msg_args

def heartbeat_msg(self):
Expand Down Expand Up @@ -205,7 +202,7 @@ def _get_socket(self, ssl_flag):
raise NotImplementedError
self.socket.connect(socket.getaddrinfo(self.server, self.port)[0][4])
self._set_socket_timeout(self._SOCK_CONNECTION_TIMEOUT)
print('Blynk connection socket created')
print('\nNew connection socket created')
except Exception as g_exc:
raise BlynkException('Connection with the Blynk servers failed: {}'.format(g_exc))

Expand All @@ -215,10 +212,12 @@ def _authenticate(self):
self.send(self.login_msg(self.token))
rsp_data = self.receive(self._MAX_CMD_BUFFER, timeout=self._SOCK_MAX_TIMEOUT)
if not rsp_data:
raise BlynkException('Blynk authentication timed out')
_, _, status, _ = self.parse_response(rsp_data, expected_msg_type=self._MSG_RSP)
raise BlynkException('Auth stage timed out')
_, _, status, _ = self.parse_response(rsp_data)
if status != self._STATUS_SUCCESS:
raise BlynkException('Blynk authentication failed')
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.')

Expand All @@ -227,10 +226,10 @@ 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')
_, _, status, _ = self.parse_response(rsp_data, expected_msg_type=self._MSG_RSP)
_, _, status, _ = self.parse_response(rsp_data)
if status != self._STATUS_SUCCESS:
raise BlynkException('Heartbeat operation status= {}'.format(status))
print("Heartbeat period = {} seconds. Happy Blynking!\n".format(self._HEARTBEAT_PERIOD))
raise BlynkException('Set heartbeat reply code= {}'.format(status))
print("Heartbeat period = {} sec.\nHappy Blynking!\n".format(self._HEARTBEAT_PERIOD))

def connected(self):
return True if self.state == self._STATE_AUTHENTICATED else False
Expand All @@ -247,10 +246,10 @@ class Blynk(Connection):
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
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=True):
def __init__(self, token, server=BLYNK_SERVER, port=BLYNK_HTTP_PORT, ssl=False):
self.token = token
self.server = server
self.port = port
Expand Down Expand Up @@ -291,7 +290,7 @@ def disconnect(self, err_msg=None):
self.socket.close()
self.state = self._STATE_DISCONNECTED
if err_msg:
print('Error: {}. Connection closed'.format(err_msg))
print('[ERROR]: {}\nConnection closed'.format(err_msg))
time.sleep(self._SOCK_RECONNECT_DELAY)
self.call_handler(self.DISCONNECT_EVENT)

Expand Down Expand Up @@ -361,8 +360,7 @@ def run(self):
if not self.is_server_alive():
self.disconnect('Blynk server is offline')
except KeyboardInterrupt:
print("\nKeyboardInterrupt: process terminated by user")
sys.exit(0)
raise
except Exception as g_exc:
print(g_exc)
self.disconnect(g_exc)
0