├── .gitignore
├── BlynkLib.py
├── BlynkTimer.py
├── LICENSE
├── README.md
├── examples
├── 01_virtual_write.py
├── 02_on_virtual_change.py
├── 03_sync_virtual.py
├── 04_timer.py
├── 05_utc_and_timezone.py
├── 06_widget_terminal.py
├── 07_other_functions.py
├── Edgent_Linux_RPi
│ ├── BlynkEdgent.py
│ ├── README.md
│ └── main.py
└── hardware
│ ├── ESP32_Cellular_PPPoS.py
│ ├── ESP8266_ESP32.py
│ ├── PyCom_BLE.py
│ ├── PyCom_WiPy.py
│ └── WM_W600.py
├── setup.cfg
└── setup.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | env/
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 |
27 | # PyInstaller
28 | # Usually these files are written by a python script from a template
29 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
30 | *.manifest
31 | *.spec
32 |
33 | # Installer logs
34 | pip-log.txt
35 | pip-delete-this-directory.txt
36 |
37 | # Unit test / coverage reports
38 | htmlcov/
39 | .tox/
40 | .coverage
41 | .coverage.*
42 | .cache
43 | nosetests.xml
44 | coverage.xml
45 | *,cover
46 | .hypothesis/
47 |
48 | # Translations
49 | *.mo
50 | *.pot
51 |
52 | # Django stuff:
53 | *.log
54 | local_settings.py
55 |
56 | # Flask stuff:
57 | instance/
58 | .webassets-cache
59 |
60 | # Scrapy stuff:
61 | .scrapy
62 |
63 | # Sphinx documentation
64 | docs/_build/
65 |
66 | # PyBuilder
67 | target/
68 |
69 | # IPython Notebook
70 | .ipynb_checkpoints
71 |
72 | # pyenv
73 | .python-version
74 |
75 | # celery beat schedule file
76 | celerybeat-schedule
77 |
78 | # dotenv
79 | .env
80 |
81 | # virtualenv
82 | venv/
83 | ENV/
84 |
85 | # Spyder project settings
86 | .spyderproject
87 |
88 | # Rope project settings
89 | .ropeproject
90 |
--------------------------------------------------------------------------------
/BlynkLib.py:
--------------------------------------------------------------------------------
1 | # Copyright (c) 2015-2019 Volodymyr Shymanskyy. See the file LICENSE for copying permission.
2 |
3 | __version__ = "1.0.0"
4 |
5 | import struct
6 | import time
7 | import sys
8 | import os
9 |
10 | try:
11 | import machine
12 | gettime = lambda: time.ticks_ms()
13 | SOCK_TIMEOUT = 0
14 | except ImportError:
15 | const = lambda x: x
16 | gettime = lambda: int(time.time() * 1000)
17 | SOCK_TIMEOUT = 0.05
18 |
19 | def dummy(*args):
20 | pass
21 |
22 | MSG_RSP = const(0)
23 | MSG_LOGIN = const(2)
24 | MSG_PING = const(6)
25 |
26 | MSG_TWEET = const(12)
27 | MSG_NOTIFY = const(14)
28 | MSG_BRIDGE = const(15)
29 | MSG_HW_SYNC = const(16)
30 | MSG_INTERNAL = const(17)
31 | MSG_PROPERTY = const(19)
32 | MSG_HW = const(20)
33 | MSG_HW_LOGIN = const(29)
34 | MSG_EVENT_LOG = const(64)
35 |
36 | MSG_REDIRECT = const(41) # TODO: not implemented
37 | MSG_DBG_PRINT = const(55) # TODO: not implemented
38 |
39 | STA_SUCCESS = const(200)
40 | STA_INVALID_TOKEN = const(9)
41 |
42 | DISCONNECTED = const(0)
43 | CONNECTING = const(1)
44 | CONNECTED = const(2)
45 |
46 | print("""
47 | ___ __ __
48 | / _ )/ /_ _____ / /__
49 | / _ / / // / _ \\/ '_/
50 | /____/_/\\_, /_//_/_/\\_\\
51 | /___/ for Python v""" + __version__ + " (" + sys.platform + ")\n")
52 |
53 | class EventEmitter:
54 | def __init__(self):
55 | self._cbks = {}
56 |
57 | def on(self, evt, f=None):
58 | if f:
59 | self._cbks[evt] = f
60 | else:
61 | def D(f):
62 | self._cbks[evt] = f
63 | return f
64 | return D
65 |
66 | def emit(self, evt, *a, **kv):
67 | if evt in self._cbks:
68 | self._cbks[evt](*a, **kv)
69 |
70 |
71 | class BlynkProtocol(EventEmitter):
72 | def __init__(self, auth, tmpl_id=None, fw_ver=None, heartbeat=50, buffin=1024, log=None):
73 | EventEmitter.__init__(self)
74 | self.heartbeat = heartbeat*1000
75 | self.buffin = buffin
76 | self.log = log or dummy
77 | self.auth = auth
78 | self.tmpl_id = tmpl_id
79 | self.fw_ver = fw_ver
80 | self.state = DISCONNECTED
81 | self.connect()
82 |
83 | def virtual_write(self, pin, *val):
84 | self._send(MSG_HW, 'vw', pin, *val)
85 |
86 | def send_internal(self, pin, *val):
87 | self._send(MSG_INTERNAL, pin, *val)
88 |
89 | def set_property(self, pin, prop, *val):
90 | self._send(MSG_PROPERTY, pin, prop, *val)
91 |
92 | def sync_virtual(self, *pins):
93 | self._send(MSG_HW_SYNC, 'vr', *pins)
94 |
95 | def log_event(self, *val):
96 | self._send(MSG_EVENT_LOG, *val)
97 |
98 | def _send(self, cmd, *args, **kwargs):
99 | if 'id' in kwargs:
100 | id = kwargs.get('id')
101 | else:
102 | id = self.msg_id
103 | self.msg_id += 1
104 | if self.msg_id > 0xFFFF:
105 | self.msg_id = 1
106 |
107 | if cmd == MSG_RSP:
108 | data = b''
109 | dlen = args[0]
110 | else:
111 | data = ('\0'.join(map(str, args))).encode('utf8')
112 | dlen = len(data)
113 |
114 | self.log('<', cmd, id, '|', *args)
115 | msg = struct.pack("!BHH", cmd, id, dlen) + data
116 | self.lastSend = gettime()
117 | self._write(msg)
118 |
119 | def connect(self):
120 | if self.state != DISCONNECTED: return
121 | self.msg_id = 1
122 | (self.lastRecv, self.lastSend, self.lastPing) = (gettime(), 0, 0)
123 | self.bin = b""
124 | self.state = CONNECTING
125 | self._send(MSG_HW_LOGIN, self.auth)
126 |
127 | def disconnect(self):
128 | if self.state == DISCONNECTED: return
129 | self.bin = b""
130 | self.state = DISCONNECTED
131 | self.emit('disconnected')
132 |
133 | def process(self, data=None):
134 | if not (self.state == CONNECTING or self.state == CONNECTED): return
135 | now = gettime()
136 | if now - self.lastRecv > self.heartbeat+(self.heartbeat//2):
137 | return self.disconnect()
138 | if (now - self.lastPing > self.heartbeat//10 and
139 | (now - self.lastSend > self.heartbeat or
140 | now - self.lastRecv > self.heartbeat)):
141 | self._send(MSG_PING)
142 | self.lastPing = now
143 |
144 | if data != None and len(data):
145 | self.bin += data
146 |
147 | while True:
148 | if len(self.bin) < 5:
149 | break
150 |
151 | cmd, i, dlen = struct.unpack("!BHH", self.bin[:5])
152 | if i == 0: return self.disconnect()
153 |
154 | self.lastRecv = now
155 | if cmd == MSG_RSP:
156 | self.bin = self.bin[5:]
157 |
158 | self.log('>', cmd, i, '|', dlen)
159 | if self.state == CONNECTING and i == 1:
160 | if dlen == STA_SUCCESS:
161 | self.state = CONNECTED
162 | dt = now - self.lastSend
163 | info = ['ver', __version__, 'h-beat', self.heartbeat//1000, 'buff-in', self.buffin, 'dev', sys.platform+'-py']
164 | if self.tmpl_id:
165 | info.extend(['tmpl', self.tmpl_id])
166 | info.extend(['fw-type', self.tmpl_id])
167 | if self.fw_ver:
168 | info.extend(['fw', self.fw_ver])
169 | self._send(MSG_INTERNAL, *info)
170 | try:
171 | self.emit('connected', ping=dt)
172 | except TypeError:
173 | self.emit('connected')
174 | else:
175 | if dlen == STA_INVALID_TOKEN:
176 | self.emit("invalid_auth")
177 | print("Invalid auth token")
178 | return self.disconnect()
179 | else:
180 | if dlen >= self.buffin:
181 | print("Cmd too big: ", dlen)
182 | return self.disconnect()
183 |
184 | if len(self.bin) < 5+dlen:
185 | break
186 |
187 | data = self.bin[5:5+dlen]
188 | self.bin = self.bin[5+dlen:]
189 |
190 | args = list(map(lambda x: x.decode('utf8'), data.split(b'\0')))
191 |
192 | self.log('>', cmd, i, '|', ','.join(args))
193 | if cmd == MSG_PING:
194 | self._send(MSG_RSP, STA_SUCCESS, id=i)
195 | elif cmd == MSG_HW or cmd == MSG_BRIDGE:
196 | if args[0] == 'vw':
197 | self.emit("V"+args[1], args[2:])
198 | self.emit("V*", args[1], args[2:])
199 | elif cmd == MSG_INTERNAL:
200 | self.emit("internal:"+args[0], args[1:])
201 | elif cmd == MSG_REDIRECT:
202 | self.emit("redirect", args[0], int(args[1]))
203 | else:
204 | print("Unexpected command: ", cmd)
205 | return self.disconnect()
206 |
207 | import socket
208 |
209 | class Blynk(BlynkProtocol):
210 | def __init__(self, auth, **kwargs):
211 | self.insecure = kwargs.pop('insecure', False)
212 | self.server = kwargs.pop('server', 'blynk.cloud')
213 | self.port = kwargs.pop('port', 80 if self.insecure else 443)
214 | BlynkProtocol.__init__(self, auth, **kwargs)
215 | self.on('redirect', self.redirect)
216 |
217 | def redirect(self, server, port):
218 | self.server = server
219 | self.port = port
220 | self.disconnect()
221 | self.connect()
222 |
223 | def connect(self):
224 | print('Connecting to %s:%d...' % (self.server, self.port))
225 | s = socket.socket()
226 | s.connect(socket.getaddrinfo(self.server, self.port)[0][-1])
227 | try:
228 | s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
229 | except:
230 | pass
231 | if self.insecure:
232 | self.conn = s
233 | else:
234 | try:
235 | import ussl
236 | ssl_context = ussl
237 | except ImportError:
238 | import ssl
239 | ssl_context = ssl.create_default_context()
240 | self.conn = ssl_context.wrap_socket(s, server_hostname=self.server)
241 | try:
242 | self.conn.settimeout(SOCK_TIMEOUT)
243 | except:
244 | s.settimeout(SOCK_TIMEOUT)
245 | BlynkProtocol.connect(self)
246 |
247 | def _write(self, data):
248 | #print('<', data)
249 | self.conn.write(data)
250 | # TODO: handle disconnect
251 |
252 | def run(self):
253 | data = b''
254 | try:
255 | data = self.conn.read(self.buffin)
256 | #print('>', data)
257 | except KeyboardInterrupt:
258 | raise
259 | except socket.timeout:
260 | # No data received, call process to send ping messages when needed
261 | pass
262 | except: # TODO: handle disconnect
263 | return
264 | self.process(data)
265 |
266 |
--------------------------------------------------------------------------------
/BlynkTimer.py:
--------------------------------------------------------------------------------
1 | """
2 | BlynkTimer
3 | blynk-library-python
4 |
5 | Module for launching timed Blynk actions
6 | with polling
7 |
8 | """
9 |
10 | import time
11 |
12 |
13 | class BlynkTimer:
14 | '''Executes functions after a defined period of time'''
15 | _MAX_TIMERS = 16
16 |
17 | def __init__(self):
18 | self.timers = []
19 | self.ids = self._get_unique_id()
20 |
21 | def _get_unique_id(self, current=0):
22 | '''yields unique id for new timer'''
23 | numId = current
24 | while numId < self._MAX_TIMERS:
25 | yield numId
26 | numId += 1
27 |
28 | def _add(self, func, **kwargs):
29 | '''Inits Timer'''
30 | timerId = next(self.ids)
31 | timer = Timer(timerId, func, **kwargs)
32 | self.timers.append(timer)
33 | return timer
34 |
35 | def _get(self, timerId):
36 | '''Gets timer by id'''
37 | timer = [t for t in self.timers if t.id == timerId]
38 | if len(timer) <= 0:
39 | return None
40 | return timer[0]
41 |
42 | def _delete(self, timerId):
43 | '''Deletes timer'''
44 | timer = self._get(timerId)
45 | timer.disable()
46 | self.timers = [t for t in self.timers if t.id != timerId]
47 | num_timers = self.get_num_timers()[0]
48 | self.ids = self._get_unique_id(current=num_timers)
49 | return timerId
50 |
51 | def get_num_timers(self):
52 | '''Returns number of used timer slots'''
53 | num_timers = len(self.timers)
54 | return (num_timers, self._MAX_TIMERS)
55 |
56 | def is_enabled(self, timerId):
57 | '''Returns true if timer is enabled'''
58 | timer = self._get(timerId)
59 | return timer.enabled
60 |
61 | def set_interval(self, value, func):
62 | '''Sets time interval for function'''
63 | timer = self._add(func)
64 | timer.set_interval(value)
65 | return timer.id
66 |
67 | def set_timeout(self, value, func):
68 | '''Runs function once after timeout'''
69 | timer = self._add(func, post_run=self._delete)
70 | timer.set_interval(value)
71 | return timer.id
72 |
73 | def enable(self, timerId):
74 | '''Enables timer'''
75 | timer = self._get(timerId)
76 | timer.enable()
77 | return timerId
78 |
79 | def disable(self, timerId):
80 | '''Disables timer'''
81 | timer = self._get(timerId)
82 | timer.disable()
83 | return timerId
84 |
85 | def run(self):
86 | '''Polls timers'''
87 | [t.run() for t in self.timers]
88 |
89 |
90 | class Timer:
91 | '''Runs function after specific interval'''
92 |
93 | def __init__(self, id, func, **kwargs):
94 | self.id = id
95 | self.func = func
96 | self.interval = None
97 | self.start_time = None
98 | self.enabled = False
99 | self.on_post_run = kwargs.get('post_run', None)
100 |
101 | def _handle_post_run(self):
102 | '''handles post run events'''
103 | self.start_time += self.interval
104 | if self.on_post_run:
105 | return self.on_post_run(self.id)
106 |
107 | def enable(self):
108 | '''enables Timer'''
109 | self.enabled = True
110 | self.start_time = time.time()
111 |
112 | def disable(self):
113 | '''disables timer'''
114 | self.enabled = False
115 | self.start_time = None
116 |
117 | def set_interval(self, value):
118 | '''Sets Time Interval for calling function'''
119 | self.interval = value
120 | self.enable()
121 |
122 | def run(self):
123 | '''Runs function if interval has passed'''
124 | if not self.enabled:
125 | return
126 | now = time.time()
127 | if now - self.start_time > self.interval:
128 | self.func()
129 | self._handle_post_run()
130 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2015-2018 Volodymyr Shymanskyy
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | > [!IMPORTANT]
2 | > **This project is still available for exploration, but is no longer actively maintained or updated.**
3 | > We recommend switching to the Blynk MQTT API for a robust and future-proof experience.
4 | > Support for this project will be phased out over time.
5 | > You can explore some [useful MQTT examples here](https://github.com/Blynk-Technologies/Blynk-MQTT-Samples).
6 |
7 | # Python client for Blynk IoT
8 |
9 | **Note:** The library has been updated for Blynk 2.0.
10 | Please remain on `v0.2.0` for legacy Blynk.
11 |
12 | [](https://github.com/vshymanskyy/blynk-library-python/releases/latest)
13 | [](https://github.com/vshymanskyy/blynk-library-python/releases/latest)
14 | [](https://github.com/vshymanskyy/blynk-library-python/stargazers)
15 | [](https://github.com/vshymanskyy/blynk-library-python/issues)
16 | [](https://github.com/vshymanskyy/blynk-library-python/blob/master/LICENSE)
17 |
18 | If you like **Blynk** - give it a star, or fork it and contribute!
19 | [](https://github.com/blynkkk/blynk-library/stargazers)
20 | [](https://github.com/blynkkk/blynk-library/network)
21 | __________
22 |
23 | ## What is Blynk?
24 | Blynk provides **iOS** and **Android** apps to control any hardware **over the Internet** or **directly using Bluetooth**.
25 | You can easily build graphic interfaces for all your projects by simply dragging and dropping widgets, **right on your smartphone**.
26 | Blynk is **the most popular IoT platform** used by design studios, makers, educators, and equipment vendors all over the world.
27 |
28 | 
29 |
30 | ## Download
31 |
32 | **Blynk Mobile App:
33 | [
Google Play](https://play.google.com/store/apps/details?id=cloud.blynk) |
34 | [
App Store](https://apps.apple.com/us/app/blynk-iot/id1559317868)**
35 |
36 | ## Documentation
37 | Social: [Webpage](http://www.blynk.cc) / [Facebook](http://www.fb.com/blynkapp) / [Twitter](http://twitter.com/blynk_app) / [Kickstarter](https://www.kickstarter.com/projects/167134865/blynk-build-an-app-for-your-arduino-project-in-5-m/description)
38 | Documentation: https://docs.blynk.io
39 | Community Forum: http://community.blynk.cc
40 | Blynk for Business: http://www.blynk.io
41 |
42 | ## Usage example
43 |
44 | ```py
45 | import BlynkLib
46 |
47 | # Initialize Blynk
48 | blynk = BlynkLib.Blynk('YourAuthToken')
49 |
50 | # Register Virtual Pins
51 | @blynk.VIRTUAL_WRITE(1)
52 | def my_write_handler(value):
53 | print('Current V1 value: {}'.format(value))
54 |
55 | @blynk.VIRTUAL_READ(2)
56 | def my_read_handler():
57 | # this widget will show some time in seconds..
58 | blynk.virtual_write(2, int(time.time()))
59 |
60 | while True:
61 | blynk.run()
62 | ```
63 |
64 |
65 | ## Features
66 | - **Python 2, Python 3, MicroPython** support
67 | - **
Linux,
68 |
Windows,
69 |
MacOS** support
70 | - `virtual_write`
71 | - `sync_virtual`
72 | - `set_property`
73 | - `log_event`
74 | - events: `Vn`, `connected`, `disconnected`, `invalid_auth`
75 | - `TCP` and secure `TLS/SSL` connection support
76 | - can run on embedded hardware, like `ESP8266`, `ESP32`, `W600` or `OpenWrt`
77 |
78 | ## Ubuntu/Linux/Raspberry Pi installation
79 |
80 | ```sh
81 | pip install blynk-library-python
82 | ```
83 |
84 | For **Blynk.Edgent Dynamic Provisioning**, please see `examples/Edgent_Linux_RPi`
85 |
86 | ## ESP32/ESP8266 installation
87 |
88 | - Get the latest [MicroPython](https://micropython.org/download) firmware and flash it to your board
89 | - Edit [ESP8266_ESP32.py](examples/hardware/ESP8266_ESP32.py) example (put your `auth token` and wifi credentials)
90 | - Use `ampy` or any other method to transfer files to the device
91 | ```sh
92 | export AMPY_PORT=/dev/ttyUSB0
93 | ampy mkdir /lib
94 | ampy put BlynkLib.py /lib/BlynkLib.py
95 | ampy put ./examples/hardware/ESP8266_ESP32.py main.py
96 | ```
97 | **Note:** LoBo firmware stores files uder `/flash` directory, use `ampy mkdir /flash/lib` and so on
98 | - Open device terminal and reboot the board (or type `execfile('main.py')`)
99 | - For ESP8266, you may need to disable secure connection using:
100 | ```py
101 | blynk = BlynkLib.Blynk('YourAuthToken', insecure=True)
102 | ```
103 |
104 | ## PyCom installation
105 | - This should work with WiPy 1.0, 2.0, 3.0, LoPy, SiPy, GPy, FiPy
106 | - Instructions are the same as for ESP32, just use [PyCom_WiPy.py](examples/hardware/PyCom_WiPy.py) example
107 |
108 | __________
109 |
110 | ### Implementations for other platforms
111 | * [Arduino](https://github.com/blynkkk/blynk-library)
112 | * [Particle](https://github.com/vshymanskyy/blynk-library-spark)
113 | * [Lua, OpenWrt, NodeMCU](https://github.com/vshymanskyy/blynk-library-lua)
114 | * [Node.js, Espruino, Browsers](https://github.com/vshymanskyy/blynk-library-js)
115 | * [OpenWrt packages](https://github.com/vshymanskyy/blynk-library-openwrt)
116 | * [MBED](https://developer.mbed.org/users/vshymanskyy/code/Blynk/)
117 | * [Node-RED for Blynk IoT](https://flows.nodered.org/node/node-red-contrib-blynk-iot)
118 | * [LabVIEW](https://github.com/juncaofish/NI-LabVIEWInterfaceforBlynk)
119 | * [C#](https://github.com/sverrefroy/BlynkLibrary)
120 |
121 | ### License
122 | This project is released under The MIT License (MIT)
123 |
--------------------------------------------------------------------------------
/examples/01_virtual_write.py:
--------------------------------------------------------------------------------
1 | """
2 | Blynk is a platform with iOS and Android apps to control
3 | Arduino, Raspberry Pi and the likes over the Internet.
4 | You can easily build graphic interfaces for all your
5 | projects by simply dragging and dropping widgets.
6 |
7 | Downloads, docs, tutorials: http://www.blynk.cc
8 | Sketch generator: http://examples.blynk.cc
9 | Blynk community: http://community.blynk.cc
10 | Social networks: http://www.fb.com/blynkapp
11 | http://twitter.com/blynk_app
12 | """
13 |
14 | import BlynkLib
15 | import time
16 |
17 | BLYNK_AUTH = 'YourAuthToken'
18 |
19 | # initialize Blynk
20 | blynk = BlynkLib.Blynk(BLYNK_AUTH)
21 |
22 | tmr_start_time = time.time()
23 | while True:
24 | blynk.run()
25 |
26 | t = time.time()
27 | if t - tmr_start_time > 1:
28 | print("1 sec elapsed, sending data to the server...")
29 | blynk.virtual_write(0, "time:" + str(t))
30 | tmr_start_time += 1
31 |
--------------------------------------------------------------------------------
/examples/02_on_virtual_change.py:
--------------------------------------------------------------------------------
1 | """
2 | Blynk is a platform with iOS and Android apps to control
3 | Arduino, Raspberry Pi and the likes over the Internet.
4 | You can easily build graphic interfaces for all your
5 | projects by simply dragging and dropping widgets.
6 |
7 | Downloads, docs, tutorials: http://www.blynk.cc
8 | Sketch generator: http://examples.blynk.cc
9 | Blynk community: http://community.blynk.cc
10 | Social networks: http://www.fb.com/blynkapp
11 | http://twitter.com/blynk_app
12 |
13 | This example shows how to perform custom actions
14 | using data from the widget.
15 |
16 | In your Blynk App project:
17 | Add a Slider widget,
18 | bind it to Virtual Pin V3.
19 | Run the App (green triangle in the upper right corner)
20 |
21 | It will automagically call v3_write_handler.
22 | In the handler, you can use args[0] to get current slider value.
23 | """
24 |
25 | import BlynkLib
26 |
27 | BLYNK_AUTH = 'YourAuthToken'
28 |
29 | # Initialize Blynk
30 | blynk = BlynkLib.Blynk(BLYNK_AUTH)
31 |
32 | # Register virtual pin handler
33 | @blynk.on("V3")
34 | def v3_write_handler(value):
35 | print('Current slider value: {}'.format(value[0]))
36 |
37 | while True:
38 | blynk.run()
39 |
--------------------------------------------------------------------------------
/examples/03_sync_virtual.py:
--------------------------------------------------------------------------------
1 | """
2 | Blynk is a platform with iOS and Android apps to control
3 | Arduino, Raspberry Pi and the likes over the Internet.
4 | You can easily build graphic interfaces for all your
5 | projects by simply dragging and dropping widgets.
6 |
7 | Downloads, docs, tutorials: http://www.blynk.cc
8 | Sketch generator: http://examples.blynk.cc
9 | Blynk community: http://community.blynk.cc
10 | Social networks: http://www.fb.com/blynkapp
11 | http://twitter.com/blynk_app
12 | """
13 |
14 | import BlynkLib
15 |
16 | BLYNK_AUTH = 'YourAuthToken'
17 |
18 | # initialize Blynk
19 | blynk = BlynkLib.Blynk(BLYNK_AUTH)
20 |
21 | @blynk.on("V*")
22 | def blynk_handle_vpins(pin, value):
23 | print("V{} value: {}".format(pin, value))
24 |
25 | @blynk.on("connected")
26 | def blynk_connected():
27 | # You can also use blynk.sync_virtual(pin)
28 | # to sync a specific virtual pin
29 | print("Updating V1,V2,V3 values from the server...")
30 | blynk.sync_virtual(1,2,3)
31 |
32 | while True:
33 | blynk.run()
34 |
--------------------------------------------------------------------------------
/examples/04_timer.py:
--------------------------------------------------------------------------------
1 | """
2 | Blynk is a platform with iOS and Android apps to control
3 | Arduino, Raspberry Pi and the likes over the Internet.
4 | You can easily build graphic interfaces for all your
5 | projects by simply dragging and dropping widgets.
6 |
7 | Downloads, docs, tutorials: http://www.blynk.cc
8 | Sketch generator: http://examples.blynk.cc
9 | Blynk community: http://community.blynk.cc
10 | Social networks: http://www.fb.com/blynkapp
11 | http://twitter.com/blynk_app
12 |
13 | This example shows how to run functions after certain intervals
14 |
15 | It will automagically call hello_word once after 2 seconds, and print_me
16 | every 5 seconds
17 |
18 | You should only need one BlynkTimer instance for a project,
19 | as you can add multiple functions to it
20 | """
21 |
22 | import BlynkLib
23 | from BlynkTimer import BlynkTimer
24 |
25 | BLYNK_AUTH = 'YourAuthToken'
26 |
27 | # Initialize Blynk
28 | blynk = BlynkLib.Blynk(BLYNK_AUTH)
29 |
30 | # Create BlynkTimer Instance
31 | timer = BlynkTimer()
32 |
33 |
34 | # Will only run once after 2 seconds
35 | def hello_world():
36 | print("Hello World!")
37 |
38 |
39 | # Will Print Every 5 Seconds
40 | def print_me():
41 | print("Thanks!")
42 |
43 |
44 | # Add Timers
45 | timer.set_timeout(2, hello_world)
46 | timer.set_interval(5, print_me)
47 |
48 |
49 | while True:
50 | blynk.run()
51 | timer.run()
52 |
--------------------------------------------------------------------------------
/examples/05_utc_and_timezone.py:
--------------------------------------------------------------------------------
1 | """
2 | Blynk is a platform with iOS and Android apps to control
3 | Arduino, Raspberry Pi and the likes over the Internet.
4 | You can easily build graphic interfaces for all your
5 | projects by simply dragging and dropping widgets.
6 |
7 | Downloads, docs, tutorials: http://www.blynk.cc
8 | Sketch generator: http://examples.blynk.cc
9 | Blynk community: http://community.blynk.cc
10 | Social networks: http://www.fb.com/blynkapp
11 | http://twitter.com/blynk_app
12 |
13 | This example shows how to get UTC time and Timezone info
14 | """
15 |
16 | import BlynkLib
17 | import time
18 |
19 | BLYNK_AUTH = 'YourAuthToken'
20 |
21 | # Initialize Blynk
22 | blynk = BlynkLib.Blynk(BLYNK_AUTH)
23 |
24 | @blynk.on("connected")
25 | def blynk_connected(ping):
26 | print('Blynk ready. Ping:', ping, 'ms')
27 | blynk.send_internal("utc", "time")
28 | blynk.send_internal("utc", "tz_name")
29 |
30 | @blynk.on("disconnected")
31 | def blynk_disconnected():
32 | print('Blynk disconnected')
33 |
34 | @blynk.on("internal:utc")
35 | def on_utc(value):
36 | if value[0] == "time":
37 | ts = int(value[1])//1000
38 | # on embedded systems, you may need to subtract time difference between 1970 and 2000
39 | #ts -= 946684800
40 | tm = time.gmtime(ts)
41 | print("UTC time: ", time.asctime(tm))
42 | elif value[0] == "tz_name":
43 | print("Timezone: ", value[1])
44 |
45 | while True:
46 | blynk.run()
47 |
--------------------------------------------------------------------------------
/examples/06_widget_terminal.py:
--------------------------------------------------------------------------------
1 | """
2 | Blynk is a platform with iOS and Android apps to control
3 | Arduino, Raspberry Pi and the likes over the Internet.
4 | You can easily build graphic interfaces for all your
5 | projects by simply dragging and dropping widgets.
6 |
7 | Downloads, docs, tutorials: http://www.blynk.cc
8 | Sketch generator: http://examples.blynk.cc
9 | Blynk community: http://community.blynk.cc
10 | Social networks: http://www.fb.com/blynkapp
11 | http://twitter.com/blynk_app
12 |
13 | This example shows how to add a custom terminal widget.
14 |
15 | In your Blynk App project:
16 | Add a Terminal widget, bind it to Virtual Pin V3.
17 | Run the App (green triangle in the upper right corner).
18 | """
19 |
20 | import BlynkLib
21 |
22 | BLYNK_AUTH = 'YourAuthToken'
23 |
24 | # initialize Blynk
25 | blynk = BlynkLib.Blynk(BLYNK_AUTH)
26 |
27 | @blynk.on("V3")
28 | def v3_write_handler(value):
29 | # execute the command echo it back
30 | blynk.virtual_write(3, 'Command: ' + value + '\n')
31 | blynk.virtual_write(3, 'Result: ')
32 | try:
33 | blynk.virtual_write(3, str(eval(value)))
34 | except:
35 | try:
36 | exec(value)
37 | except Exception as e:
38 | blynk.virtual_write(3, 'Exception:\n ' + repr(e))
39 | finally:
40 | blynk.virtual_write(3, '\n')
41 |
42 | while True:
43 | blynk.run()
44 |
--------------------------------------------------------------------------------
/examples/07_other_functions.py:
--------------------------------------------------------------------------------
1 | """
2 | Blynk is a platform with iOS and Android apps to control
3 | Arduino, Raspberry Pi and the likes over the Internet.
4 | You can easily build graphic interfaces for all your
5 | projects by simply dragging and dropping widgets.
6 |
7 | Downloads, docs, tutorials: http://www.blynk.cc
8 | Sketch generator: http://examples.blynk.cc
9 | Blynk community: http://community.blynk.cc
10 | Social networks: http://www.fb.com/blynkapp
11 | http://twitter.com/blynk_app
12 |
13 | This example shows how to use advanced functions of Blynk library:
14 | - insecure connection
15 | - debug logging
16 | - custom server
17 | - changing heartbeat
18 | - connected/disconnected events
19 | - generic virtual pin events
20 | """
21 |
22 | from __future__ import print_function
23 | import BlynkLib
24 |
25 | BLYNK_AUTH = 'YourAuthToken'
26 |
27 | # Initialize Blynk
28 | blynk = BlynkLib.Blynk(BLYNK_AUTH,
29 | insecure=True, # disable SSL/TLS
30 | server='blynk.cloud', # set server address
31 | port=80, # set server port
32 | heartbeat=30, # set heartbeat to 30 secs
33 | log=print # use print function for debug logging
34 | )
35 |
36 | @blynk.on("connected")
37 | def blynk_connected(ping):
38 | print('Blynk ready. Ping:', ping, 'ms')
39 |
40 | @blynk.on("disconnected")
41 | def blynk_disconnected():
42 | print('Blynk disconnected')
43 |
44 | @blynk.on("V*")
45 | def blynk_handle_vpins(pin, value):
46 | print("V{} value: {}".format(pin, value))
47 |
48 | while True:
49 | blynk.run()
50 |
--------------------------------------------------------------------------------
/examples/Edgent_Linux_RPi/BlynkEdgent.py:
--------------------------------------------------------------------------------
1 |
2 | from http.server import BaseHTTPRequestHandler, HTTPServer
3 | from urllib.parse import urlparse, parse_qsl
4 | from contextlib import suppress
5 | import sys, time
6 | import nmcli
7 | import json
8 | import binascii
9 |
10 | def log(*args, **kwargs):
11 | print(*args, file=sys.stderr, **kwargs)
12 |
13 | class WiFi:
14 | def __init__(self):
15 | #nmcli.disable_use_sudo()
16 |
17 | wifi_devices = list(filter(lambda x: x.device_type=="wifi", nmcli.device()))
18 | assert(len(wifi_devices) > 0)
19 | self.device = wifi_devices[0].device
20 | details = nmcli.device.show(self.device)
21 | self.mac_addr = details["GENERAL.HWADDR"]
22 | self.ap_name = "Blynk AP"
23 | log("WiFi devices:", wifi_devices)
24 | log("WiFi MAC: ", self.mac_addr)
25 |
26 | def mac_address(self):
27 | return self.mac_addr
28 |
29 | def set_hostname(self, name):
30 | nmcli.general.set_hostname(name)
31 | log("Hostname: ", name)
32 |
33 | def _cleanup(self, conn):
34 | with suppress(Exception):
35 | nmcli.connection.down(conn)
36 | with suppress(Exception):
37 | nmcli.connection.delete(conn)
38 |
39 | def create_ap(self, ssid):
40 | self.remove_ap()
41 | nmcli.connection.add(name = self.ap_name, conn_type = "wifi", options = {
42 | "ssid": ssid,
43 | "ipv4.method": "shared",
44 | "ipv4.addresses": "192.168.4.1/24",
45 | "802-11-wireless.mode": "ap",
46 | "802-11-wireless.band": "bg"
47 | })
48 | nmcli.connection.up(self.ap_name)
49 | log("AP SSID: ", ssid)
50 |
51 | def remove_ap(self):
52 | self._cleanup(self.ap_name)
53 |
54 | def scan(self):
55 | results = []
56 | for net in nmcli.device.wifi():
57 | signal = max(30, min(net.signal, 100))
58 | rssi_max = -20
59 | rssi_min = -90
60 | rssi = int(-((((rssi_max - rssi_min) * (signal - 100)) / -70) - rssi_max))
61 | results.append({
62 | "ssid": net.ssid,
63 | "bssid": net.bssid,
64 | "freq": net.freq,
65 | "rssi": rssi,
66 | "sec": net.security if len(net.security) else "OPEN",
67 | "ch": net.chan
68 | })
69 |
70 | return results
71 |
72 | def restart(self):
73 | nmcli.radio.wifi_off()
74 | nmcli.radio.wifi_on()
75 |
76 | def connect(self, ssid, password):
77 | self._cleanup(ssid)
78 | nmcli.device.wifi_connect(ssid, password)
79 |
80 | class HTTPHandler(BaseHTTPRequestHandler):
81 | def _reply_json(self, data):
82 | self.send_response(200)
83 | self.send_header("Content-type", "application/json")
84 | self.end_headers()
85 | self.wfile.write(json.dumps(data).encode())
86 |
87 | def log_message(self, format, *args):
88 | return
89 |
90 | def do_GET(self):
91 | o = urlparse(self.path)
92 | q = dict(parse_qsl(o.query))
93 | if o.path == "/board_info.json":
94 | self._reply_json(self.server.blynk_info)
95 | elif o.path == "/wifi_scan.json":
96 | self._reply_json(self.server.wifi_networks)
97 | elif o.path == "/config":
98 | q["auth"] = q.pop("blynk")
99 | q["server"] = q.pop("host")
100 | q["port"] = int(q.pop("port"))
101 | q["port_ssl"] = int(q.pop("port_ssl"))
102 | if "save" in q:
103 | self._reply_json({"status":"ok","msg":"Configuration saved"})
104 | else:
105 | self._reply_json({"status":"ok","msg":"Trying to connect..."})
106 | self.server.blynk_config = q
107 | else:
108 | self.send_error(404)
109 |
110 | def provision(board, tmpl_id, fw_ver, prefix = "Blynk"):
111 | wifi = WiFi()
112 |
113 | wifi_networks = wifi.scan()
114 |
115 | suffix = format(binascii.crc32(wifi.mac_address().encode() * 4) & 0xFFFFF, 'X')
116 | my_ssid = prefix + " " + board + "-" + suffix
117 |
118 | config = None
119 | try:
120 | wifi.create_ap(my_ssid)
121 | with HTTPServer(("0.0.0.0", 11080), HTTPHandler) as httpd:
122 | httpd.blynk_info = {
123 | "board": board,
124 | "tmpl_id": tmpl_id,
125 | "fw_type": tmpl_id,
126 | "fw_ver": fw_ver,
127 | "ssid": my_ssid,
128 | "bssid": wifi.mac_address(),
129 | "wifi_scan": True,
130 | "static_ip": False
131 | }
132 | httpd.wifi_networks = wifi_networks
133 | httpd.blynk_config = None
134 |
135 | log("Waiting for Blynk App connection...")
136 | while httpd.blynk_config is None:
137 | httpd.handle_request()
138 | config = httpd.blynk_config
139 | finally:
140 | wifi.remove_ap()
141 |
142 | if config is not None:
143 | wifi.set_hostname(my_ssid.replace(" ", "-"))
144 | wifi.restart()
145 | time.sleep(3)
146 | wifi.scan()
147 | time.sleep(1)
148 | wifi.connect(config['ssid'], config['pass'])
149 | time.sleep(1)
150 |
151 | return config
152 |
153 | if __name__ == "__main__":
154 | config = provision(sys.argv[1], sys.argv[2], sys.argv[3])
155 | print(json.dumps(config))
156 |
--------------------------------------------------------------------------------
/examples/Edgent_Linux_RPi/README.md:
--------------------------------------------------------------------------------
1 |
2 | **Warning:** Do not use SSH/remote desktop for these commands, as your network connection can become unavailable.
3 | Connect screen and keyboard to your RPi, or use a serial adapter to access console.
4 |
5 |
6 | ## Install NetworkManager
7 |
8 | NetworkManager provides detection and configuration for systems to automatically connect to different wired and wireless networks.
9 |
10 | ```sh
11 | sudo apt-get install network-manager
12 | sudo systemctl disable dhcpcd
13 | sudo systemctl stop dhcpcd
14 | sudo reboot
15 | ```
16 |
17 | After reboot, check if `nmcli works` with WiFi. For example, perform scanning:
18 | ```sh
19 | $ sudo nmcli dev wifi
20 | IN-USE SSID MODE CHAN RATE SIGNAL BARS SECURITY
21 | myNetwork Infra 6 270 Mbit/s 75 ▂▄▆_ WPA2
22 | otherNet Infra 9 405 Mbit/s 29 ▂___ WPA1 WPA2
23 | ```
24 |
25 | With `nmcli`, you can also easily connect to a wifi network (if needed):
26 |
27 | ```sh
28 | sudo nmcli device wifi con "my-ssid" password "my-pass"
29 | ```
30 |
31 | ## Troubleshooting
32 | 1. Make sure that your `wlan` interface is not configured via `/etc/network/interfaces`. NetworkManager ignores such interfaces.
33 | 2. Check if your WiFi is blocked using `rfkill list`. Run `rfkill unblock wifi` to unblock it.
34 |
35 |
36 | ## Install Edgent prerequisites
37 |
38 | ```sh
39 | pip3 install --upgrade https://github.com/vshymanskyy/nmcli/archive/master.zip
40 | pip3 install --upgrade RPi.GPIO
41 | ```
42 |
43 | ## Attach config reset button
44 |
45 | Connect button between gpio16 and GND.
46 | Hold the button for 10 seconds to reset config.
47 |
48 | ## Run script manually
49 |
50 | ```
51 | pyhton3 beemate.py
52 | ```
53 |
54 | Alternatively, you can configure RPi to auto-run `main.py` on boot.
55 |
--------------------------------------------------------------------------------
/examples/Edgent_Linux_RPi/main.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import time, os, sys
4 | import json
5 |
6 | import BlynkLib
7 | import BlynkEdgent
8 | import RPi.GPIO as GPIO
9 |
10 | # -- Configuration --------------------
11 | BLYNK_TEMPLATE_ID = ""
12 | BLYNK_DEVICE_NAME = ""
13 |
14 | BLYNK_FIRMWARE_VERSION = "0.1.0"
15 |
16 | BUTTON_GPIO = 16
17 | # -------------------------------------
18 |
19 | try:
20 | with open("config.json") as jsonFile:
21 | config = json.load(jsonFile)
22 | needToSave = False
23 | except:
24 | config = BlynkEdgent.provision(BLYNK_DEVICE_NAME, BLYNK_TEMPLATE_ID, BLYNK_FIRMWARE_VERSION)
25 | needToSave = True
26 |
27 | def reset_config():
28 | if os.path.exists("config.json"):
29 | print("Resetting configuration")
30 | os.remove("config.json")
31 | # Restart
32 | os.execv(sys.executable, ['python3'] + sys.argv)
33 | sys.exit(0)
34 |
35 | # Initialize Blynk
36 | blynk = BlynkLib.Blynk(config['auth'],
37 | server = config['server'],
38 | port = config['port_ssl'],
39 | tmpl_id = BLYNK_TEMPLATE_ID,
40 | fw_ver = BLYNK_FIRMWARE_VERSION)
41 |
42 | @blynk.on("connected")
43 | def blynk_connected(ping):
44 | print('Blynk ready. Ping:', ping, 'ms')
45 | if needToSave:
46 | with open('config.json', 'w') as jsonFile:
47 | json.dump(config, jsonFile)
48 | print("Configuration is saved")
49 |
50 | @blynk.on("disconnected")
51 | def blynk_disconnected():
52 | print('Blynk disconnected')
53 |
54 | @blynk.on("V*")
55 | def blynk_handle_vpins(pin, value):
56 | print("V{} value: {}".format(pin, value))
57 |
58 | def button_callback(channel):
59 | if GPIO.input(channel) == 1:
60 | return
61 |
62 | print("Hold button for 10 seconds to reset configuration")
63 | start_time = time.time()
64 | # Wait for the button up
65 | while (GPIO.input(channel) == 0 and
66 | time.time() - start_time <= 10):
67 | time.sleep(0.1)
68 | if time.time() - start_time > 10:
69 | reset_config()
70 |
71 | # Main
72 |
73 | GPIO.setmode(GPIO.BCM)
74 | GPIO.setup(BUTTON_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP)
75 |
76 | GPIO.add_event_detect(BUTTON_GPIO, GPIO.BOTH,
77 | callback=button_callback, bouncetime=50)
78 |
79 | def blynk_connect_with_retries():
80 | while True:
81 | try:
82 | blynk.connect()
83 | return
84 | except Exception as e:
85 | print(e)
86 | time.sleep(1)
87 |
88 | blynk_connect_with_retries()
89 |
90 | while True:
91 | blynk.run()
92 |
--------------------------------------------------------------------------------
/examples/hardware/ESP32_Cellular_PPPoS.py:
--------------------------------------------------------------------------------
1 | """
2 | Blynk is a platform with iOS and Android apps to control
3 | Arduino, Raspberry Pi and the likes over the Internet.
4 | You can easily build graphic interfaces for all your
5 | projects by simply dragging and dropping widgets.
6 |
7 | Downloads, docs, tutorials: http://www.blynk.cc
8 | Sketch generator: http://examples.blynk.cc
9 | Blynk community: http://community.blynk.cc
10 | Social networks: http://www.fb.com/blynkapp
11 | http://twitter.com/blynk_app
12 |
13 | This example shows how to initialize your ESP32 board
14 | and connect it to Blynk using a Cellular modem.
15 |
16 | Read more about LoBo GSM module here:
17 | https://github.com/loboris/MicroPython_ESP32_psRAM_LoBo/wiki/gsm
18 |
19 | Don't forget to change TX/RX pins, APN, user, password and BLYNK_AUTH ;)
20 | """
21 |
22 | import BlynkLib
23 | import gsm
24 | import machine, time
25 |
26 | BLYNK_AUTH = 'YourAuthToken'
27 |
28 | gsm.start(tx=27, rx=26, apn='', user='', password='')
29 |
30 | for retry in range(10):
31 | if gsm.atcmd('AT'):
32 | break
33 | else:
34 | print("Waiting modem")
35 | time.sleep_ms(5000)
36 | else:
37 | raise Exception("Modem not responding!")
38 |
39 | print("Connecting to GSM...")
40 | gsm.connect()
41 |
42 | while gsm.status()[0] != 1:
43 | pass
44 |
45 | print('IP:', gsm.ifconfig()[0])
46 |
47 | print("Connecting to Blynk...")
48 | blynk = BlynkLib.Blynk(BLYNK_AUTH)
49 |
50 | @blynk.on("connected")
51 | def blynk_connected(ping):
52 | print('Blynk ready. Ping:', ping, 'ms')
53 |
54 | def runLoop():
55 | while True:
56 | blynk.run()
57 | machine.idle()
58 |
59 | # Run blynk in the main thread:
60 | runLoop()
61 |
62 | # Or, run blynk in a separate thread (unavailable for esp8266):
63 | #import _thread
64 | #_thread.stack_size(5*1024)
65 | #_thread.start_new_thread("Blynk", runLoop, ())
66 |
--------------------------------------------------------------------------------
/examples/hardware/ESP8266_ESP32.py:
--------------------------------------------------------------------------------
1 | """
2 | Blynk is a platform with iOS and Android apps to control
3 | Arduino, Raspberry Pi and the likes over the Internet.
4 | You can easily build graphic interfaces for all your
5 | projects by simply dragging and dropping widgets.
6 |
7 | Downloads, docs, tutorials: http://www.blynk.cc
8 | Sketch generator: http://examples.blynk.cc
9 | Blynk community: http://community.blynk.cc
10 | Social networks: http://www.fb.com/blynkapp
11 | http://twitter.com/blynk_app
12 |
13 | This example shows how to initialize your ESP8266/ESP32 board
14 | and connect it to Blynk.
15 |
16 | Don't forget to change WIFI_SSID, WIFI_PASS and BLYNK_AUTH ;)
17 | """
18 |
19 | import BlynkLib
20 | import network
21 | import machine
22 |
23 | WIFI_SSID = 'YourWiFiNetwork'
24 | WIFI_PASS = 'YourWiFiPassword'
25 |
26 | BLYNK_AUTH = 'YourAuthToken'
27 |
28 | wifi = network.WLAN(network.STA_IF)
29 | if not wifi.isconnected():
30 | print("Connecting to WiFi...")
31 | wifi.active(True)
32 | wifi.connect(WIFI_SSID, WIFI_PASS)
33 | while not wifi.isconnected():
34 | pass
35 |
36 | print('IP:', wifi.ifconfig()[0])
37 |
38 | blynk = BlynkLib.Blynk(BLYNK_AUTH)
39 |
40 | @blynk.on("connected")
41 | def blynk_connected(ping):
42 | print('Blynk ready. Ping:', ping, 'ms')
43 |
44 | @blynk.on("disconnected")
45 | def blynk_disconnected():
46 | print('Blynk disconnected')
47 |
48 | def runLoop():
49 | while True:
50 | blynk.run()
51 | machine.idle()
52 |
53 | # Run blynk in the main thread
54 | runLoop()
55 |
56 | # You can also run blynk in a separate thread (ESP32 only)
57 | #import _thread
58 | #_thread.stack_size(5*1024)
59 | #_thread.start_new_thread(runLoop, ())
60 |
61 |
--------------------------------------------------------------------------------
/examples/hardware/PyCom_BLE.py:
--------------------------------------------------------------------------------
1 | """
2 | THIS EXAMPLE IS NOT FINISHED YET.
3 | (You can use this for educational purposes)
4 | """
5 |
6 | from network import Bluetooth
7 | from binascii import unhexlify
8 | from BlynkLib import BlynkProtocol
9 | import machine, time
10 |
11 | BLYNK_AUTH = "YourAuthToken"
12 |
13 | def unhex(s):
14 | return bytes(reversed(unhexlify(s.replace('-',''))))
15 |
16 |
17 | class BlynkBLE(BlynkProtocol):
18 | def __init__(self, auth, **kwargs):
19 | self.bout = b''
20 | BlynkProtocol.__init__(self, auth, **kwargs)
21 |
22 | def connect(self):
23 | bluetooth = Bluetooth()
24 | bluetooth.set_advertisement(name='Blynk')
25 |
26 | def conn_cb(bt):
27 | events = bt.events()
28 | if events & Bluetooth.CLIENT_CONNECTED:
29 | self.bout = b''
30 | print("Client connected")
31 | elif events & Bluetooth.CLIENT_DISCONNECTED:
32 | print("Client disconnected")
33 | BlynkProtocol.disconnect(self)
34 |
35 | bluetooth.callback(trigger=Bluetooth.CLIENT_CONNECTED | Bluetooth.CLIENT_DISCONNECTED, handler=conn_cb)
36 |
37 | nus = bluetooth.service(uuid=unhex('6E400001-B5A3-F393-E0A9-E50E24DCCA9E'), isprimary=True, nbr_chars=2)
38 | self.rx = nus.characteristic(uuid=unhex('6E400002-B5A3-F393-E0A9-E50E24DCCA9E'),
39 | properties=Bluetooth.PROP_WRITE | Bluetooth.PROP_WRITE_NR,
40 | value='')
41 | self.tx = nus.characteristic(uuid=unhex('6E400003-B5A3-F393-E0A9-E50E24DCCA9E'),
42 | properties=Bluetooth.PROP_READ | Bluetooth.PROP_NOTIFY,
43 | value='')
44 |
45 | bluetooth.advertise(True)
46 |
47 | def rx_cb(chr):
48 | data = chr.value()
49 | print('>', data)
50 | self.process(bytes(data))
51 |
52 | def tx_subsc(chr):
53 | print("Client subscribed", chr)
54 | BlynkProtocol.connect(self, login=False)
55 |
56 | self.tx.callback(trigger=Bluetooth.CHAR_SUBSCRIBE_EVENT, handler=tx_subsc)
57 | self.rx.callback(trigger=Bluetooth.CHAR_WRITE_EVENT, handler=rx_cb)
58 |
59 | def _write(self, data):
60 | self.bout += data
61 |
62 | def run(self):
63 | self.process()
64 |
65 | while len(self.bout):
66 | data = self.bout[:20]
67 | self.bout = self.bout[20:]
68 | print('<', data)
69 | self.tx.value(data)
70 |
71 | blynk = BlynkBLE(BLYNK_AUTH)
72 |
73 | @blynk.on("connected")
74 | def blynk_connected(ping):
75 | print('Blynk ready. Ping:', ping, 'ms')
76 |
77 | def runLoop():
78 | while True:
79 | blynk.run()
80 | time.sleep(0.1)
81 | #machine.idle()
82 |
83 | # Run blynk in the main thread:
84 | runLoop()
85 |
--------------------------------------------------------------------------------
/examples/hardware/PyCom_WiPy.py:
--------------------------------------------------------------------------------
1 | """
2 | Blynk is a platform with iOS and Android apps to control
3 | Arduino, Raspberry Pi and the likes over the Internet.
4 | You can easily build graphic interfaces for all your
5 | projects by simply dragging and dropping widgets.
6 |
7 | Downloads, docs, tutorials: http://www.blynk.cc
8 | Sketch generator: http://examples.blynk.cc
9 | Blynk community: http://community.blynk.cc
10 | Social networks: http://www.fb.com/blynkapp
11 | http://twitter.com/blynk_app
12 |
13 | This example shows how to initialize your WiPy board
14 | and connect it to Blynk.
15 |
16 | Don't forget to change WIFI_SSID, WIFI_PASS and BLYNK_AUTH ;)
17 | """
18 |
19 | import BlynkLib
20 | from network import WLAN
21 | import machine, time
22 |
23 | WIFI_SSID = 'YourWiFiNetwork'
24 | WIFI_PASS = 'YourWiFiPassword'
25 |
26 | BLYNK_AUTH = 'YourAuthToken'
27 |
28 | print("Connecting to WiFi...")
29 | wifi = WLAN(mode=WLAN.STA)
30 | wifi.connect(ssid=WIFI_SSID, auth=(WLAN.WPA2, WIFI_PASS))
31 | while not wifi.isconnected():
32 | time.sleep_ms(50)
33 |
34 | print('IP:', wifi.ifconfig()[0])
35 |
36 | print("Connecting to Blynk...")
37 | blynk = BlynkLib.Blynk(BLYNK_AUTH)
38 |
39 | @blynk.on("connected")
40 | def blynk_connected(ping):
41 | print('Blynk ready. Ping:', ping, 'ms')
42 |
43 | def runLoop():
44 | while True:
45 | blynk.run()
46 | machine.idle()
47 |
48 | # Run blynk in the main thread:
49 | runLoop()
50 |
--------------------------------------------------------------------------------
/examples/hardware/WM_W600.py:
--------------------------------------------------------------------------------
1 | """
2 | Blynk is a platform with iOS and Android apps to control
3 | Arduino, Raspberry Pi and the likes over the Internet.
4 | You can easily build graphic interfaces for all your
5 | projects by simply dragging and dropping widgets.
6 |
7 | Downloads, docs, tutorials: http://www.blynk.cc
8 | Sketch generator: http://examples.blynk.cc
9 | Blynk community: http://community.blynk.cc
10 | Social networks: http://www.fb.com/blynkapp
11 | http://twitter.com/blynk_app
12 |
13 | This example shows how to initialize your W600 board
14 | and connect it to Blynk.
15 |
16 | Don't forget to change WIFI_SSID, WIFI_PASS and BLYNK_AUTH ;)
17 | """
18 |
19 | import BlynkLib
20 | import machine
21 | from easyw600 import *
22 |
23 | WIFI_SSID = 'YourWiFiNetwork'
24 | WIFI_PASS = 'YourWiFiPassword'
25 |
26 | BLYNK_AUTH = 'YourAuthToken'
27 |
28 |
29 | wifi = connect(WIFI_SSID, WIFI_PASS)
30 |
31 | print("Connecting to Blynk...")
32 | blynk = BlynkLib.Blynk(BLYNK_AUTH, log=print)
33 |
34 | @blynk.on("connected")
35 | def blynk_connected(ping):
36 | print('Blynk ready. Ping:', ping, 'ms')
37 |
38 | @blynk.VIRTUAL_WRITE(1)
39 | def v1(param):
40 | print('!!!VIRTUAL_WRITE', param)
41 |
42 | @blynk.ON("V2")
43 | def v2(param):
44 | print('!!!ON')
45 |
46 | @blynk.on("V3")
47 | def v3(param):
48 | print('!!!on')
49 |
50 | def runLoop():
51 | while True:
52 | blynk.run()
53 | machine.idle()
54 |
55 | runLoop()
56 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | description-file = README.md
3 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | from setuptools import setup
4 |
5 | setup(
6 | name = "blynk-library-python",
7 | version = "1.0.0", #blynk.lib.__version__
8 | description = "Blynk library",
9 | platforms = "any",
10 | url = "http://www.blynk.cc",
11 | license = "MIT",
12 | author = "Volodymyr Shymanskyy",
13 | author_email = "vshymanskyi@gmail.com",
14 |
15 | py_modules = ['BlynkLib', 'BlynkEdgent', 'BlynkTimer'],
16 |
17 | classifiers = [
18 | "Topic :: Software Development :: Libraries :: Python Modules",
19 | "Development Status :: 4 - Beta",
20 | "License :: OSI Approved :: MIT License",
21 | "Operating System :: POSIX :: Linux",
22 | "Operating System :: Microsoft :: Windows",
23 | "Operating System :: MacOS :: MacOS X"
24 | ]
25 | )
26 |
--------------------------------------------------------------------------------