8000 Implement saving file from string to board · arduino/micropython.js@e1ad10c · GitHub
[go: up one dir, main page]

Skip to content

Commit e1ad10c

Browse files
committed
Implement saving file from string to board
1 parent 8e5f4e7 commit e1ad10c

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

examples/07_save_file.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
const Board = require('../micropython.js')
2+
3+
let content = `
4+
"""
5+
Blinky
6+
"""
7+
from machine import Pin
8+
from time import sleep
9+
# Nano Connect rp2040 internal LED
10+
led = Pin(6, Pin.OUT)
11+
while True:
12+
print('on')
13+
led.on()
14+
sleep(0.25)
15+
print('off')
16+
led.off()
17+
sleep(0.25)
18+
`
19+
20+
console.log('connect')
21+
let board = new Board()
22+
board.open(process.env.PORT || '/dev/tty.usbmodem141101')
23+
.then(async () => {
24+
try {
25+
await board.fs_save(content, 'test.py')
26+
console.log('disconnect')
27+
} catch(e) {
28+
console.log('error', e)
29+
}
30+
board.close()
31+
})

micropython.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,27 @@ class MicroPythonBoard {
225225
return Promise.reject(new Error(`Must specify source and destination paths`))
226226
}
227227

228+
async fs_save(content, dest) {
229+
if (content && dest) {
230+
if (typeof content === 'string') {
231+
content = Buffer.from(content)
232+
}
233+
await this.enter_raw_repl()
234+
let output = await this.exec_raw({
235+
command: `f=open('${dest}','w')\nw=f.write`
236+
})
237+
for (let i = 0; i < content.length; i+=64) {
238+
let slice = content.slice(i, i+64)
239+
slice = slice.toString()
240+
slice = slice.replace(/"""/g, `\\"\\"\\"`)
241+
await this.serial.write(`w("""${slice}""")`)
242+
await this.serial.write(`\x04`)
243+
await sleep(50)
244+
}
245+
return this.exit_raw_repl()
246+
} else {
247+
return Promise.reject(new Error(`Must specify content and destination path`))
248+
}
228249
}
229250

230251
async fs_mkdir() {

0 commit comments

Comments
 (0)
0