klib.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. def woke_up():
  2. with uses("machine") as machine:
  3. return machine.reset_cause() == machine.DEEPSLEEP_RESET
  4. def poweroff(wake_in=0):
  5. with uses("machine") as machine:
  6. if wake_in:
  7. rtc = machine.RTC()
  8. rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
  9. rtc.alarm(rtc.ALARM0, int(wake_in * 1000))
  10. machine.deepsleep()
  11. def turbo():
  12. class Turbo:
  13. impl = __import__("machine")
  14. def __enter__(self):
  15. # memleak ?
  16. self.last = self.impl.freq()
  17. self.impl.freq(160000000)
  18. def __exit__(*self):
  19. # memleak ?
  20. # __import__('machine').freq(80000000)
  21. self.impl.freq(self.last)
  22. del self.last
  23. return Turbo()
  24. async def sha256(f, block=512):
  25. with uses("uhashlib", "ubinascii"):
  26. h = uhashlib.sha256()
  27. if isinstance(f, str):
  28. try:
  29. f = open(f, "rb")
  30. except OSError:
  31. f = None
  32. while f:
  33. if use.aio:
  34. await uses.aio.idle()
  35. data = f.read(block)
  36. if data:
  37. h.update(data)
  38. else:
  39. break
  40. if f:
  41. f.close()
  42. return ubinascii.hexlify(h.digest()).decode() # .lower()
  43. async def urlopen(url, data=None, method="GET"):
  44. if data is not None and method == "GET":
  45. method = "POST"
  46. proto, dummy, host = url.split("/", 2)
  47. if host.find("/")>0:
  48. host,path = host.split("/",1)
  49. else:
  50. path=""
  51. ssl = proto[4] == "s"
  52. if ":" in host:
  53. host, port = host.split(":", 1)
  54. port = int(port)
  55. elif ssl:
  56. port = 443
  57. else:
  58. port = 80
  59. with uses("usocket") as usocket:
  60. addr = usocket.getaddrinfo(host, port)[0][4]
  61. s = usocket.socket()
  62. s.connect(addr)
  63. if ssl:
  64. s = __import__("ussl").wrap_socket(s)
  65. sw = s.write
  66. sw(method)
  67. sw(b" ")
  68. sw(b"/")
  69. sw(path)
  70. sw(b" HTTP/1.0\r\nHost: ")
  71. sw(host)
  72. sw(b"\r\n")
  73. if data:
  74. sw(b"Content-Length: ")
  75. sw(str(len(data)))
  76. sw(b"\r\n")
  77. sw(b"\r\n")
  78. if data:
  79. sw(data)
  80. l = s.readline()
  81. protover, status, msg = l.split(None, 2)
  82. status = int(status)
  83. if status == 404:
  84. raise OSError(2, "404 [%s]" % url)
  85. elif status != 200:
  86. print( status , method, url )
  87. while True:
  88. l = s.readline().lower()
  89. if not l or l == b"\r\n":
  90. break
  91. if l.startswith(b"transfer-encoding:"):
  92. if b"chunked" in l:
  93. raise ValueError("Unsupported " + l)
  94. elif l.startswith(b"location:"):
  95. raise NotImplementedError("Redirect N/I")
  96. if use.aio:
  97. await use.aio.idle()
  98. return s
  99. def reboot():
  100. __import__('machine').reset()
  101. def gpio(*argv,**kw):
  102. import sys
  103. with uses('m.%s'% sys.platform) as mod:
  104. try:
  105. return mod.gpio(*argv,**kw)
  106. finally:
  107. del mod
  108. #this one could gc, when all opened files are closed, may need rewrite as a module
  109. def fopen(*argv, **kw):
  110. import m.fopen
  111. return m.fopen.fopen(*argv, **kw)
  112. def Pin(pin,mode='r',value=0, **kw):
  113. import m.pin
  114. thepin=gpio(pin,mode)
  115. return m.pin.Pin(pin, thepin, mode,value, **kw)
  116. def HBridge(*argv, **kw):
  117. import m.hbridge
  118. return m.hbridge.HBridge(*argv, **kw)
  119. def init_adc(*argv, **kw):
  120. try:
  121. return ADC
  122. except:
  123. print("loading ADC(MCP3008)")
  124. import m.MCP3008
  125. return ADC
  126. def ping(*argv, **kw):
  127. with uses('m.uping'):
  128. m.uping.ping(*argv,**kw)