8000 connect handler for each server send needs closing forced reading · vicantec/lib-python@2011889 · GitHub
[go: up one dir, main page]

Skip to content

Commit 2011889

Browse files
author
amorozenko
committed
connect handler for each server send needs closing forced reading
1 parent 37df411 commit 2011889

File tree

4 files changed

+126
-8
lines changed

4 files changed

+126
-8
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@ Examples can be found **[here][blynk-py-examples]** Check them all to get famili
160160
- [06_terminal_widget.py](https://github.com/blynkkk/lib-python/blob/master/examples/06_terminal_widget.py): Communication between hardware and app through Terminal widget)
161161
- [07_tweet_and_logging.py](https://github.com/blynkkk/lib-python/blob/master/examples/07_tweet_and_logging.py): How to post to Twitter and log events from your hardware
162162
- [08_blynk_timer.py](https://github.com/blynkkk/lib-python/blob/master/examples/08_blynk_timer.py): How send data periodically from hardware by using **[Blynk Timer][blynktimer-doc]**
163+
- [09_sync_virtual_pin.py]((https://github.com/blynkkk/lib-python/blob/master/examples/09_sync_virtual_pin.py)): How to sync virtual pin states and properties
163164

164165
##### Raspberry Pi (any):
165166
Read [Raspberry Pi guide](https://github.com/blynkkk/lib-python/tree/master/examples/raspberry) first.

blynklib.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -275,13 +275,13 @@ def connect(self, timeout=_CONNECT_TIMEOUT):
275275
return False
276276

277277
def disconnect(self, err_msg=None):
278+
self.call_handler(self._DISCONNECT)
278279
if self._socket:
279280
self._socket.close()
280281
self._state = self.DISCONNECTED
281282
if err_msg:
282283
self.log('[ERROR]: {}\nConnection closed'.format(err_msg))
283284
time.sleep(self.RECONNECT_SLEEP)
284-
self.call_handler(self._DISCONNECT)
285285

286286
def virtual_write(self, v_pin, *val):
287287
return self.send(self.virtual_write_msg(v_pin, *val))
@@ -336,16 +336,21 @@ def process(self, msg_type, msg_id, msg_len, msg_args):
336336
elif len(msg_args) == const(2) and msg_args[0] == 'vr':
337337
self.call_handler("{}{}".format(self._VPIN_READ, msg_args[1]), int(msg_args[1]))
338338

339+
def read_response(self, timeout=0.5):
340+
end_time = time.time() + timeout
341+
while time.time() <= end_time:
342+
rsp_data = self.receive(self.rcv_buffer, self.SOCK_TIMEOUT)
343+
self._last_rcv_time = ticks_ms()
344+
if rsp_data:
345+
msg_type, msg_id, h_data, msg_args = self.parse_response(rsp_data, self.rcv_buffer)
346+
self.process(msg_type, msg_id, h_data, msg_args)
347+
339348
def run(self):
340349
if not self.connected():
341350
self.connect()
342351
else:
343352
try:
344-
rsp_data = self.receive(self.rcv_buffer, self.SOCK_TIMEOUT)
345-
self._last_rcv_time = ticks_ms()
346-
if rsp_data:
347-
msg_type, msg_id, h_data, msg_args = self.parse_response(rsp_data, self.rcv_buffer)
348-
self.process(msg_type, msg_id, h_data, msg_args)
353+
self.read_response(timeout=self.SOCK_TIMEOUT)
349354
if not self.is_server_alive():
350355
self.disconnect('Blynk server is offline')
351356
except KeyboardInterrupt:

examples/05_set_property_notify.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,8 @@
7474

7575
@blynk.handle_event('write V5')
7676
def write_handler(pin, value):
77-
current_color = random.choice(colors.keys())
78-
blynk.set_property(pin, 'color', random.choice(colors.keys()))
77+
current_color = random.choice(list(colors.keys()))
78+
blynk.set_property(pin, 'color', current_color)
7979
blynk.notify(NOTIFY_MSG.format(colors[current_color]))
8080
print(NOTIFY_MSG.format(colors[current_color]))
8181

examples/09_sync_virtual_pin.py

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
"""
2+
[VIRTUAL PIN SYNC EXAMPLE] ==========================================================================================
3+
4+
Environment prepare:
5+
In your Blynk App project:
6+
- add 3 "Button" widgets,
7+
- bind then to Virtual Pins V0, V1, v2
8+
- set mode "SWITCH" for all of them
9+
- Run the App (green triangle in the upper right corner).
10+
- define your auth token for current example and run it
11+
12+
13+
This started program will restore on connect write_virtual_pin states and colors.
14+
Buttons states and colors can be modified during script run.
15+
If script was interrupted (KeyboardInterrupt) buttons colors will be changed to red.
16+
During next connect event ( script re-run) previous buttons states and colors will be restored.
17+
18+
Schema:
19+
=====================================================================================================================
20+
+-----------+ +--------------+ +--------------+
21+
| | | | | |
22+
| blynk lib | | blynk server | | blynk app |
23+
| | | virtual pin | | |
24+
| | | | | |
25+
+-----+-----+ +------+-------+ +-------+------+
26+
connect handler | | |
27+
+--------+ | |
28+
| +------------------------------------>+ |
29+
| | virtual pin sync | |
30+
| +<------------------------------------+----------------------------------->+
31+
| | virtual pin write stored value | send pin value to app |
32+
| +<------------------------------------+----------------------------------->+
33+
| | virtual pin apply stored properties | send pin properties to app |
34+
+------->+ | |
35+
write handler | | |
36+
+--------+ +<-----------------------------------+
37+
| +<------------------------------------+ write event from button |
38+
+>------>+ write event form server | |
39+
| | |
40+
| | |
41+
disconnect | | |
42+
handler | | |
43+
+-------+ | |
44+
| +------------------------------------>+ |
45+
+------>+ set new virtual pin property | |
46+
| | |
47+
| | |
48+
| | |
49+
+ + +
50+
51+
=====================================================================================================================
52+
Additional info about blynk you can find by examining such resources:
53+
54+
Downloads, docs, tutorials: https://blynk.io
55+
Sketch generator: http://examples.blynk.cc
56+
Blynk community: http://community.blynk.cc
57+
Social networks: http://www.fb.com/blynkapp
58+
http://twitter.com/blynk_app
59+
=====================================================================================================================
60+
"""
61+
import logging
62+
import blynklib
63+
64+
# tune console logging
65+
_log = logging.getLogger('BlynkLog')
66+
logFormatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
67+
consoleHandler = logging.StreamHandler()
68+
consoleHandler.setFormatter(logFormatter)
69+
_log.addHandler(consoleHandler)
70+
_log.setLevel(logging.DEBUG)
71+
72+
colors = {'1': '#FFC300', '0': '#CCCCCC', 'OFFLINE': '#FF0000'}
73+
74+
BLYNK_AUTH = 'YourAuthToken'
75+
blynk = blynklib.Blynk(BLYNK_AUTH, log=_log.info)
76+
77+
78+
@blynk.handle_event("connect")
79+
def connect_handler():
80+
_log.info('SCRIPT_START')
81+
for pin in range(3):
82+
_log.info('Syncing virtual pin {}'.format(pin))
83+
blynk.virtual_sync(pin)
84+
85+
# within connect handler after each server send operation forced socket reading is required cause:
86+
# - we are not in script listening state yet
87+
# - without forced reading some portion of blynk server messages can be not delivered to HW
88+
blynk.read_response(timeout=0.5)
89+
90+
91+
@blynk.handle_event('write V*')
92+
def write_handler(pin, value):
93+
button_state = value[0]
94+
blynk.set_property(pin, 'color', colors[button_state])
95+
96+
97+
@blynk.handle_event("disconnect")
98+
def connect_handler():
99+
for pin in range(3):
100+
_log.info("Set 'OFFLINE' color for pin {}".format(pin))
101+
blynk.set_property(pin, 'color', colors['OFFLINE'])
102+
103+
104+
###########################################################
105+
# infinite loop that waits for event
106+
###########################################################
107+
try:
108+
while True:
109+
blynk.run()
110+
except KeyboardInterrupt:
111+
blynk.disconnect()
112+
_log.info('SCRIPT WAS INTERRUPTED')

0 commit comments

Comments
 (0)
0