cerapi.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. # A demo of the Windows CE Remote API
  2. #
  3. # This connects to a CE device, and interacts with it.
  4. import wincerapi
  5. import win32event
  6. import win32api
  7. import win32con
  8. import os
  9. import sys
  10. import getopt
  11. def DumpPythonRegistry():
  12. try:
  13. h = wincerapi.CeRegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, "Software\\Python\\PythonCore\\%s\\PythonPath" % sys.winver)
  14. except win32api.error:
  15. print("The remote device does not appear to have Python installed")
  16. return 0
  17. path, typ = wincerapi.CeRegQueryValueEx(h, None)
  18. print("The remote PythonPath is '%s'" % (str(path), ))
  19. h.Close()
  20. return 1
  21. def DumpRegistry(root, level=0):
  22. # A recursive dump of the remote registry to test most functions.
  23. h = wincerapi.CeRegOpenKeyEx(win32con.HKEY_LOCAL_MACHINE, None)
  24. level_prefix = " " * level
  25. index = 0
  26. # Enumerate values.
  27. while 1:
  28. try:
  29. name, data, typ = wincerapi.CeRegEnumValue(root, index)
  30. except win32api.error:
  31. break
  32. print("%s%s=%s" % (level_prefix, name, repr(str(data))))
  33. index = index+1
  34. # Now enumerate all keys.
  35. index=0
  36. while 1:
  37. try:
  38. name, klass = wincerapi.CeRegEnumKeyEx(root, index)
  39. except win32api.error:
  40. break
  41. print("%s%s\\" % (level_prefix, name))
  42. subkey = wincerapi.CeRegOpenKeyEx(root, name)
  43. DumpRegistry(subkey, level+1)
  44. index = index+1
  45. def DemoCopyFile():
  46. # Create a file on the device, and write a string.
  47. cefile = wincerapi.CeCreateFile("TestPython", win32con.GENERIC_WRITE, 0, None, win32con.OPEN_ALWAYS, 0, None)
  48. wincerapi.CeWriteFile(cefile, "Hello from Python")
  49. cefile.Close()
  50. # reopen the file and check the data.
  51. cefile = wincerapi.CeCreateFile("TestPython", win32con.GENERIC_READ, 0, None, win32con.OPEN_EXISTING, 0, None)
  52. if wincerapi.CeReadFile(cefile, 100) != "Hello from Python":
  53. print("Couldnt read the data from the device!")
  54. cefile.Close()
  55. # Delete the test file
  56. wincerapi.CeDeleteFile("TestPython")
  57. print("Created, wrote to, read from and deleted a test file!")
  58. def DemoCreateProcess():
  59. try:
  60. hp, ht, pid, tid = wincerapi.CeCreateProcess("Windows\\Python.exe", "", None, None, 0, 0, None, "", None)
  61. # Not necessary, except to see if handle closing raises an exception
  62. # (if auto-closed, the error is suppressed)
  63. hp.Close()
  64. ht.Close()
  65. print("Python is running on the remote device!")
  66. except win32api.error as xxx_todo_changeme1:
  67. (hr, fn, msg) = xxx_todo_changeme1.args
  68. print("Couldnt execute remote process -", msg)
  69. def DumpRemoteMachineStatus():
  70. ACLineStatus, BatteryFlag, BatteryLifePercent, BatteryLifeTime, BatteryFullLifeTime, BackupBatteryFlag, BackupBatteryLifePercent, BackupBatteryLifeTime, BackupBatteryLifeTime = \
  71. wincerapi.CeGetSystemPowerStatusEx()
  72. if ACLineStatus:
  73. power = "AC"
  74. else:
  75. power = "battery"
  76. if BatteryLifePercent==255:
  77. batPerc = "unknown"
  78. else:
  79. batPerc = BatteryLifePercent
  80. print("The batteries are at %s%%, and is currently being powered by %s" % (batPerc, power))
  81. memLoad, totalPhys, availPhys, totalPage, availPage, totalVirt, availVirt = \
  82. wincerapi.CeGlobalMemoryStatus()
  83. print("The memory is %d%% utilized." % (memLoad))
  84. print("%-20s%-10s%-10s" % ("", "Total", "Avail"))
  85. print("%-20s%-10s%-10s" % ("Physical Memory", totalPhys, availPhys))
  86. print("%-20s%-10s%-10s" % ("Virtual Memory", totalVirt, availVirt))
  87. print("%-20s%-10s%-10s" % ("Paging file", totalPage, availPage))
  88. storeSize, freeSize = wincerapi.CeGetStoreInformation()
  89. print("%-20s%-10s%-10s" % ("File store", storeSize, freeSize))
  90. print("The CE temp path is", wincerapi.CeGetTempPath())
  91. print("The system info for the device is", wincerapi.CeGetSystemInfo())
  92. def DumpRemoteFolders():
  93. # Dump all special folders possible.
  94. for name, val in list(wincerapi.__dict__.items()):
  95. if name[:6]=="CSIDL_":
  96. try:
  97. loc = str(wincerapi.CeGetSpecialFolderPath(val))
  98. print("Folder %s is at %s" % (name, loc))
  99. except win32api.error as details:
  100. pass
  101. # Get the shortcut targets for the "Start Menu"
  102. print("Dumping start menu shortcuts...")
  103. try:
  104. startMenu = str(wincerapi.CeGetSpecialFolderPath(wincerapi.CSIDL_STARTMENU))
  105. except win32api.error as details:
  106. print("This device has no start menu!", details)
  107. startMenu = None
  108. if startMenu:
  109. for fileAttr in wincerapi.CeFindFiles(os.path.join(startMenu, "*")):
  110. fileName = fileAttr[8]
  111. fullPath = os.path.join(startMenu, str(fileName))
  112. try:
  113. resolved = wincerapi.CeSHGetShortcutTarget(fullPath)
  114. except win32api.error as xxx_todo_changeme:
  115. (rc, fn, msg) = xxx_todo_changeme.args
  116. resolved = "#Error - %s" % msg
  117. print("%s->%s" % (fileName, resolved))
  118. # print "The start menu is at",
  119. # print wincerapi.CeSHGetShortcutTarget("\\Windows\\Start Menu\\Shortcut to Python.exe.lnk")
  120. def usage():
  121. print("Options:")
  122. print("-a - Execute all demos")
  123. print("-p - Execute Python process on remote device")
  124. print("-r - Dump the remote registry")
  125. print("-f - Dump all remote special folder locations")
  126. print("-s - Dont dump machine status")
  127. print("-y - Perform asynch init of CE connection")
  128. def main():
  129. async_init = bStartPython = bDumpRegistry = bDumpFolders = 0
  130. bDumpStatus = 1
  131. try:
  132. opts, args = getopt.getopt(sys.argv[1:], "apr")
  133. except getopt.error as why:
  134. print("Invalid usage:", why)
  135. usage()
  136. return
  137. for o, v in opts:
  138. if o=="-a":
  139. bStartPython = bDumpRegistry = bDumpStatus = bDumpFolders = asynch_init = 1
  140. if o=="-p":
  141. bStartPython=1
  142. if o=="-r":
  143. bDumpRegistry=1
  144. if o=="-s":
  145. bDumpStatus=0
  146. if o=="-f":
  147. bDumpFolders = 1
  148. if o=="-y":
  149. print("Doing asynch init of CE connection")
  150. async_init = 1
  151. if async_init:
  152. event, rc = wincerapi.CeRapiInitEx()
  153. while 1:
  154. rc = win32event.WaitForSingleObject(event, 500)
  155. if rc==win32event.WAIT_OBJECT_0:
  156. # We connected.
  157. break
  158. else:
  159. print("Waiting for Initialize to complete (picture a Cancel button here :)")
  160. else:
  161. wincerapi.CeRapiInit()
  162. print("Connected to remote CE device.")
  163. try:
  164. verinfo = wincerapi.CeGetVersionEx()
  165. print("The device is running windows CE version %d.%d - %s" % (verinfo[0], verinfo[1], verinfo[4]))
  166. if bDumpStatus:
  167. print("Dumping remote machine status")
  168. DumpRemoteMachineStatus()
  169. if bDumpRegistry:
  170. print("Dumping remote registry...")
  171. DumpRegistry(win32con.HKEY_LOCAL_MACHINE)
  172. if bDumpFolders:
  173. print("Dumping remote folder information")
  174. DumpRemoteFolders()
  175. DemoCopyFile()
  176. if bStartPython:
  177. print("Starting remote Python process")
  178. if DumpPythonRegistry():
  179. DemoCreateProcess()
  180. else:
  181. print("Not trying to start Python, as it's not installed")
  182. finally:
  183. wincerapi.CeRapiUninit()
  184. print("Disconnected")
  185. if __name__=='__main__':
  186. main()