forked from gepd/uPiotMicroPythonTool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsampy.py
More file actions
292 lines (229 loc) · 11.1 KB
/
sampy.py
File metadata and controls
292 lines (229 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# Adafruit MicroPython Tool - Command Line Interface
# Author: Tony DiCola
# Copyright (c) 2016 Adafruit Industries
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import re
import os
from sublime import platform, set_timeout_async
from ..tools.ampy import files
from ..tools import serial
from ..tools.repl import Repl
_board = None
class Sampy:
_board = None
def __init__(self, port, baudrate=115200, data_consumer=None):
"""ampy - Adafruit MicroPython Tool
Ampy is a tool to control MicroPython boards over a serial connection.
Using ampy you can manipulate files on the board's internal filesystem
and even run scripts.
"""
global _board
if _board is not None:
try:
_board.close()
except:
pass
# On Windows fix the COM port path name for ports above 9 (see comment
# in windows_full_port_name function).
if platform() == 'windows':
port = windows_full_port_name(port)
try:
raw = serial.serial_dict[port].raw()
except KeyError as e:
print("console not connected")
return
_board = Repl(serial=raw, data_consumer=data_consumer)
def get(self, remote_file, local_file=None):
"""
Retrieve a file from the board.
Get will download a file from the board and print its contents or
save it locally. You must pass at least one argument which is the path
to the file to download from the board. If you don't specify a second
argument then the file contents will be printed to standard output.
However if you pass a file name as the second argument then the
contents of the downloaded file will be saved to that file
(overwriting anything inside it!).
For example to retrieve the boot.py and print it out run:
ampy --port /board/serial/port get boot.py
Or to get main.py and save it as main.py locally run:
ampy --port /board/serial/port get main.py main.py
"""
# Get the file contents.
global print_text
board_files = files.Files(_board)
contents = board_files.get(remote_file)
# Print the file out if no local file was provided, otherwise save it.
if local_file is None:
return contents.decode('utf-8')
else:
local_file.write(contents)
def mkdir(self, directory):
"""
Create a directory on the board.
Mkdir will create the specified directory on the board. One argument
is required, the full path of the directory to create.
Note that you cannot recursively create a hierarchy of directories with
one mkdir command, instead you must create each parent directory with
separate mkdir command calls.
For example to make a directory under the root called 'code':
ampy --port /board/serial/port mkdir /code
"""
# Run the mkdir command.
board_files = files.Files(_board)
board_files.mkdir(directory)
def ls(self, directory=''):
"""List contents of a directory on the board.
Can pass an optional argument which is the path to the directory. The
default is to list the contents of the root, /, path.
For example to list the contents of the root run:
ampy --port /board/serial/port ls
Or to list the contents of the /foo/bar directory on the board run:
ampy --port /board/serial/port ls /foo/bar
"""
# List each file/directory on a separate line.
items = []
board_files = files.Files(_board)
for f in board_files.ls(directory):
items.append(f)
return items
def put(self, local, remote=None):
"""Put a file or folder and its contents on the board.
Put will upload a local file or folder to the board. If the file
already exists on the board it will be overwritten with no warning!
You must pass at least one argument which is the path to the local
file/folder to upload. If the item to upload is a folder then it will
be copied to the board recursively with its entire child structure.
You can pass a second optional argument which is the path and name of
the file/folder to put to on the connected board.
For example to upload a main.py from the current directory to the
board's root run:
ampy --port /board/serial/port put main.py
Or to upload a board_boot.py from a ./foo subdirectory and save it as
boot.py in the board's root run:
ampy --port /board/serial/port put ./foo/board_boot.py boot.py
To upload a local folder adafruit_library and all of its child
files/folders as an item under the board's root run:
ampy --port /board/serial/port put adafruit_library
Or to put a local folder adafruit_library on the board under the path
/lib/adafruit_library on the board run:
ampy --port /board/serial/port put adafruit_library
/lib/adafruit_library
"""
# Use the local filename if no remote filename is provided.
if remote is None:
remote = os.path.basename(os.path.abspath(local))
# Check if path is a folder and do recursive copy of everything inside
# it. Otherwise it's a file and should simply be copied over.
if os.path.isdir(local):
# Directory copy, create the directory and walk all children to
# copy over the files.
board_files = files.Files(_board)
for parent, child_dirs, child_files in os.walk(local):
# Create board filesystem absolute path to parent directory.
remote_parent = posixpath.normpath(
posixpath.join(remote, os.path.relpath(parent, local)))
try:
# Create remote parent directory.
board_files.mkdir(remote_parent)
# Loop through all the files and put them on the board too.
for filename in child_files:
with open(os.path.join(parent, filename), 'rb') as f:
remote_filename = posixpath.join(
remote_parent, filename)
board_files.put(remote_filename, f.read())
except files.DirectoryExistsError:
# Ignore errors for directories that already exist.
pass
else:
# File copy, open the file and copy its contents to the board.
# Put the file on the board.
with open(local, 'rb') as infile:
board_files = files.Files(_board)
board_files.put(remote, infile.read())
def rm(self, remote_file):
"""Remove a file from the board.
Remove the specified file from the board's filesystem. Must specify
one argument which is the path to the file to delete. Note that this
can't delete directories which have files inside them, but can delete
empty directories.
For example to delete main.py from the root of a board run:
ampy --port /board/serial/port rm main.py
"""
# Delete the provided file/directory on the board.
board_files = files.Files(_board)
board_files.rm(remote_file)
def rmdir(self, remote_folder):
"""Forcefully remove a folder and all its children from the board.
Remove the specified folder from the board's filesystem. Must specify
one argument which is the path to the folder to delete. This will
delete the directory and ALL of its children recursively, use with
caution!
For example to delete everything under /adafruit_library from the root
of a board run:
ampy --port /board/serial/port rmdir adafruit_library
"""
# Delete the provided file/directory on the board.
board_files = files.Files(_board)
board_files.rmdir(remote_folder)
def run(self, local_file, no_output=None):
"""Run a script and print its output.
Run will send the specified file to the board and execute it
immediately.
Any output from the board will be printed to the console (note that
this is not a 'shell' and you can't send input to the program).
Note that if your code has a main or infinite loop you should add the
--no-output option. This will run the script and immediately exit
without waiting for the script to finish and print output.
For example to run a test.py script and print any output after it
finishes:
ampy --port /board/serial/port run test.py
Or to run test.py and not wait for it to finish:
ampy --port /board/serial/port run --no-output test.py
"""
# Run the provided file and print its output.
board_files = files.Files(_board)
output = board_files.run(local_file)
if output is not None:
return output.decode('utf-8')
def close(self):
_board.close()
def reset(self):
"""Perform soft reset/reboot of the board.
Will connect to the board and perform a soft reset. No arguments are
necessary:
ampy --port /board/serial/port reset
"""
# Enter then exit the raw REPL, in the process the board will be soft
# reset (part of enter raw REPL).
_board.enter_raw_repl()
_board.exit_raw_repl()
def windows_full_port_name(portname):
# Helper function to generate proper Windows COM port paths. Apparently
# Windows requires COM ports above 9 to have a special path, where ports
# below 9 are just referred to by COM1, COM2, etc. (wacky!) See this post
# for more info and where this code came from:
# http://eli.thegreenplace.net/2009/07/31/listing-all-serial-ports-on-windows-with-python/
m = re.match('^COM(\d+)$', portname)
if m and int(m.group(1)) < 10:
return portname
else:
return '\\\\.\\{0}'.format(portname)