luacode.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Copyright (C) 2015-2016 Peter Magnusson <peter@birchroad.net>
  4. # these functions are needed on the device, otherwise they will be
  5. # uploaded during prepare
  6. LUA_FUNCTIONS = ['recv_block', 'recv_name','recv','shafile', 'send_block', 'send_file', 'send']
  7. DOWNLOAD_FILE = "file.open('{filename}') print(file.seek('end', 0)) file.seek('set', {bytes_read}) uart.write(0, file.read({chunk_size}))file.close()"
  8. PRINT_FILE = "file.open('{filename}') print('---{filename}---') print(file.read()) file.close() print('---')"
  9. LIST_FILES = 'for key,value in pairs(file.list()) do print(key,value) end'
  10. #NUL = \000, ACK = \006
  11. RECV_LUA = \
  12. r"""
  13. function recv_block(d)
  14. if string.byte(d, 1) == 1 then
  15. size = string.byte(d, 2)
  16. uart.write(0,'\006')
  17. if size > 0 then
  18. file.write(string.sub(d, 3, 3+size-1))
  19. else
  20. file.close()
  21. uart.on('data')
  22. uart.setup(0,{baud},8,0,1,1)
  23. end
  24. else
  25. uart.write(0, '\021' .. d)
  26. uart.setup(0,{baud},8,0,1,1)
  27. uart.on('data')
  28. end
  29. end
  30. function recv_name(d) d = string.gsub(d, '\000', '') file.remove(d) file.open(d, 'w') uart.on('data', 130, recv_block, 0) uart.write(0, '\006') end
  31. function recv() uart.setup(0,{baud},8,0,1,0) uart.on('data', '\000', recv_name, 0) uart.write(0, 'C') end
  32. function shafile(f) file.open(f, "r") print(crypto.toHex(crypto.hash("sha1",file.read()))) file.close() end
  33. """
  34. SEND_LUA = \
  35. r"""
  36. function send_block(d) l = string.len(d) uart.write(0, '\001' .. string.char(l) .. d .. string.rep('#', 128 - l)) return l end
  37. function send_file(f) file.open(f) s=file.seek('end', 0) p=0 uart.on('data', 1, function(data)
  38. if data == '\006' and p<s then file.seek('set',p) p=p+send_block(file.read(128)) else
  39. send_block('') file.close() uart.on('data') print('interrupted') end end, 0) uart.write(0, f .. '\000')
  40. end
  41. function send(f) uart.on('data', 1, function (data)
  42. uart.on('data') if data == 'C' then send_file(f) else print('transfer interrupted') end end, 0)
  43. end
  44. """
  45. UART_SETUP = 'uart.setup(0,{baud},8,0,1,1)'