PageRenderTime 49ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/src/LabJackPython.py

https://github.com/arch-web-labs/LabJackPython
Python | 3579 lines | 3334 code | 92 blank | 153 comment | 24 complexity | 48d0b0c530feeeaea6134fb86703de43 MD5 | raw file
  1. """
  2. Multi-Platform Python wrapper that implements functions from the LabJack
  3. Windows UD Driver, and the Exodriver.
  4. This python wrapper is intended to make working with your LabJack device easy. The functions contained in this module are helper and device agnostic functions. This module provides the base Device class which the U3, U6, and UE9 classes inherit from.
  5. A typical user should start with their device's module, such as u3.py.
  6. """
  7. # We use the 'with' keyword to manage the thread-safe device lock. It's built-in on 2.6; 2.5 requires an import.
  8. from __future__ import with_statement
  9. import collections
  10. import ctypes
  11. import os
  12. import struct
  13. from decimal import Decimal
  14. import socket
  15. import Modbus
  16. import atexit # For auto-closing devices
  17. import threading # For a thread-safe device lock
  18. LABJACKPYTHON_VERSION = "10-22-2012"
  19. SOCKET_TIMEOUT = 3
  20. LJSOCKET_TIMEOUT = 62
  21. BROADCAST_SOCKET_TIMEOUT = 1
  22. MAX_USB_PACKET_LENGTH = 64
  23. NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS = 5
  24. class LabJackException(Exception):
  25. """Custom Exception meant for dealing specifically with LabJack Exceptions.
  26. Error codes are either going to be a LabJackUD error code or a -1. The -1 implies
  27. a python wrapper specific error.
  28. WINDOWS ONLY
  29. If errorString is not specified then errorString is set by errorCode
  30. """
  31. def __init__(self, ec = 0, errorString = ''):
  32. self.errorCode = ec
  33. self.errorString = errorString
  34. if not self.errorString:
  35. try:
  36. pString = ctypes.create_string_buffer(256)
  37. staticLib.ErrorToString(ctypes.c_long(self.errorCode), ctypes.byref(pString))
  38. self.errorString = pString.value
  39. except:
  40. self.errorString = str(self.errorCode)
  41. def __str__(self):
  42. return self.errorString
  43. # Raised when a low-level command raises an error.
  44. class LowlevelErrorException(LabJackException): pass
  45. # Raised when the return value of OpenDevice is null.
  46. class NullHandleException(LabJackException):
  47. def __init__(self):
  48. self.errorString = "Couldn't open device. Please check that the device you are trying to open is connected."
  49. def errcheck(ret, func, args):
  50. """
  51. Whenever a function is called through ctypes, the return value is passed to
  52. this function to be checked for errors.
  53. Support for errno didn't come until 2.6, so Python 2.5 people should
  54. upgrade.
  55. """
  56. if ret == -1:
  57. try:
  58. ec = ctypes.get_errno()
  59. raise LabJackException(ec, "Exodriver returned error number %s" % ec)
  60. except AttributeError:
  61. raise LabJackException(-1, "Exodriver returned an error, but LabJackPython is unable to read the error code. Upgrade to Python 2.6 for this functionality.")
  62. else:
  63. return ret
  64. def _loadLinuxSo():
  65. """
  66. Attempts to load the liblabjackusb.so for Linux.
  67. """
  68. try:
  69. l = ctypes.CDLL("liblabjackusb.so", use_errno=True)
  70. except TypeError:
  71. l = ctypes.CDLL("liblabjackusb.so")
  72. l.LJUSB_Stream.errcheck = errcheck
  73. l.LJUSB_Read.errcheck = errcheck
  74. return l
  75. def _loadMacDylib():
  76. """
  77. Attempts to load the liblabjackusb.dylib for Mac OS X.
  78. """
  79. try:
  80. l = ctypes.CDLL("liblabjackusb.dylib", use_errno=True)
  81. except TypeError:
  82. l = ctypes.CDLL("liblabjackusb.dylib")
  83. l.LJUSB_Stream.errcheck = errcheck
  84. l.LJUSB_Read.errcheck = errcheck
  85. return l
  86. def _loadLibrary():
  87. """_loadLibrary()
  88. Returns a ctypes dll pointer to the library.
  89. """
  90. if(os.name == 'posix'):
  91. try:
  92. return _loadLinuxSo()
  93. except OSError, e:
  94. pass # We may be on Mac.
  95. except Exception, e:
  96. raise LabJackException("Could not load the Linux SO for some reason other than it not being installed. Ethernet connectivity only.\n\n The error was: %s" % e)
  97. try:
  98. return _loadMacDylib()
  99. except OSError, e:
  100. raise LabJackException("Could not load the Exodriver driver. Ethernet connectivity only.\n\nCheck that the Exodriver is installed, and the permissions are set correctly.\nThe error message was: %s" % e)
  101. except Exception, e:
  102. raise LabJackException("Could not load the Mac Dylib for some reason other than it not being installed. Ethernet connectivity only.\n\n The error was: %s" % e)
  103. if(os.name == 'nt'):
  104. try:
  105. return ctypes.windll.LoadLibrary("labjackud")
  106. except Exception, e:
  107. raise LabJackException("Could not load labjackud driver. Ethernet connectivity availability only.\n\n The error was: %s" % e)
  108. try:
  109. staticLib = _loadLibrary()
  110. except LabJackException, e:
  111. print "%s: %s" % ( type(e), e )
  112. staticLib = None
  113. # Attempt to load the windows Skymote library.
  114. try:
  115. skymoteLib = ctypes.windll.LoadLibrary("liblabjackusb")
  116. except:
  117. skymoteLib = None
  118. class Device(object):
  119. """Device(handle, localId = None, serialNumber = None, ipAddress = "", type = None)
  120. Creates a simple 0 with the following functions:
  121. write(writeBuffer) -- Writes a buffer.
  122. writeRegister(addr, value) -- Writes a value to a modbus register
  123. read(numBytes) -- Reads until a packet is received.
  124. readRegister(addr, numReg = None, format = None) -- Reads a modbus register.
  125. ping() -- Pings the device. Returns true if communication worked.
  126. close() -- Closes the device.
  127. reset() -- Resets the device.
  128. """
  129. def __init__(self, handle, localId = None, serialNumber = None, ipAddress = "", devType = None):
  130. # Not saving the handle as a void* causes many problems on 64-bit machines.
  131. if isinstance(handle, int):
  132. self.handle = ctypes.c_void_p(handle)
  133. else:
  134. self.handle = handle
  135. self.localId = localId
  136. self.serialNumber = serialNumber
  137. self.ipAddress = ipAddress
  138. self.devType = devType
  139. self.debug = False
  140. self.streamConfiged = False
  141. self.streamStarted = False
  142. self.streamPacketOffset = 0
  143. self._autoCloseSetup = False
  144. self.modbusPrependZeros = True
  145. self.deviceLock = threading.Lock()
  146. self.deviceName = "LabJack"
  147. def _writeToLJSocketHandle(self, writeBuffer, modbus):
  148. #if modbus is True and self.modbusPrependZeros:
  149. # writeBuffer = [ 0, 0 ] + writeBuffer
  150. packFormat = "B" * len(writeBuffer)
  151. tempString = struct.pack(packFormat, *writeBuffer)
  152. if modbus:
  153. self.handle.modbusSocket.send(tempString)
  154. else:
  155. self.handle.crSocket.send(tempString)
  156. return writeBuffer
  157. def _writeToUE9TCPHandle(self, writeBuffer, modbus):
  158. packFormat = "B" * len(writeBuffer)
  159. tempString = struct.pack(packFormat, *writeBuffer)
  160. if modbus is True:
  161. if self.handle.modbus is None:
  162. raise LabJackException("Modbus port is not available. Please upgrade to UE9 Comm firmware 1.43 or higher.")
  163. self.handle.modbus.send(tempString)
  164. else:
  165. self.handle.data.send(tempString)
  166. return writeBuffer
  167. def _writeToExodriver(self, writeBuffer, modbus):
  168. if modbus is True and self.modbusPrependZeros:
  169. writeBuffer = [ 0, 0 ] + writeBuffer
  170. newA = (ctypes.c_byte*len(writeBuffer))(0)
  171. for i in range(len(writeBuffer)):
  172. newA[i] = ctypes.c_byte(writeBuffer[i])
  173. writeBytes = staticLib.LJUSB_Write(self.handle, ctypes.byref(newA), len(writeBuffer))
  174. if(writeBytes != len(writeBuffer)):
  175. raise LabJackException( "Could only write %s of %s bytes." % (writeBytes, len(writeBuffer) ) )
  176. return writeBuffer
  177. def _writeToUDDriver(self, writeBuffer, modbus):
  178. if self.devType == 0x501:
  179. newA = (ctypes.c_byte*len(writeBuffer))(0)
  180. for i in range(len(writeBuffer)):
  181. newA[i] = ctypes.c_byte(writeBuffer[i])
  182. writeBytes = skymoteLib.LJUSB_IntWrite(self.handle, 1, ctypes.byref(newA), len(writeBuffer))
  183. if(writeBytes != len(writeBuffer)):
  184. raise LabJackException( "Could only write %s of %s bytes." % (writeBytes, len(writeBuffer) ) )
  185. else:
  186. if modbus is True and self.devType == 9:
  187. dataWords = len(writeBuffer)
  188. writeBuffer = [0, 0xF8, 0, 0x07, 0, 0] + writeBuffer #modbus low-level function
  189. if dataWords % 2 != 0:
  190. dataWords = (dataWords+1)/2
  191. writeBuffer.append(0)
  192. else:
  193. dataWords = dataWords/2
  194. writeBuffer[2] = dataWords
  195. setChecksum(writeBuffer)
  196. elif modbus is True and self.modbusPrependZeros:
  197. writeBuffer = [ 0, 0 ] + writeBuffer
  198. eGetRaw(self.handle, LJ_ioRAW_OUT, 0, len(writeBuffer), writeBuffer)
  199. return writeBuffer
  200. def write(self, writeBuffer, modbus = False, checksum = True):
  201. """write([writeBuffer], modbus = False)
  202. Writes the data contained in writeBuffer to the device. writeBuffer must be a list of
  203. bytes.
  204. """
  205. if self.handle is None:
  206. raise LabJackException("The device handle is None.")
  207. if checksum:
  208. setChecksum(writeBuffer)
  209. if(isinstance(self.handle, LJSocketHandle)):
  210. wb = self._writeToLJSocketHandle(writeBuffer, modbus)
  211. elif(isinstance(self.handle, UE9TCPHandle)):
  212. wb = self._writeToUE9TCPHandle(writeBuffer, modbus)
  213. else:
  214. if os.name == 'posix':
  215. wb = self._writeToExodriver(writeBuffer, modbus)
  216. elif os.name == 'nt':
  217. wb = self._writeToUDDriver(writeBuffer, modbus)
  218. if self.debug: print "Sent: ", hexWithoutQuotes(wb)
  219. def read(self, numBytes, stream = False, modbus = False):
  220. """read(numBytes, stream = False, modbus = False)
  221. Blocking read until a packet is received.
  222. """
  223. readBytes = 0
  224. if self.handle is None:
  225. raise LabJackException("The device handle is None.")
  226. if(isinstance(self.handle, LJSocketHandle)):
  227. return self._readFromLJSocketHandle(numBytes, modbus, stream)
  228. elif(isinstance(self.handle, UE9TCPHandle)):
  229. return self._readFromUE9TCPHandle(numBytes, stream, modbus)
  230. else:
  231. if(os.name == 'posix'):
  232. return self._readFromExodriver(numBytes, stream, modbus)
  233. elif os.name == 'nt':
  234. return self._readFromUDDriver(numBytes, stream, modbus)
  235. def _readFromLJSocketHandle(self, numBytes, modbus, spont = False):
  236. """
  237. Reads from LJSocket. Returns the result as a list.
  238. """
  239. if modbus:
  240. rcvString = self.handle.modbusSocket.recv(numBytes)
  241. elif spont:
  242. rcvString = self.handle.spontSocket.recv(numBytes)
  243. else:
  244. rcvString = self.handle.crSocket.recv(numBytes)
  245. readBytes = len(rcvString)
  246. packFormat = "B" * readBytes
  247. rcvDataBuff = struct.unpack(packFormat, rcvString)
  248. return list(rcvDataBuff)
  249. def _readFromUE9TCPHandle(self, numBytes, stream, modbus):
  250. if stream is True:
  251. rcvString = self.handle.stream.recv(numBytes)
  252. return rcvString
  253. else:
  254. if modbus is True:
  255. if self.handle.modbus is None:
  256. raise LabJackException("Modbus port is not available. Please upgrade to UE9 Comm firmware 1.43 or higher.")
  257. rcvString = self.handle.modbus.recv(numBytes)
  258. else:
  259. rcvString = self.handle.data.recv(numBytes)
  260. readBytes = len(rcvString)
  261. packFormat = "B" * readBytes
  262. rcvDataBuff = struct.unpack(packFormat, rcvString)
  263. return list(rcvDataBuff)
  264. def _readFromExodriver(self, numBytes, stream, modbus):
  265. newA = (ctypes.c_byte*numBytes)()
  266. if(stream):
  267. readBytes = staticLib.LJUSB_Stream(self.handle, ctypes.byref(newA), numBytes)
  268. if readBytes == 0:
  269. return ''
  270. # return the byte string in stream mode
  271. return struct.pack('b' * readBytes, *newA)
  272. else:
  273. readBytes = staticLib.LJUSB_Read(self.handle, ctypes.byref(newA), numBytes)
  274. # return a list of integers in command/response mode
  275. return [(newA[i] & 0xff) for i in range(readBytes)]
  276. def _readFromUDDriver(self, numBytes, stream, modbus):
  277. if self.devType == 0x501:
  278. newA = (ctypes.c_byte*numBytes)()
  279. readBytes = skymoteLib.LJUSB_IntRead(self.handle, 0x81, ctypes.byref(newA), numBytes)
  280. return [(newA[i] & 0xff) for i in range(readBytes)]
  281. else:
  282. if modbus is True and self.devType == 9:
  283. tempBuff = [0] * (8 + numBytes + numBytes%2)
  284. eGetBuff = list()
  285. eGetBuff = eGetRaw(self.handle, LJ_ioRAW_IN, 0, len(tempBuff), tempBuff)[1]
  286. #parse the modbus response out (reponse is the Modbus extended low=level function)
  287. retBuff = list()
  288. if len(eGetBuff) >= 9 and eGetBuff[1] == 0xF8 and eGetBuff[3] == 0x07:
  289. #figuring out the length of the modbus response
  290. mbSize = len(eGetBuff) - 8
  291. if len(eGetBuff) >= 14:
  292. mbSize = min(mbSize, eGetBuff[13] + 6)
  293. i = min(mbSize, numBytes)
  294. i = max(i, 0)
  295. retBuff = eGetBuff[8:8+i] #getting the response only
  296. return retBuff
  297. tempBuff = [0] * numBytes
  298. if stream:
  299. return eGetRaw(self.handle, LJ_ioRAW_IN, 1, numBytes, tempBuff)[1]
  300. return eGetRaw(self.handle, LJ_ioRAW_IN, 0, numBytes, tempBuff)[1]
  301. def readRegister(self, addr, numReg = None, format = None, unitId = None):
  302. """ Reads a specific register from the device and returns the value.
  303. Requires Modbus.py
  304. readHoldingRegister(addr, numReg = None, format = None)
  305. addr: The address you would like to read
  306. numReg: Number of consecutive addresses you would like to read
  307. format: the unpack format of the returned value ( '>f' or '>I')
  308. Modbus is supported for UE9s over USB from Comm Firmware 1.50 and above.
  309. """
  310. pkt, numBytes = self._buildReadRegisterPacket(addr, numReg, unitId)
  311. response = self._modbusWriteRead(pkt, numBytes)
  312. return self._parseReadRegisterResponse(response, numBytes, addr, format, numReg)
  313. def _buildReadRegisterPacket(self, addr, numReg, unitId):
  314. """
  315. self._buildReadRegisterPacket(addr, numReg)
  316. Builds a raw modbus "Read Register" packet to be written to a device
  317. returns a tuple:
  318. ( < Packet as a list >, < number of bytes to read > )
  319. """
  320. # Calculates the number of registers for that request, or if numReg is
  321. # specified, checks that it is a valid number.
  322. numReg = Modbus.calcNumberOfRegisters(addr, numReg = numReg)
  323. pkt = Modbus.readHoldingRegistersRequest(addr, numReg = numReg, unitId = unitId)
  324. pkt = [ ord(c) for c in pkt ]
  325. numBytes = 9 + (2 * int(numReg))
  326. return (pkt, numBytes)
  327. def _parseReadRegisterResponse(self, response, numBytes, addr, format, numReg = None):
  328. """
  329. self._parseReadRegisterReponse(reponse, numBytes, addr, format)
  330. Takes a "Read Register" response and converts it to a value
  331. returns the value
  332. """
  333. if len(response) != numBytes:
  334. raise LabJackException(9001, "Got incorrect number of bytes from device. Expected %s bytes, got %s bytes. The packet recieved was: %s" % (numBytes, len(response),response))
  335. if isinstance(response, list):
  336. packFormat = ">" + "B" * numBytes
  337. response = struct.pack(packFormat, *response)
  338. if format == None:
  339. format = Modbus.calcFormat(addr, numReg)
  340. value = Modbus.readHoldingRegistersResponse(response, payloadFormat=format)
  341. return value
  342. def writeRegister(self, addr, value, unitId = None):
  343. """
  344. Writes a value to a register. Returns the value to be written, if successful.
  345. Requires Modbus.py
  346. writeRegister(self, addr, value)
  347. addr: The address you want to write to.
  348. value: The value, or list of values, you want to write.
  349. if you cannot write to that register, a LabJackException is raised.
  350. Modbus is not supported for UE9's over USB. If you try it, a LabJackException is raised.
  351. """
  352. pkt, numBytes = self._buildWriteRegisterPacket(addr, value, unitId)
  353. response = self._modbusWriteRead(pkt, numBytes)
  354. return self._parseWriteRegisterResponse(response, pkt, value)
  355. def _buildWriteRegisterPacket(self, addr, value, unitId):
  356. """
  357. self._buildWriteRegisterPacket(addr, value)
  358. Builds a raw modbus "Write Register" packet to be written to a device
  359. returns a tuple:
  360. ( < Packet as a list >, < number of bytes to read > )
  361. """
  362. if type(value) is list:
  363. return self._buildWriteMultipleRegisters(addr, value, unitId)
  364. fmt = Modbus.calcFormat(addr)
  365. if fmt != '>H':
  366. return self._buildWriteFloatToRegister(addr, value, unitId, fmt)
  367. request = Modbus.writeRegisterRequest(addr, value, unitId)
  368. request = [ ord(c) for c in request ]
  369. numBytes = 12
  370. return request, numBytes
  371. def _buildWriteFloatToRegister(self, addr, value, unitId, fmt = '>f'):
  372. numReg = 2
  373. if not isinstance(value, int) and not isinstance(value, float):
  374. raise TypeError("Value must be a float or int.")
  375. # Function, Address, Num Regs, Byte count, Data
  376. payload = struct.pack('>BHHB', 0x10, addr, 0x02, 0x04) + struct.pack(fmt, value)
  377. request = Modbus._buildHeaderBytes(length = len(payload)+1, unitId = unitId)
  378. request += payload
  379. request = [ ord(c) for c in request ]
  380. numBytes = 12
  381. return (request, numBytes)
  382. def _buildWriteMultipleRegisters(self, startAddr, values, unitId = None):
  383. request = Modbus.writeRegistersRequest(startAddr, values, unitId)
  384. request = [ ord(c) for c in request ]
  385. numBytes = 12
  386. return (request, numBytes)
  387. def _parseWriteRegisterResponse(self, response, request, value):
  388. response = list(response)
  389. if request[2] != 0 and request[3] != 0:
  390. protoID = (request[2] << 8) + request[3]
  391. raise Modbus.ModbusException("Got an unexpected protocol ID: %s (expected 0). Please make sure that you have the latest firmware. UE9s need a Comm Firmware of 1.50 or greater.\n\nThe packet you received: %s" % (protoID, hexWithoutQuotes(response)))
  392. if request[7] != response[7]:
  393. raise LabJackException(9002, "Modbus error number %s raised while writing to register. Make sure you're writing to an address that allows writes.\n\nThe packet you received: %s" % (response[8], hexWithoutQuotes(response)))
  394. return value
  395. def setDIOState(self, IOnum, state):
  396. value = (int(state) & 0x01)
  397. self.writeRegister(6000+IOnum, value)
  398. return True
  399. def _modbusWriteRead(self, request, numBytes):
  400. with self.deviceLock:
  401. self.write(request, modbus = True, checksum = False)
  402. try:
  403. result = self.read(numBytes, modbus = True)
  404. if self.debug: print "Response: ", hexWithoutQuotes(result)
  405. return result
  406. except LabJackException:
  407. self.write(request, modbus = True, checksum = False)
  408. result = self.read(numBytes, modbus = True)
  409. if self.debug: print "Response: ", hexWithoutQuotes(result)
  410. return result
  411. def _checkCommandBytes(self, results, commandBytes):
  412. """
  413. Checks all the stuff from a command
  414. """
  415. size = len(commandBytes)
  416. if len(results) == 0:
  417. raise LabJackException("Got a zero length packet.")
  418. elif results[0] == 0xB8 and results[1] == 0xB8:
  419. raise LabJackException("Device detected a bad checksum.")
  420. elif results[1:(size+1)] != commandBytes:
  421. raise LabJackException("Got incorrect command bytes.\nExpected: %s\nGot: %s\nFull packet: %s" % (hexWithoutQuotes(commandBytes), hexWithoutQuotes(results[1:(size+1)]), hexWithoutQuotes(results)))
  422. elif not verifyChecksum(results):
  423. raise LabJackException("Checksum was incorrect.")
  424. elif results[6] != 0:
  425. raise LowlevelErrorException(results[6], "\nThe %s returned an error:\n %s" % (self.deviceName , lowlevelErrorToString(results[6])) )
  426. def _writeRead(self, command, readLen, commandBytes, checkBytes = True, stream=False, checksum = True):
  427. # Acquire the device lock.
  428. with self.deviceLock:
  429. self.write(command, checksum = checksum)
  430. result = self.read(readLen, stream=False)
  431. if self.debug: print "Response: ", hexWithoutQuotes(result)
  432. if checkBytes:
  433. self._checkCommandBytes(result, commandBytes)
  434. return result
  435. def ping(self):
  436. try:
  437. if self.devType == LJ_dtUE9:
  438. writeBuffer = [0x70, 0x70]
  439. self.write(writeBuffer)
  440. try:
  441. self.read(2)
  442. except LabJackException:
  443. self.write(writeBuffer)
  444. self.read(2)
  445. return True
  446. if self.devType == LJ_dtU3:
  447. writeBuffer = [0, 0xf8, 0x01, 0x2a, 0, 0, 0, 0]
  448. writeBuffer = setChecksum(writeBuffer)
  449. self.write(writeBuffer)
  450. self.read(40)
  451. return True
  452. return False
  453. except Exception, e:
  454. print e
  455. return False
  456. def open(self, devType, Ethernet=False, firstFound = True, serial = None, localId = None, devNumber = None, ipAddress = None, handleOnly = False, LJSocket = None):
  457. """
  458. Device.open(devType, Ethernet=False, firstFound = True, serial = None, localId = None, devNumber = None, ipAddress = None, handleOnly = False, LJSocket = None)
  459. Open a device of type devType.
  460. """
  461. if self.handle is not None:
  462. raise LabJackException(9000,"Open called on a device with a handle. Please close the device, and try again. Your device is probably already open.\nLook for lines of code that look like this:\nd = u3.U3()\nd.open() # Wrong! Device is already open.")
  463. ct = LJ_ctUSB
  464. if Ethernet:
  465. ct = LJ_ctETHERNET
  466. if LJSocket is not None:
  467. ct = LJ_ctLJSOCKET
  468. d = None
  469. if devNumber:
  470. d = openLabJack(devType, ct, firstFound = False, devNumber = devNumber, handleOnly = handleOnly, LJSocket = LJSocket)
  471. elif serial:
  472. d = openLabJack(devType, ct, firstFound = False, pAddress = serial, handleOnly = handleOnly, LJSocket = LJSocket)
  473. elif localId:
  474. d = openLabJack(devType, ct, firstFound = False, pAddress = localId, handleOnly = handleOnly, LJSocket = LJSocket)
  475. elif ipAddress:
  476. d = openLabJack(devType, ct, firstFound = False, pAddress = ipAddress, handleOnly = handleOnly, LJSocket = LJSocket)
  477. elif LJSocket:
  478. d = openLabJack(devType, ct, handleOnly = handleOnly, LJSocket = LJSocket)
  479. elif firstFound:
  480. d = openLabJack(devType, ct, firstFound = True, handleOnly = handleOnly, LJSocket = LJSocket)
  481. else:
  482. raise LabJackException("You must use first found, or give a localId, devNumber, or IP Address")
  483. self.handle = d.handle
  484. if not handleOnly:
  485. self._loadChangedIntoSelf(d)
  486. self._registerAtExitClose()
  487. def _loadChangedIntoSelf(self, d):
  488. for key, value in d.changed.items():
  489. self.__setattr__(key, value)
  490. def _registerAtExitClose(self):
  491. if not self._autoCloseSetup:
  492. # Only need to register auto-close once per device.
  493. atexit.register(self.close)
  494. self._autoCloseSetup = True
  495. def close(self):
  496. """close()
  497. This function is not specifically supported in the LabJackUD driver
  498. for Windows and so simply calls the UD function Close. For Mac and unix
  499. drivers, this function MUST be performed when finished with a device.
  500. The reason for this close is because there can not be more than one program
  501. with a given device open at a time. If a device is not closed before
  502. the program is finished it may still be held open and unable to be used
  503. by other programs until properly closed.
  504. For Windows, Linux, and Mac
  505. """
  506. if isinstance(self.handle, UE9TCPHandle) or isinstance(self.handle, LJSocketHandle):
  507. self.handle.close()
  508. elif os.name == 'posix':
  509. staticLib.LJUSB_CloseDevice(self.handle)
  510. elif self.devType == 0x501:
  511. skymoteLib.LJUSB_CloseDevice(self.handle)
  512. self.handle = None
  513. def reset(self):
  514. """Reset the LabJack device.
  515. For Windows, Linux, and Mac
  516. Sample Usage:
  517. >>> u3 = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
  518. >>> u3.reset()
  519. @type None
  520. @param Function takes no arguments
  521. @rtype: None
  522. @return: Function returns nothing.
  523. @raise LabJackException:
  524. """
  525. if os.name == 'nt':
  526. staticLib = ctypes.windll.LoadLibrary("labjackud")
  527. ec = staticLib.ResetLabJack(self.handle)
  528. if ec != 0: raise LabJackException(ec)
  529. elif os.name == 'posix':
  530. sndDataBuff = [0] * 4
  531. #Make the reset packet
  532. sndDataBuff[0] = 0x9B
  533. sndDataBuff[1] = 0x99
  534. sndDataBuff[2] = 0x02
  535. try:
  536. self.write(sndDataBuff)
  537. rcvDataBuff = self.read(4)
  538. if(len(rcvDataBuff) != 4):
  539. raise LabJackException(0, "Unable to reset labJack 2")
  540. except Exception, e:
  541. raise LabJackException(0, "Unable to reset labjack: %s" % str(e))
  542. def breakupPackets(self, packets, numBytesPerPacket):
  543. """
  544. Name: Device.breakupPackets
  545. Args: packets, a string or list of packets
  546. numBytesPerPacket, how big each packe is
  547. Desc: This function will break up a list into smaller chunks and return
  548. each chunk one at a time.
  549. >>> l = range(15)
  550. >>> for packet in d.breakupPackets(l, 5):
  551. ... print packet
  552. [ 0, 1, 2, 3, 4 ]
  553. [ 5, 6, 7, 8, 9 ]
  554. [ 10, 11, 12, 13, 14]
  555. """
  556. start, end = 0, numBytesPerPacket
  557. while end <= len(packets):
  558. yield packets[start:end]
  559. start, end = end, end + numBytesPerPacket
  560. def samplesFromPacket(self, packet):
  561. """
  562. Name: Device.samplesFromPacket
  563. Args: packet, a packet of stream data
  564. Desc: This function breaks a packet into all the two byte samples it
  565. contains and returns them one at a time.
  566. >>> packet = range(16) # fake packet with 1 sample in it
  567. >>> for sample in d.samplesFromPacket(packet):
  568. ... print sample
  569. [ 12, 13 ]
  570. """
  571. HEADER_SIZE = 12
  572. FOOTER_SIZE = 2
  573. BYTES_PER_PACKET = 2
  574. l = str(packet)
  575. l = l[HEADER_SIZE:]
  576. l = l[:-FOOTER_SIZE]
  577. while len(l) > 0:
  578. yield l[:BYTES_PER_PACKET]
  579. l = l[BYTES_PER_PACKET:]
  580. def streamStart(self):
  581. """
  582. Name: Device.streamStart()
  583. Args: None
  584. Desc: Starts streaming on the device.
  585. Note: You must call streamConfig() before calling this function.
  586. """
  587. if not self.streamConfiged:
  588. raise LabJackException("Stream must be configured before it can be started.")
  589. if self.streamStarted:
  590. raise LabJackException("Stream already started.")
  591. command = [ 0xA8, 0xA8 ]
  592. results = self._writeRead(command, 4, [], False, False, False)
  593. if results[2] != 0:
  594. raise LowlevelErrorException(results[2], "StreamStart returned an error:\n %s" % lowlevelErrorToString(results[2]) )
  595. self.streamStarted = True
  596. def streamData(self, convert=True):
  597. """
  598. Name: Device.streamData()
  599. Args: convert, should the packets be converted as they are read.
  600. set to False to get much faster speeds, but you will
  601. have to process the results later.
  602. Desc: Reads stream data from a LabJack device. See our stream example
  603. to get an idea of how this function should be called. The return
  604. value of streamData is a dictionary with the following keys:
  605. * errors: The number of errors in this block.
  606. * numPackets: The number of USB packets collected to return this
  607. block.
  608. * missed: The number of readings that were missed because of
  609. buffer overflow on the LabJack.
  610. * firstPacket: The PacketCounter value in the first USB packet.
  611. * result: The raw bytes returned from read(). The only way to get
  612. data if called with convert = False.
  613. * AINi, where i is an entry in the passed in PChannels. If called
  614. with convert = True, this is a list of all the readings
  615. in this block.
  616. Note: You must start the stream by calling streamStart() before calling
  617. this function.
  618. """
  619. if not self.streamStarted:
  620. raise LabJackException("Please start streaming before reading.")
  621. numBytes = 14 + (self.streamSamplesPerPacket * 2)
  622. while True:
  623. result = self.read(numBytes * self.packetsPerRequest, stream = True)
  624. if len(result) == 0:
  625. yield None
  626. continue
  627. numPackets = len(result) // numBytes
  628. errors = 0
  629. missed = 0
  630. firstPacket = ord(result[10])
  631. for i in range(numPackets):
  632. e = ord(result[11+(i*numBytes)])
  633. if e != 0:
  634. errors += 1
  635. if self.debug and e != 60 and e != 59: print e
  636. if e == 60:
  637. missed += struct.unpack('<I', result[6+(i*numBytes):10+(i*numBytes)] )[0]
  638. returnDict = dict(numPackets = numPackets, result = result, errors = errors, missed = missed, firstPacket = firstPacket )
  639. if convert:
  640. returnDict.update(self.processStreamData(result, numBytes = numBytes))
  641. yield returnDict
  642. def streamStop(self):
  643. """
  644. Name: Device.streamStop()
  645. Args: None
  646. Desc: Stops streaming on the device.
  647. """
  648. command = [ 0xB0, 0xB0 ]
  649. results = self._writeRead(command, 4, [], False, False, False)
  650. if results[2] != 0:
  651. raise LowlevelErrorException(results[2], "StreamStop returned an error:\n %s" % lowlevelErrorToString(results[2]) )
  652. self.streamStarted = False
  653. def getName(self):
  654. """
  655. Name: Device.getName()
  656. Args: None
  657. Desc: Returns the name of a device.
  658. Always returns a unicode string.
  659. Works as of the following firmware versions:
  660. U6 - 1.00
  661. U3 - 1.22
  662. UE9 - 2.00
  663. >>> d = u3.U3()
  664. >>> d.open()
  665. >>> d.getName()
  666. u'My LabJack U3'
  667. """
  668. name = list(self.readRegister(58000, format='B'*48, numReg = 24))
  669. if name[1] == 3:
  670. # Old style string
  671. name = "My %s" % self.deviceName
  672. if self.debug: print "Old UTF-16 name detected, replacing with %s" % name
  673. self.setName(name)
  674. name = name.decode("UTF-8")
  675. else:
  676. try:
  677. end = name.index(0x00)
  678. name = struct.pack("B"*end, *name[:end]).decode("UTF-8")
  679. except ValueError:
  680. name = "My %s" % self.deviceName
  681. if self.debug: print "Invalid name detected, replacing with %s" % name
  682. self.setName(name)
  683. name = name.decode("UTF-8")
  684. return name
  685. def setName(self, name = "My LabJack U3"):
  686. """
  687. Name: Device.setName(name = ""My LabJack U3")
  688. Args: name, the name you'd like to assign the the U3
  689. Desc: Writes a new name to the device.
  690. Names a limited to 30 characters or less.
  691. Works as of the following firmware versions:
  692. U6 - 1.00
  693. U3 - 1.22
  694. UE9 - 2.00
  695. >>> d = u3.U3()
  696. >>> d.open()
  697. >>> d.getName()
  698. u'My LabJack U3'
  699. >>> d.setName("Johann")
  700. >>> d.getName()
  701. u'Johann'
  702. """
  703. strLen = len(name)
  704. if strLen > 47:
  705. raise LabJackException("The name is too long, must be less than 48 characters.")
  706. newname = name.encode('UTF-8')
  707. bl = list(struct.unpack("B"*strLen, newname)) + [0x00]
  708. strLen += 1
  709. if strLen%2 != 0:
  710. bl = bl + [0x00]
  711. strLen += 1
  712. bl = struct.unpack(">"+"H"*(strLen/2), struct.pack("B" * strLen, *bl))
  713. self.writeRegister(58000, list(bl))
  714. name = property(getName, setName)
  715. def setDefaults(self, SetToFactoryDefaults = False):
  716. """
  717. Name: Device.setDefaults(SetToFactoryDefaults = False)
  718. Args: SetToFactoryDefaults, set to True reset to factory defaults.
  719. Desc: Executing this function causes the current or last used values
  720. (or the factory defaults) to be stored in flash as the power-up
  721. defaults.
  722. >>> myU6 = U6()
  723. >>> myU6.setDefaults()
  724. """
  725. command = [ 0 ] * 8
  726. #command[0] = Checksum8
  727. command[1] = 0xF8
  728. command[2] = 0x01
  729. command[3] = 0x0E
  730. #command[4] = Checksum16 (LSB)
  731. #command[5] = Checksum16 (MSB)
  732. command[6] = 0xBA
  733. command[7] = 0x26
  734. if SetToFactoryDefaults:
  735. command[6] = 0x82
  736. command[7] = 0xC7
  737. self._writeRead(command, 8, [ 0xF8, 0x01, 0x0E ] )
  738. def setToFactoryDefaults(self):
  739. return self.setDefaults(SetToFactoryDefaults = True)
  740. validDefaultBlocks = range(8)
  741. def readDefaults(self, BlockNum, ReadCurrent = False):
  742. """
  743. Name: Device.readDefaults(BlockNum)
  744. Args: BlockNum, which block to read. Must be 0-7.
  745. ReadCurrent, True = read current configuration
  746. Desc: Reads the power-up defaults from flash.
  747. >>> myU6 = U6()
  748. >>> myU6.readDefaults(0)
  749. [ 0, 0, ... , 0]
  750. """
  751. if BlockNum not in self.validDefaultBlocks:
  752. raise LabJackException("Defaults must be in range 0-7")
  753. byte7 = (int(bool(ReadCurrent)) << 7) + BlockNum
  754. command = [ 0, 0xF8, 0x01, 0x0E, 0, 0, 0, byte7 ]
  755. result = self._writeRead(command, 40, [ 0xF8, 0x11, 0x0E ])
  756. return result[8:]
  757. def readCurrent(self, BlockNum):
  758. self.readDefaults(BlockNum, ReadCurrent = True)
  759. def loadGenericDevice(self, device):
  760. """ Take a generic Device object, and loads it into the current object.
  761. The generic Device is consumed in the process.
  762. """
  763. self.handle = device.handle
  764. self._loadChangedIntoSelf(device)
  765. self._registerAtExitClose()
  766. device = None
  767. # --------------------- BEGIN LabJackPython ---------------------------------
  768. def setChecksum(command):
  769. """Returns a command with checksums places in the proper locations
  770. For Windows, Mac, and Linux
  771. Sample Usage:
  772. >>> from LabJackPython import *
  773. >>> command = [0] * 12
  774. >>> command[1] = 0xf8
  775. >>> command[2] = 0x03
  776. >>> command[3] = 0x0b
  777. >>> command = SetChecksum(command)
  778. >>> command
  779. [7, 248, 3, 11, 0, 0, 0, 0, 0, 0, 0, 0]
  780. @type command: List
  781. @param command: The command by which to calculate the checksum
  782. @rtype: List
  783. @return: A command list with checksums in the proper locations.
  784. """
  785. if len(command) < 8:
  786. raise LabJackException("Command does not contain enough bytes.")
  787. try:
  788. a = command[1]
  789. a = (a & 0x78) >> 3
  790. #Check if the command is an extended command
  791. if a == 15:
  792. command = setChecksum16(command)
  793. command = setChecksum8(command, 6)
  794. return command
  795. else:
  796. command = setChecksum8(command, len(command))
  797. return command
  798. except LabJackException, e:
  799. raise e
  800. except Exception, e:
  801. raise LabJackException("SetChecksum Exception:" + str(e))
  802. def verifyChecksum(buffer):
  803. """Verifies the checksum of a given buffer using the traditional U3/UE9 Command Structure.
  804. """
  805. buff0 = buffer[0]
  806. buff4 = buffer[4]
  807. buff5 = buffer[5]
  808. tempBuffer = setChecksum(buffer)
  809. if (buff0 == tempBuffer[0]) and (buff4 == tempBuffer[4]) \
  810. and (buff5 == tempBuffer[5]):
  811. return True
  812. return False
  813. # 1 = LJ_ctUSB
  814. def listAll(deviceType, connectionType = 1):
  815. """listAll(deviceType, connectionType) -> [[local ID, Serial Number, IP Address], ...]
  816. Searches for all devices of a given type over a given connection type and returns a list
  817. of all devices found.
  818. WORKS on WINDOWS, MAC, UNIX
  819. """
  820. if connectionType == LJ_ctLJSOCKET:
  821. ipAddress, port = deviceType.split(":")
  822. port = int(port)
  823. serverSocket = socket.socket()
  824. serverSocket.connect((ipAddress, port))
  825. serverSocket.settimeout(10)
  826. f = serverSocket.makefile(bufsize = 0)
  827. f.write("scan\r\n")
  828. l = f.readline().strip()
  829. try:
  830. status, numLines = l.split(' ')
  831. except ValueError:
  832. raise Exception("Got invalid line from server: %s" % l)
  833. if status.lower().startswith('ok'):
  834. lines = []
  835. marked = None
  836. for i in range(int(numLines)):
  837. l = f.readline().strip()
  838. dev = parseline(l)
  839. lines.append(dev)
  840. f.close()
  841. serverSocket.close()
  842. #print "Result of scan:"
  843. #print lines
  844. return lines
  845. if deviceType == 12:
  846. if U12DriverPresent():
  847. u12Driver = ctypes.windll.LoadLibrary("ljackuw")
  848. # Setup all the ctype arrays
  849. pSerialNumbers = (ctypes.c_long * 127)(0)
  850. pIDs = (ctypes.c_long * 127)(0)
  851. pProdID = (ctypes.c_long * 127)(0)
  852. pPowerList = (ctypes.c_long * 127)(0)
  853. pCalMatrix = (ctypes.c_long * 2540)(0)
  854. pNumFound = ctypes.c_long()
  855. pFcdd = ctypes.c_long(0)
  856. pHvc = ctypes.c_long(0)
  857. #Output dictionary
  858. deviceList = {}
  859. ec = u12Driver.ListAll(ctypes.cast(pProdID, ctypes.POINTER(ctypes.c_long)),
  860. ctypes.cast(pSerialNumbers, ctypes.POINTER(ctypes.c_long)),
  861. ctypes.cast(pIDs, ctypes.POINTER(ctypes.c_long)),
  862. ctypes.cast(pPowerList, ctypes.POINTER(ctypes.c_long)),
  863. ctypes.cast(pCalMatrix, ctypes.POINTER(ctypes.c_long)),
  864. ctypes.byref(pNumFound),
  865. ctypes.byref(pFcdd),
  866. ctypes.byref(pHvc))
  867. if ec != 0: raise LabJackException(ec)
  868. for i in range(pNumFound.value):
  869. deviceList[pSerialNumbers[i]] = { 'SerialNumber' : pSerialNumbers[i], 'Id' : pIDs[i], 'ProdId' : pProdID[i], 'powerList' : pPowerList[i] }
  870. return deviceList
  871. else:
  872. return {}
  873. if(os.name == 'nt'):
  874. if deviceType == 0x501:
  875. if skymoteLib is None:
  876. raise ImportError("Couldn't load liblabjackusb.dll. Please install, and try again.")
  877. num = skymoteLib.LJUSB_GetDevCount(0x501)
  878. deviceList = dict()
  879. for i in range(num):
  880. try:
  881. device = openLabJack(0x501, 1, firstFound = False, pAddress = None, devNumber = i+1)
  882. device.close()
  883. deviceList[str(device.serialNumber)] = device.__dict__
  884. except LabJackException:
  885. pass
  886. return deviceList
  887. pNumFound = ctypes.c_long()
  888. pSerialNumbers = (ctypes.c_long * 128)()
  889. pIDs = (ctypes.c_long * 128)()
  890. pAddresses = (ctypes.c_double * 128)()
  891. #The actual return variables so the user does not have to use ctypes
  892. serialNumbers = []
  893. ids = []
  894. addresses = []
  895. ec = staticLib.ListAll(deviceType, connectionType,
  896. ctypes.byref(pNumFound),
  897. ctypes.cast(pSerialNumbers, ctypes.POINTER(ctypes.c_long)),
  898. ctypes.cast(pIDs, ctypes.POINTER(ctypes.c_long)),
  899. ctypes.cast(pAddresses, ctypes.POINTER(ctypes.c_long)))
  900. if ec != 0 and ec != 1010: raise LabJackException(ec)
  901. deviceList = dict()
  902. for i in xrange(pNumFound.value):
  903. if pSerialNumbers[i] != 1010:
  904. deviceValue = dict(localId = pIDs[i], serialNumber = pSerialNumbers[i], ipAddress = DoubleToStringAddress(pAddresses[i]), devType = deviceType)
  905. deviceList[pSerialNumbers[i]] = deviceValue
  906. return deviceList
  907. if(os.name == 'posix'):
  908. if deviceType == LJ_dtUE9:
  909. return __listAllUE9Unix(connectionType)
  910. if deviceType == LJ_dtU3:
  911. return __listAllU3Unix()
  912. if deviceType == 6:
  913. return __listAllU6Unix()
  914. if deviceType == 0x501:
  915. return __listAllBridgesUnix()
  916. def isHandleValid(handle):
  917. if(os.name == 'nt'):
  918. return True
  919. else:
  920. return staticLib.LJUSB_IsHandleValid(handle)
  921. def deviceCount(devType = None):
  922. """Returns the number of devices connected. """
  923. if(os.name == 'nt'):
  924. if devType is None:
  925. numdev = len(listAll(3))
  926. numdev += len(listAll(9))
  927. numdev += len(listAll(6))
  928. if skymoteLib is not None:
  929. numdev += len(listAll(0x501))
  930. return numdev
  931. else:
  932. return len(listAll(devType))
  933. else:
  934. if devType == None:
  935. numdev = staticLib.LJUSB_GetDevCount(3)
  936. numdev += staticLib.LJUSB_GetDevCount(9)
  937. numdev += staticLib.LJUSB_GetDevCount(6)
  938. numdev += staticLib.LJUSB_GetDevCount(0x501)
  939. return numdev
  940. else:
  941. return staticLib.LJUSB_GetDevCount(devType)
  942. def getDevCounts():
  943. if os.name == "nt":
  944. # Right now there is no good way to count all the U12s on a Windows box
  945. return { 3 : len(listAll(3)), 6 : len(listAll(6)), 9 : len(listAll(9)), 1 : 0, 0x501 : len(listAll(0x501))}
  946. else:
  947. devCounts = (ctypes.c_uint*NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS)()
  948. devIds = (ctypes.c_uint*NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS)()
  949. n = ctypes.c_uint(NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS)
  950. r = staticLib.LJUSB_GetDevCounts(ctypes.byref(devCounts), ctypes.byref(devIds), n)
  951. returnDict = dict()
  952. for i in range(NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS):
  953. returnDict[int(devIds[i])] = int(devCounts[i])
  954. return returnDict
  955. def openAllLabJacks():
  956. if os.name == "nt":
  957. # Windows doesn't provide a nice way to open all the devices.
  958. devs = dict()
  959. devs[3] = listAll(3)
  960. devs[6] = listAll(6)
  961. devs[9] = listAll(9)
  962. devs[0x501] = listAll(0x501)
  963. devices = list()
  964. for prodId, numConnected in devs.items():
  965. for i, serial in enumerate(numConnected.keys()):
  966. d = Device(None, devType = prodId)
  967. if prodId == 0x501:
  968. d.open(prodId, devNumber = i)
  969. d = _makeDeviceFromHandle(d.handle, prodId)
  970. else:
  971. d.open(prodId, serial = serial)
  972. d = _makeDeviceFromHandle(d.handle, prodId)
  973. devices.append(d)
  974. else:
  975. maxHandles = 10
  976. devHandles = (ctypes.c_void_p*maxHandles)()
  977. devIds = (ctypes.c_uint*maxHandles)()
  978. n = ctypes.c_uint(maxHandles)
  979. numOpened = staticLib.LJUSB_OpenAllDevices(ctypes.byref(devHandles), ctypes.byref(devIds), n)
  980. devices = list()
  981. for i in range(numOpened):
  982. devices.append(_makeDeviceFromHandle(devHandles[i], int(devIds[i])))
  983. return devices
  984. def _openLabJackUsingLJSocket(deviceType, firstFound, pAddress, LJSocket, handleOnly ):
  985. if LJSocket is not '':
  986. ip, port = LJSocket.split(":")
  987. port = int(port)
  988. handle = LJSocketHandle(ip, port, deviceType, firstFound, pAddress)
  989. else:
  990. handle = LJSocketHandle('localhost', 6000, deviceType, firstFound, pAddress)
  991. return handle
  992. def _openLabJackUsingUDDriver(deviceType, connectionType, firstFound, pAddress, devNumber ):
  993. if devNumber is not None:
  994. devs = listAll(deviceType)
  995. pAddress = devs.keys()[(devNumber-1)]
  996. handle = ctypes.c_long()
  997. pAddress = str(pAddress)
  998. ec = staticLib.OpenLabJack(deviceType, connectionType,
  999. pAddress, firstFound, ctypes.byref(handle))
  1000. if ec != 0: raise LabJackException(ec)
  1001. devHandle = handle.value
  1002. return devHandle
  1003. def _openLabJackUsingExodriver(deviceType, firstFound, pAddress, devNumber):
  1004. devType = ctypes.c_ulong(deviceType)
  1005. openDev = staticLib.LJUSB_OpenDevice
  1006. openDev.restype = ctypes.c_void_p
  1007. if(devNumber != None):
  1008. handle = openDev(devNumber, 0, devType)
  1009. if handle <= 0:
  1010. raise NullHandleException()
  1011. return handle
  1012. elif(firstFound):
  1013. handle = openDev(1, 0, devType)
  1014. if handle <= 0:
  1015. print "handle: %s" % handle
  1016. raise NullHandleException()
  1017. return handle
  1018. else:
  1019. numDevices = staticLib.LJUSB_GetDevCount(deviceType)
  1020. for i in range(numDevices):
  1021. handle = openDev(i + 1, 0, devType)
  1022. try:
  1023. if handle <= 0:
  1024. raise NullHandleException()
  1025. device = _makeDeviceFromHandle(handle, deviceType)
  1026. except:
  1027. continue
  1028. if device.localId == pAddress or device.serialNumber == pAddress or device.ipAddress == pAddress:
  1029. return device
  1030. else:
  1031. device.close()
  1032. raise LabJackException(LJE_LABJACK_NOT_FOUND)
  1033. def _openUE9OverEthernet(firstFound, pAddress, devNumber):
  1034. if firstFound is not True and pAddress is not None:
  1035. #Check if valid IP address and attempt to get TCP handle
  1036. try:
  1037. socket.inet_aton(pAddress)
  1038. return UE9TCPHandle(pAddress)
  1039. except:
  1040. pass
  1041. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  1042. s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  1043. s.settimeout(BROADCAST_SOCKET_TIMEOUT)
  1044. sndDataBuff = [0] * 6
  1045. sndDataBuff[0] = 0x22
  1046. sndDataBuff[1] = 0x78
  1047. sndDataBuff[3] = 0xa9
  1048. outBuff = ""
  1049. for item in sndDataBuff:
  1050. outBuff += chr(item)
  1051. s.sendto(outBuff, ("255.255.255.255", 52362))
  1052. try:
  1053. count = 1
  1054. while True:
  1055. rcvDataBuff = s.recv(128)
  1056. rcvDataBuff = [ord(val) for val in rcvDataBuff]
  1057. if verifyChecksum(rcvDataBuff):
  1058. #Parse the packet
  1059. macAddress = rcvDataBuff[28:34]
  1060. macAddress.reverse()
  1061. # The serial number is four bytes:
  1062. # 0x10 and the last three bytes of the MAC address
  1063. serialBytes = chr(0x10)
  1064. for j in macAddress[3:]:
  1065. serialBytes += chr(j)
  1066. serialNumber = struct.unpack(">I", serialBytes)[0]
  1067. #Parse out the IP address
  1068. ipAddress = ""
  1069. for j in range(13, 9, -1):
  1070. ipAddress += str(int(rcvDataBuff[j]))
  1071. ipAddress += "."
  1072. ipAddress = ipAddress[0:-1]
  1073. #Local ID
  1074. localId = rcvDataBuff[8] & 0xff
  1075. # Check if we have found the device we are looking for.
  1076. # pAddress represents either Local ID, Serial Number, or the
  1077. # IP Address. This is so there are no conflicting identifiers.
  1078. if firstFound \
  1079. or devNumber == count \
  1080. or pAddress in [localId, serialNumber, ipAddress]:
  1081. handle = UE9TCPHandle(ipAddress)
  1082. return handle
  1083. count += 1
  1084. else:
  1085. # Got a bad checksum.
  1086. pass
  1087. except LabJackException, e:
  1088. raise LabJackException(LJE_LABJACK_NOT_FOUND, "%s" % e)
  1089. except:
  1090. raise LabJackException("LJE_LABJACK_NOT_FOUND: Couldn't find the specified LabJack.")
  1091. def _openWirelessBridgeOnWindows(firstFound, pAddress, devNumber):
  1092. if skymoteLib is None:
  1093. raise ImportError("Couldn't load liblabjackusb.dll. Please install, and try again.")
  1094. devType = ctypes.c_ulong(0x501)
  1095. openDev = skymoteLib.LJUSB_OpenDevice
  1096. openDev.restype = ctypes.c_void_p
  1097. if(devNumber != None):
  1098. handle = openDev(devNumber, 0, devType)
  1099. if handle <= 0:
  1100. raise NullHandleException()
  1101. return handle
  1102. elif(firstFound):
  1103. handle = openDev(1, 0, devType)
  1104. if handle <= 0:
  1105. raise NullHandleException()
  1106. return handle
  1107. else:
  1108. raise LabjackException("Bridges don't have identifiers yet.")
  1109. if handleOnly:
  1110. raise LabjackException("Can't use handleOnly with an id.")
  1111. numDevices = skymoteLib.LJUSB_GetDevCount(deviceType)
  1112. for i in range(numDevices):
  1113. handle = openDev(i + 1, 0, devType)
  1114. try:
  1115. if handle <= 0:
  1116. raise NullHandleException()
  1117. device = _makeDeviceFromHandle(handle, deviceType)
  1118. except:
  1119. continue
  1120. if device.localId == pAddress or device.serialNumber == pAddress or device.ipAddress == pAddress:
  1121. return device
  1122. else:
  1123. device.close()
  1124. raise LabJackException(LJE_LABJACK_NOT_FOUND)
  1125. #Windows, Linux, and Mac
  1126. def openLabJack(deviceType, connectionType, firstFound = True, pAddress = None, devNumber = None, handleOnly = False, LJSocket = None):
  1127. """openLabJack(deviceType, connectionType, firstFound = True, pAddress = 1, LJSocket = None)
  1128. Note: On Windows, Ue9 over Ethernet, pAddress MUST be the IP address.
  1129. """
  1130. rcvDataBuff = []
  1131. handle = None
  1132. if connectionType == LJ_ctLJSOCKET:
  1133. # LJSocket handles work indepenent of OS
  1134. handle = _openLabJackUsingLJSocket(deviceType, firstFound, pAddress, LJSocket, handleOnly )
  1135. elif os.name == 'posix' and connectionType == LJ_ctUSB:
  1136. # Linux/Mac need to work in the low level driver.
  1137. handle = _openLabJackUsingExodriver(deviceType, firstFound, pAddress, devNumber)
  1138. if isinstance( handle, Device ):
  1139. return handle
  1140. elif os.name == 'nt':
  1141. #If windows operating system then use the UD Driver
  1142. if deviceType == 0x501:
  1143. handle = _openWirelessBridgeOnWindows(firstFound, pAddress, devNumber)
  1144. handle = ctypes.c_void_p(handle)
  1145. elif staticLib is not None:
  1146. handle = _openLabJackUsingUDDriver(deviceType, connectionType, firstFound, pAddress, devNumber )
  1147. elif connectionType == LJ_ctETHERNET and deviceType == LJ_dtUE9 :
  1148. handle = _openUE9OverEthernet(firstFound, pAddress, devNumber)
  1149. if not handleOnly:
  1150. return _makeDeviceFromHandle(handle, deviceType)
  1151. else:
  1152. return Device(handle, devType = deviceType)
  1153. def _makeDeviceFromHandle(handle, deviceType):
  1154. """ A helper function to get set all the info about a device from a handle"""
  1155. device = Device(handle, devType = deviceType)
  1156. device.changed = dict()
  1157. if(deviceType == LJ_dtUE9):
  1158. sndDataBuff = [0] * 38
  1159. sndDataBuff[0] = 0x89
  1160. sndDataBuff[1] = 0x78
  1161. sndDataBuff[2] = 0x10
  1162. sndDataBuff[3] = 0x01
  1163. try:
  1164. device.write(sndDataBuff, checksum = False)
  1165. rcvDataBuff = device.read(38)
  1166. # Local ID
  1167. device.localId = rcvDataBuff[8] & 0xff
  1168. # MAC Address
  1169. device.macAddress = "%02X:%02X:%02X:%02X:%02X:%02X" % (rcvDataBuff[33], rcvDataBuff[32], rcvDataBuff[31], rcvDataBuff[30], rcvDataBuff[29], rcvDataBuff[28])
  1170. # Parse out serial number
  1171. device.serialNumber = struct.unpack("<I", struct.pack("BBBB", rcvDataBuff[28], rcvDataBuff[29], rcvDataBuff[30], 0x10))[0]
  1172. #Parse out the IP address
  1173. device.ipAddress = "%s.%s.%s.%s" % (rcvDataBuff[13], rcvDataBuff[12], rcvDataBuff[11], rcvDataBuff[10] )
  1174. # Comm FW Version
  1175. device.commFWVersion = "%s.%02d" % (rcvDataBuff[37], rcvDataBuff[36])
  1176. device.changed['localId'] = device.localId
  1177. device.changed['macAddress'] = device.macAddress
  1178. device.changed['serialNumber'] = device.serialNumber
  1179. device.changed['ipAddress'] = device.ipAddress
  1180. device.changed['commFWVersion'] = device.commFWVersion
  1181. except Exception, e:
  1182. device.close()
  1183. raise e
  1184. elif deviceType == LJ_dtU3:
  1185. sndDataBuff = [0] * 26
  1186. sndDataBuff[0] = 0x0b
  1187. sndDataBuff[1] = 0xf8
  1188. sndDataBuff[2] = 0x0a
  1189. sndDataBuff[3] = 0x08
  1190. try:
  1191. device.write(sndDataBuff, checksum = False)
  1192. rcvDataBuff = device.read(38)
  1193. except LabJackException, e:
  1194. device.close()
  1195. raise e
  1196. device.localId = rcvDataBuff[21] & 0xff
  1197. serialNumber = struct.pack("<BBBB", *rcvDataBuff[15:19])
  1198. device.serialNumber = struct.unpack('<I', serialNumber)[0]
  1199. device.ipAddress = ""
  1200. device.firmwareVersion = "%d.%02d" % (rcvDataBuff[10], rcvDataBuff[9])
  1201. device.hardwareVersion = "%d.%02d" % (rcvDataBuff[14], rcvDataBuff[13])
  1202. device.versionInfo = rcvDataBuff[37]
  1203. device.deviceName = 'U3'
  1204. if device.versionInfo == 1:
  1205. device.deviceName += 'B'
  1206. elif device.versionInfo == 2:
  1207. device.deviceName += '-LV'
  1208. elif device.versionInfo == 18:
  1209. device.deviceName += '-HV'
  1210. device.changed['localId'] = device.localId
  1211. device.changed['serialNumber'] = device.serialNumber
  1212. device.changed['ipAddress'] = device.ipAddress
  1213. device.changed['firmwareVersion'] = device.firmwareVersion
  1214. device.changed['versionInfo'] = device.versionInfo
  1215. device.changed['deviceName'] = device.deviceName
  1216. device.changed['hardwareVersion'] = device.hardwareVersion
  1217. elif deviceType == 6:
  1218. command = [ 0 ] * 26
  1219. command[1] = 0xF8
  1220. command[2] = 0x0A
  1221. command[3] = 0x08
  1222. try:
  1223. device.write(command)
  1224. rcvDataBuff = device.read(38)
  1225. except LabJackException, e:
  1226. device.close()
  1227. raise e
  1228. device.localId = rcvDataBuff[21] & 0xff
  1229. serialNumber = struct.pack("<BBBB", *rcvDataBuff[15:19])
  1230. device.serialNumber = struct.unpack('<I', serialNumber)[0]
  1231. device.ipAddress = ""
  1232. device.firmwareVersion = "%s.%02d" % (rcvDataBuff[10], rcvDataBuff[9])
  1233. device.bootloaderVersion = "%s.%02d" % (rcvDataBuff[12], rcvDataBuff[11])
  1234. device.hardwareVersion = "%s.%02d" % (rcvDataBuff[14], rcvDataBuff[13])
  1235. device.versionInfo = rcvDataBuff[37]
  1236. device.deviceName = 'U6'
  1237. if device.versionInfo == 12:
  1238. device.deviceName = 'U6-Pro'
  1239. device.changed['localId'] = device.localId
  1240. device.changed['serialNumber'] = device.serialNumber
  1241. device.changed['ipAddress'] = device.ipAddress
  1242. device.changed['firmwareVersion'] = device.firmwareVersion
  1243. device.changed['versionInfo'] = device.versionInfo
  1244. device.changed['deviceName'] = device.deviceName
  1245. device.changed['hardwareVersion'] = device.hardwareVersion
  1246. device.changed['bootloaderVersion'] = device.bootloaderVersion
  1247. elif deviceType == 0x501:
  1248. pkt, readlen = device._buildReadRegisterPacket(65104, 4, 0)
  1249. device.modbusPrependZeros = False
  1250. device.write(pkt, modbus = True, checksum = False)
  1251. for i in range(5):
  1252. try:
  1253. serial = None
  1254. response = device.read(64, False, True)
  1255. serial = device._parseReadRegisterResponse(response[:readlen], readlen, 65104, '>Q', numReg = 4)
  1256. break
  1257. except Modbus.ModbusException:
  1258. pass
  1259. if serial is None:
  1260. raise LabJackException("Error reading serial number.")
  1261. device.serialNumber = serial
  1262. device.localId = 0
  1263. device.deviceName = "SkyMote Bridge"
  1264. device.changed['localId'] = device.localId
  1265. device.changed['deviceName'] = device.deviceName
  1266. device.changed['serialNumber'] = device.serialNumber
  1267. return device
  1268. def AddRequest(Handle, IOType, Channel, Value, x1, UserData):
  1269. """AddRequest(handle, ioType, channel, value, x1, userData)
  1270. Windows Only
  1271. """
  1272. if os.name == 'nt':
  1273. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1274. v = ctypes.c_double(Value)
  1275. ud = ctypes.c_double(UserData)
  1276. ec = staticLib.AddRequest(Handle, IOType, Channel, v, x1, ud)
  1277. if ec != 0: raise LabJackException(ec)
  1278. else:
  1279. raise LabJackException(0, "Function only supported for Windows")
  1280. #Windows
  1281. def AddRequestS(Handle, pIOType, Channel, Value, x1, UserData):
  1282. """Add a request to the LabJackUD request stack
  1283. For Windows
  1284. Sample Usage to get the AIN value from channel 0:
  1285. >>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
  1286. >>> AddRequestS(u3Handle,"LJ_ioGET_AIN", 0, 0.0, 0, 0.0)
  1287. >>> Go()
  1288. >>> value = GetResult(u3Handle, LJ_ioGET_AIN, 0)
  1289. >>> print "Value:" + str(value)
  1290. Value:0.366420765873
  1291. @type Handle: number
  1292. @param Handle: Handle to the LabJack device.
  1293. @type IOType: String
  1294. @param IOType: IO Request to the LabJack.
  1295. @type Channel: number
  1296. @param Channel: Channel for the IO request.
  1297. @type Value: number
  1298. @param Value: Used for some requests
  1299. @type x1: number
  1300. @param x1: Used for some requests
  1301. @type UserData: number
  1302. @param UserData: Used for some requests
  1303. @rtype: None
  1304. @return: Function returns nothing.
  1305. @raise LabJackException:
  1306. """
  1307. if os.name == 'nt':
  1308. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1309. v = ctypes.c_double(Value)
  1310. ud = ctypes.c_double(UserData)
  1311. ec = staticLib.AddRequestS(Handle, pIOType, Channel,
  1312. v, x1, ud)
  1313. if ec != 0: raise LabJackException(ec)
  1314. else:
  1315. raise LabJackException(0, "Function only supported for Windows")
  1316. #Windows
  1317. def AddRequestSS(Handle, pIOType, pChannel, Value, x1, UserData):
  1318. """Add a request to the LabJackUD request stack
  1319. For Windows
  1320. Sample Usage to get the AIN value from channel 0:
  1321. >>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
  1322. >>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
  1323. >>> Go()
  1324. >>> value = GetResultS(u3Handle, "LJ_ioGET_CONFIG", LJ_chFIRMWARE_VERSION)
  1325. >>> print "Value:" + str(value)
  1326. Value:1.27
  1327. @type Handle: number
  1328. @param Handle: Handle to the LabJack device.
  1329. @type IOType: String
  1330. @param IOType: IO Request to the LabJack.
  1331. @type Channel: String
  1332. @param Channel: Channel for the IO request.
  1333. @type Value: number
  1334. @param Value: Used for some requests
  1335. @type x1: number
  1336. @param x1: Used for some requests
  1337. @type UserData: number
  1338. @param UserData: Used for some requests
  1339. @rtype: None
  1340. @return: Function returns nothing.
  1341. @raise LabJackException:
  1342. """
  1343. if os.name == 'nt':
  1344. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1345. v = ctypes.c_double(Value)
  1346. ud = ctypes.c_double(UserData)
  1347. ec = staticLib.AddRequestSS(Handle, pIOType, pChannel,
  1348. v, x1, ud)
  1349. if ec != 0: raise LabJackException(ec)
  1350. else:
  1351. raise LabJackException(0, "Function only supported for Windows")
  1352. #Windows
  1353. def Go():
  1354. """Complete all requests currently on the LabJackUD request stack
  1355. For Windows Only
  1356. Sample Usage:
  1357. >>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
  1358. >>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
  1359. >>> Go()
  1360. >>> value = GetResultS(u3Handle, "LJ_ioGET_CONFIG", LJ_chFIRMWARE_VERSION)
  1361. >>> print "Value:" + str(value)
  1362. Value:1.27
  1363. @rtype: None
  1364. @return: Function returns nothing.
  1365. @raise LabJackException:
  1366. """
  1367. if os.name == 'nt':
  1368. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1369. ec = staticLib.Go()
  1370. if ec != 0: raise LabJackException(ec)
  1371. else:
  1372. raise LabJackException("Function only supported for Windows")
  1373. #Windows
  1374. def GoOne(Handle):
  1375. """Performs the next request on the LabJackUD request stack
  1376. For Windows Only
  1377. Sample Usage:
  1378. >>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
  1379. >>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
  1380. >>> GoOne(u3Handle)
  1381. >>> value = GetResultS(u3Handle, "LJ_ioGET_CONFIG", LJ_chFIRMWARE_VERSION)
  1382. >>> print "Value:" + str(value)
  1383. Value:1.27
  1384. @type Handle: number
  1385. @param Handle: Handle to the LabJack device.
  1386. @rtype: None
  1387. @return: Function returns nothing.
  1388. @raise LabJackException:
  1389. """
  1390. if os.name == 'nt':
  1391. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1392. ec = staticLib.GoOne(Handle)
  1393. if ec != 0: raise LabJackException(ec)
  1394. else:
  1395. raise LabJackException(0, "Function only supported for Windows")
  1396. #Windows
  1397. def eGet(Handle, IOType, Channel, pValue, x1):
  1398. """Perform one call to the LabJack Device
  1399. eGet is equivilent to an AddRequest followed by a GoOne.
  1400. For Windows Only
  1401. Sample Usage:
  1402. >>> eGet(u3Handle, LJ_ioGET_AIN, 0, 0, 0)
  1403. 0.39392614550888538
  1404. @type Handle: number
  1405. @param Handle: Handle to the LabJack device.
  1406. @type IOType: number
  1407. @param IOType: IO Request to the LabJack.
  1408. @type Channel: number
  1409. @param Channel: Channel for the IO request.
  1410. @type Value: number
  1411. @param Value: Used for some requests
  1412. @type x1: number
  1413. @param x1: Used for some requests
  1414. @rtype: number
  1415. @return: Returns the value requested.
  1416. - value
  1417. @raise LabJackException:
  1418. """
  1419. if os.name == 'nt':
  1420. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1421. pv = ctypes.c_double(pValue)
  1422. #ppv = ctypes.pointer(pv)
  1423. ec = staticLib.eGet(Handle, IOType, Channel, ctypes.byref(pv), x1)
  1424. #staticLib.eGet.argtypes = [ctypes.c_long, ctypes.c_long, ctypes.c_long, ctypes.c_double, ctypes.c_long]
  1425. #ec = staticLib.eGet(Handle, IOType, Channel, pValue, x1)
  1426. if ec != 0: raise LabJackException(ec)
  1427. #print "EGet:" + str(ppv)
  1428. #print "Other:" + str(ppv.contents)
  1429. return pv.value
  1430. else:
  1431. raise LabJackException(0, "Function only supported for Windows")
  1432. #Windows
  1433. #Raw method -- Used because x1 is an output
  1434. def eGetRaw(Handle, IOType, Channel, pValue, x1):
  1435. """Perform one call to the LabJack Device as a raw command
  1436. eGetRaw is equivilent to an AddRequest followed by a GoOne.
  1437. For Windows Only
  1438. Sample Usage (Calling a echo command):
  1439. >>> sendBuff = [0] * 2
  1440. >>> sendBuff[0] = 0x70
  1441. >>> sendBuff[1] = 0x70
  1442. >>> eGetRaw(ue9Handle, LJ_ioRAW_OUT, 0, len(sendBuff), sendBuff)
  1443. (2.0, [112, 112])
  1444. @type Handle: number
  1445. @param Handle: Handle to the LabJack device.
  1446. @type IOType: number
  1447. @param IOType: IO Request to the LabJack.
  1448. @type Channel: number
  1449. @param Channel: Channel for the IO request.
  1450. @type pValue: number
  1451. @param Value: Length of the buffer.
  1452. @type x1: number
  1453. @param x1: Buffer to send.
  1454. @rtype: Tuple
  1455. @return: The tuple (numBytes, returnBuffer)
  1456. - numBytes (number)
  1457. - returnBuffer (List)
  1458. @raise LabJackException:
  1459. """
  1460. ec = 0
  1461. x1Type = "int"
  1462. if os.name == 'nt':
  1463. digitalConst = [35, 36, 37, 45]
  1464. pv = ctypes.c_double(pValue)
  1465. #If IOType is digital then call eget with x1 as a long
  1466. if IOType in digitalConst:
  1467. ec = staticLib.eGet(Handle, IOType, Channel, ctypes.byref(pv), x1)
  1468. else: #Otherwise as an array
  1469. try:
  1470. #Verify x1 is an array
  1471. if len(x1) < 1:
  1472. raise LabJackException(0, "x1 is not a valid variable for the given IOType")
  1473. except Exception:
  1474. raise LabJackException(0, "x1 is not a valid variable for the given IOType")
  1475. #Initialize newA
  1476. newA = None
  1477. if type(x1[0]) == int:
  1478. newA = (ctypes.c_byte*len(x1))()
  1479. for i in range(0, len(x1), 1):
  1480. newA[i] = ctypes.c_byte(x1[i])
  1481. else:
  1482. x1Type = "float"
  1483. newA = (ctypes.c_double*len(x1))()
  1484. for i in range(0, len(x1), 1):
  1485. newA[i] = ctypes.c_double(x1[i])
  1486. ec = staticLib.eGet(Handle, IOType, Channel, ctypes.byref(pv), ctypes.byref(newA))
  1487. if IOType == LJ_ioRAW_IN and Channel == 1:
  1488. # We return the raw byte string if we are streaming
  1489. x1 = struct.pack('b' * len(x1), *newA)
  1490. elif IOType == LJ_ioRAW_IN and Channel == 0:
  1491. x1 = [0] * int(pv.value)
  1492. for i in range(len(x1)):
  1493. x1[i] = newA[i] & 0xff
  1494. else:
  1495. x1 = [0] * len(x1)
  1496. for i in range(len(x1)):
  1497. x1[i] = newA[i]
  1498. if(x1Type == "int"):
  1499. x1[i] = x1[i] & 0xff
  1500. if ec != 0: raise LabJackException(ec)
  1501. return pv.value, x1
  1502. else:
  1503. raise LabJackException(0, "Function only supported for Windows")
  1504. #Windows
  1505. def eGetS(Handle, pIOType, Channel, pValue, x1):
  1506. """Perform one call to the LabJack Device
  1507. eGet is equivilent to an AddRequest followed by a GoOne.
  1508. For Windows Only
  1509. Sample Usage:
  1510. >>> eGet(u3Handle, "LJ_ioGET_AIN", 0, 0, 0)
  1511. 0.39392614550888538
  1512. @type Handle: number
  1513. @param Handle: Handle to the LabJack device.
  1514. @type pIOType: String
  1515. @param pIOType: IO Request to the LabJack.
  1516. @type Channel: number
  1517. @param Channel: Channel for the IO request.
  1518. @type Value: number
  1519. @param Value: Used for some requests
  1520. @type x1: number
  1521. @param x1: Used for some requests
  1522. @rtype: number
  1523. @return: Returns the value requested.
  1524. - value
  1525. @raise LabJackException:
  1526. """
  1527. if os.name == 'nt':
  1528. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1529. pv = ctypes.c_double(pValue)
  1530. ec = staticLib.eGetS(Handle, pIOType, Channel, ctypes.byref(pv), x1)
  1531. if ec != 0: raise LabJackException(ec)
  1532. return pv.value
  1533. else:
  1534. raise LabJackException(0, "Function only supported for Windows")
  1535. #Windows
  1536. def eGetSS(Handle, pIOType, pChannel, pValue, x1):
  1537. """Perform one call to the LabJack Device
  1538. eGet is equivilent to an AddRequest followed by a GoOne.
  1539. For Windows Only
  1540. Sample Usage:
  1541. >>> eGetSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0, 0)
  1542. 1.27
  1543. @type Handle: number
  1544. @param Handle: Handle to the LabJack device.
  1545. @type pIOType: String
  1546. @param pIOType: IO Request to the LabJack.
  1547. @type Channel: String
  1548. @param Channel: Channel for the IO request.
  1549. @type Value: number
  1550. @param Value: Used for some requests
  1551. @type x1: number
  1552. @param x1: Used for some requests
  1553. @rtype: number
  1554. @return: Returns the value requested.
  1555. - value
  1556. @raise LabJackException:
  1557. """
  1558. if os.name == 'nt':
  1559. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1560. pv = ctypes.c_double(pValue)
  1561. ec = staticLib.eGetSS(Handle, pIOType, pChannel, ctypes.byref(pv), x1)
  1562. if ec != 0: raise LabJackException(ec)
  1563. return pv.value
  1564. else:
  1565. raise LabJackException(0, "Function only supported for Windows")
  1566. #Windows
  1567. #Not currently implemented
  1568. def eGetRawS(Handle, pIOType, Channel, pValue, x1):
  1569. """Function not yet implemented.
  1570. For Windows only.
  1571. """
  1572. pass
  1573. #Windows
  1574. def ePut(Handle, IOType, Channel, Value, x1):
  1575. """Put one value to the LabJack device
  1576. ePut is equivilent to an AddRequest followed by a GoOne.
  1577. For Windows Only
  1578. Sample Usage:
  1579. >>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
  1580. >>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
  1581. 0.0
  1582. >>> ePut(u3Handle, LJ_ioPUT_CONFIG, LJ_chLOCALID, 8, 0)
  1583. >>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
  1584. 8.0
  1585. @type Handle: number
  1586. @param Handle: Handle to the LabJack device.
  1587. @type IOType: number
  1588. @param IOType: IO Request to the LabJack.
  1589. @type Channel: number
  1590. @param Channel: Channel for the IO request.
  1591. @type Value: number
  1592. @param Value: Used for some requests
  1593. @type x1: number
  1594. @param x1: Used for some requests
  1595. @rtype: None
  1596. @return: Function returns nothing.
  1597. @raise LabJackException:
  1598. """
  1599. if os.name == 'nt':
  1600. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1601. pv = ctypes.c_double(Value)
  1602. ec = staticLib.ePut(Handle, IOType, Channel, pv, x1)
  1603. if ec != 0: raise LabJackException(ec)
  1604. else:
  1605. raise LabJackException(0, "Function only supported for Windows")
  1606. #Windows
  1607. def ePutS(Handle, pIOType, Channel, Value, x1):
  1608. """Put one value to the LabJack device
  1609. ePut is equivilent to an AddRequest followed by a GoOne.
  1610. For Windows Only
  1611. Sample Usage:
  1612. >>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
  1613. >>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
  1614. 0.0
  1615. >>> ePutS(u3Handle, "LJ_ioPUT_CONFIG", LJ_chLOCALID, 8, 0)
  1616. >>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
  1617. 8.0
  1618. @type Handle: number
  1619. @param Handle: Handle to the LabJack device.
  1620. @type IOType: String
  1621. @param IOType: IO Request to the LabJack.
  1622. @type Channel: number
  1623. @param Channel: Channel for the IO request.
  1624. @type Value: number
  1625. @param Value: Used for some requests
  1626. @type x1: number
  1627. @param x1: Used for some requests
  1628. @rtype: None
  1629. @return: Function returns nothing.
  1630. @raise LabJackException:
  1631. """
  1632. if os.name == 'nt':
  1633. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1634. pv = ctypes.c_double(Value)
  1635. ec = staticLib.ePutS(Handle, pIOType, Channel, pv, x1)
  1636. if ec != 0: raise LabJackException(ec)
  1637. else:
  1638. raise LabJackException(0, "Function only supported for Windows")
  1639. #Windows
  1640. def ePutSS(Handle, pIOType, pChannel, Value, x1):
  1641. """Put one value to the LabJack device
  1642. ePut is equivilent to an AddRequest followed by a GoOne.
  1643. For Windows Only
  1644. Sample Usage:
  1645. >>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
  1646. >>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
  1647. 0.0
  1648. >>> ePutSS(u3Handle, "LJ_ioPUT_CONFIG", "LJ_chLOCALID", 8, 0)
  1649. >>> eGet(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0)
  1650. 8.0
  1651. @type Handle: number
  1652. @param Handle: Handle to the LabJack device.
  1653. @type IOType: String
  1654. @param IOType: IO Request to the LabJack.
  1655. @type Channel: String
  1656. @param Channel: Channel for the IO request.
  1657. @type Value: number
  1658. @param Value: Used for some requests
  1659. @type x1: number
  1660. @param x1: Used for some requests
  1661. @rtype: None
  1662. @return: Function returns nothing.
  1663. @raise LabJackException:
  1664. """
  1665. if os.name == 'nt':
  1666. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1667. pv = ctypes.c_double(Value)
  1668. ec = staticLib.ePutSS(Handle, pIOType, pChannel, pv, x1)
  1669. if ec != 0: raise LabJackException(ec)
  1670. else:
  1671. raise LabJackException(0, "Function only supported for Windows")
  1672. #Windows
  1673. def GetResult(Handle, IOType, Channel):
  1674. """Put one value to the LabJack device
  1675. ePut is equivilent to an AddRequest followed by a GoOne.
  1676. For Windows Only
  1677. Sample Usage:
  1678. >>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
  1679. >>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
  1680. >>> GoOne(u3Handle)
  1681. >>> value = GetResult(u3Handle, LJ_ioGET_CONFIG, LJ_chFIRMWARE_VERSION)
  1682. >>> print "Value:" + str(value)
  1683. Value:1.27
  1684. @type Handle: number
  1685. @param Handle: Handle to the LabJack device.
  1686. @type IOType: number
  1687. @param IOType: IO Request to the LabJack.
  1688. @type Channel: number
  1689. @param Channel: Channel for the IO request.
  1690. @rtype: number
  1691. @return: The value requested.
  1692. - value
  1693. @raise LabJackException:
  1694. """
  1695. if os.name == 'nt':
  1696. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1697. pv = ctypes.c_double()
  1698. ec = staticLib.GetResult(Handle, IOType, Channel, ctypes.byref(pv))
  1699. if ec != 0: raise LabJackException(ec)
  1700. return pv.value
  1701. else:
  1702. raise LabJackException(0, "Function only supported for Windows")
  1703. #Windows
  1704. def GetResultS(Handle, pIOType, Channel):
  1705. """Put one value to the LabJack device
  1706. ePut is equivilent to an AddRequest followed by a GoOne.
  1707. For Windows Only
  1708. Sample Usage:
  1709. >>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
  1710. >>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
  1711. >>> GoOne(u3Handle)
  1712. >>> value = GetResultS(u3Handle, "LJ_ioGET_CONFIG", LJ_chFIRMWARE_VERSION)
  1713. >>> print "Value:" + str(value)
  1714. Value:1.27
  1715. @type Handle: number
  1716. @param Handle: Handle to the LabJack device.
  1717. @type pIOType: String
  1718. @param pIOType: IO Request to the LabJack.
  1719. @type Channel: number
  1720. @param Channel: Channel for the IO request.
  1721. @rtype: number
  1722. @return: The value requested.
  1723. - value
  1724. @raise LabJackException:
  1725. """
  1726. if os.name == 'nt':
  1727. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1728. pv = ctypes.c_double()
  1729. ec = staticLib.GetResultS(Handle, pIOType, Channel, ctypes.byref(pv))
  1730. if ec != 0: raise LabJackException(ec)
  1731. return pv.value
  1732. else:
  1733. raise LabJackException(0, "Function only supported for Windows")
  1734. #Windows
  1735. def GetResultSS(Handle, pIOType, pChannel):
  1736. """Put one value to the LabJack device
  1737. ePut is equivilent to an AddRequest followed by a GoOne.
  1738. For Windows Only
  1739. Sample Usage:
  1740. >>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
  1741. >>> AddRequestSS(u3Handle,"LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION", 0.0, 0, 0.0)
  1742. >>> GoOne(u3Handle)
  1743. >>> value = GetResultSS(u3Handle, "LJ_ioGET_CONFIG", "LJ_chFIRMWARE_VERSION")
  1744. >>> print "Value:" + str(value)
  1745. Value:1.27
  1746. @type Handle: number
  1747. @param Handle: Handle to the LabJack device.
  1748. @type pIOType: String
  1749. @param pIOType: IO Request to the LabJack.
  1750. @type Channel: String
  1751. @param Channel: Channel for the IO request.
  1752. @rtype: number
  1753. @return: The value requested.
  1754. - value
  1755. @raise LabJackException:
  1756. """
  1757. if os.name == 'nt':
  1758. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1759. pv = ctypes.c_double()
  1760. ec = staticLib.GetResultS(Handle, pIOType, pChannel, ctypes.byref(pv))
  1761. if ec != 0: raise LabJackException(ec)
  1762. return pv.value
  1763. else:
  1764. raise LabJackException(0, "Function only supported for Windows")
  1765. #Windows
  1766. def GetFirstResult(Handle):
  1767. """List All LabJack devices of a specific type over a specific connection type.
  1768. For Windows only.
  1769. Sample Usage (Shows getting the localID (8) and firmware version (1.27) of a U3 device):
  1770. >>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
  1771. >>> AddRequest(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0, 0)
  1772. >>> AddRequest(u3Handle, LJ_ioGET_CONFIG, LJ_chFIRMWARE_VERSION, 0, 0, 0)
  1773. >>> Go()
  1774. >>> GetFirstResult(u3Handle)
  1775. (1001, 0, 8.0, 0, 0.0)
  1776. >>> GetNextResult(u3Handle)
  1777. (1001, 11, 1.27, 0, 0.0)
  1778. @type DeviceType: number
  1779. @param DeviceType: The LabJack device.
  1780. @type ConnectionType: number
  1781. @param ConnectionType: The connection method (Ethernet/USB).
  1782. @rtype: Tuple
  1783. @return: The tuple (ioType, channel, value, x1, userData)
  1784. - ioType (number): The io of the result.
  1785. - serialNumber (number): The channel of the result.
  1786. - value (number): The requested result.
  1787. - x1 (number): Used only in certain requests.
  1788. - userData (number): Used only in certain requests.
  1789. @raise LabJackException:
  1790. """
  1791. if os.name == 'nt':
  1792. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1793. pio = ctypes.c_long()
  1794. pchan = ctypes.c_long()
  1795. pv = ctypes.c_double()
  1796. px = ctypes.c_long()
  1797. pud = ctypes.c_double()
  1798. ec = staticLib.GetFirstResult(Handle, ctypes.byref(pio),
  1799. ctypes.byref(pchan), ctypes.byref(pv),
  1800. ctypes.byref(px), ctypes.byref(pud))
  1801. if ec != 0: raise LabJackException(ec)
  1802. return pio.value, pchan.value, pv.value, px.value, pud.value
  1803. else:
  1804. raise LabJackException(0, "Function only supported for Windows")
  1805. #Windows
  1806. def GetNextResult(Handle):
  1807. """List All LabJack devices of a specific type over a specific connection type.
  1808. For Windows only.
  1809. Sample Usage (Shows getting the localID (8) and firmware version (1.27) of a U3 device):
  1810. >>> u3Handle = OpenLabJack(LJ_dtU3, LJ_ctUSB, "0", 1)
  1811. >>> AddRequest(u3Handle, LJ_ioGET_CONFIG, LJ_chLOCALID, 0, 0, 0)
  1812. >>> AddRequest(u3Handle, LJ_ioGET_CONFIG, LJ_chFIRMWARE_VERSION, 0, 0, 0)
  1813. >>> Go()
  1814. >>> GetFirstResult(u3Handle)
  1815. (1001, 0, 8.0, 0, 0.0)
  1816. >>> GetNextResult(u3Handle)
  1817. (1001, 11, 1.27, 0, 0.0)
  1818. @type DeviceType: number
  1819. @param DeviceType: The LabJack device.
  1820. @type ConnectionType: number
  1821. @param ConnectionType: The connection method (Ethernet/USB).
  1822. @rtype: Tuple
  1823. @return: The tuple (ioType, channel, value, x1, userData)
  1824. - ioType (number): The io of the result.
  1825. - serialNumber (number): The channel of the result.
  1826. - value (number): The requested result.
  1827. - x1 (number): Used only in certain requests.
  1828. - userData (number): Used only in certain requests.
  1829. @raise LabJackException:
  1830. """
  1831. if os.name == 'nt':
  1832. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1833. pio = ctypes.c_long()
  1834. pchan = ctypes.c_long()
  1835. pv = ctypes.c_double()
  1836. px = ctypes.c_long()
  1837. pud = ctypes.c_double()
  1838. ec = staticLib.GetNextResult(Handle, ctypes.byref(pio),
  1839. ctypes.byref(pchan), ctypes.byref(pv),
  1840. ctypes.byref(px), ctypes.byref(pud))
  1841. if ec != 0: raise LabJackException(ec)
  1842. return pio.value, pchan.value, pv.value, px.value, pud.value
  1843. else:
  1844. raise LabJackException(0, "Function only supported for Windows")
  1845. #Windows
  1846. def DoubleToStringAddress(number):
  1847. """Converts a number (base 10) to an IP string.
  1848. For Windows
  1849. Sample Usage:
  1850. >>> DoubleToStringAddress(3232235985)
  1851. '192.168.1.209'
  1852. @type number: number
  1853. @param number: Number to be converted.
  1854. @rtype: String
  1855. @return: The IP string converted from the number (base 10).
  1856. @raise LabJackException:
  1857. """
  1858. number = int(number)
  1859. address = "%i.%i.%i.%i" % ((number >> 8*3 & 0xFF), (number >> 8*2 & 0xFF), (number >> 8 & 0xFF), (number & 0xFF))
  1860. return address
  1861. def StringToDoubleAddress(pString):
  1862. """Converts an IP string to a number (base 10).
  1863. Sample Usage:
  1864. >>> StringToDoubleAddress("192.168.1.209")
  1865. 3232235985L
  1866. @type pString: String
  1867. @param pString: String to be converted.
  1868. @rtype: number
  1869. @return: The number (base 10) that represents the IP string.
  1870. @raise LabJackException:
  1871. """
  1872. parts = pString.split('.')
  1873. if len(parts) is not 4:
  1874. raise LabJackException(0, "IP address not correctly formatted")
  1875. try:
  1876. value = (int(parts[0]) << 8*3) + (int(parts[1]) << 8*2) + (int(parts[2]) << 8) + int(parts[3])
  1877. except ValueError:
  1878. raise LabJackException(0, "IP address not correctly formatted")
  1879. return value
  1880. #Windows
  1881. def StringToConstant(pString):
  1882. """Converts an LabJackUD valid string to its constant value.
  1883. For Windows
  1884. Sample Usage:
  1885. >>> StringToConstant("LJ_dtU3")
  1886. 3
  1887. @type pString: String
  1888. @param pString: String to be converted.
  1889. @rtype: number
  1890. @return: The number (base 10) that represents the LabJackUD string.
  1891. """
  1892. if os.name == 'nt':
  1893. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1894. a = ctypes.create_string_buffer(pString, 256)
  1895. return staticLib.StringToConstant(a)
  1896. else:
  1897. raise LabJackException(0, "Function only supported for Windows")
  1898. # To hold all the error codes and what they mean:
  1899. ERROR_TO_STRING_DICT = dict()
  1900. ERROR_TO_STRING_DICT['1'] = ("SCRATCH_WRT_FAIL", "")
  1901. ERROR_TO_STRING_DICT['2'] = ("SCRATCH_ERASE_FAIL", "")
  1902. ERROR_TO_STRING_DICT['3'] = ("DATA_BUFFER_OVERFLOW", "")
  1903. ERROR_TO_STRING_DICT['4'] = ("ADC0_BUFFER_OVERFLOW", "")
  1904. ERROR_TO_STRING_DICT['5'] = ("FUNCTION_INVALID", "")
  1905. ERROR_TO_STRING_DICT['6'] = ("SWDT_TIME_INVALID", "This error is caused when an invalid time was passed to the watchdog.")
  1906. ERROR_TO_STRING_DICT['7'] = ("XBR_CONFIG_ERROR", "")
  1907. ERROR_TO_STRING_DICT['16'] = ("FLASH_WRITE_FAIL", "For some reason, the LabJack was unable to write the specified page of its internal flash.")
  1908. ERROR_TO_STRING_DICT['17'] = ("FLASH_ERASE_FAIL", "For some reason, the LabJack was unable to erase the specified page of its internal flash.")
  1909. ERROR_TO_STRING_DICT['18'] = ("FLASH_JMP_FAIL", "For some reason, the LabJack was unable to jump to a different section of flash. This may be an indication the flash is corrupted.")
  1910. ERROR_TO_STRING_DICT['19'] = ("FLASH_PSP_TIMEOUT", "")
  1911. ERROR_TO_STRING_DICT['20'] = ("FLASH_ABORT_RECEIVED", "")
  1912. ERROR_TO_STRING_DICT['21'] = ("FLASH_PAGE_MISMATCH", "")
  1913. ERROR_TO_STRING_DICT['22'] = ("FLASH_BLOCK_MISMATCH", "")
  1914. ERROR_TO_STRING_DICT['23'] = ("FLASH_PAGE_NOT_IN_CODE_AREA", "Usually, this error is raised when you try to write new firmware before upgrading the bootloader.")
  1915. ERROR_TO_STRING_DICT['24'] = ("MEM_ILLEGAL_ADDRESS", "")
  1916. ERROR_TO_STRING_DICT['25'] = ("FLASH_LOCKED", "Tried to write to flash before unlocking it.")
  1917. ERROR_TO_STRING_DICT['26'] = ("INVALID_BLOCK", "")
  1918. ERROR_TO_STRING_DICT['27'] = ("FLASH_ILLEGAL_PAGE", "")
  1919. ERROR_TO_STRING_DICT['28'] = ("FLASH_TOO_MANY_BYTES", "")
  1920. ERROR_TO_STRING_DICT['29'] = ("FLASH_INVALID_STRING_NUM", "")
  1921. ERROR_TO_STRING_DICT['40'] = ("SHT1x_COMM_TIME_OUT", "LabJack never received the ACK it was expecting from the SHT. This is usually due to incorrect wiring. Double check that all wires are securely connected to the correct pins.")
  1922. ERROR_TO_STRING_DICT['41'] = ("SHT1x_NO_ACK", "")
  1923. ERROR_TO_STRING_DICT['42'] = ("SHT1x_CRC_FAILED", "")
  1924. ERROR_TO_STRING_DICT['43'] = ("SHT1x_TOO_MANY_W_BYTES", "")
  1925. ERROR_TO_STRING_DICT['44'] = ("SHT1x_TOO_MANY_R_BYTES", "")
  1926. ERROR_TO_STRING_DICT['45'] = ("SHT1x_INVALID_MODE", "")
  1927. ERROR_TO_STRING_DICT['46'] = ("SHT1x_INVALID_LINE", "")
  1928. ERROR_TO_STRING_DICT['48'] = ("STREAM_IS_ACTIVE", "This error is raised when you call StreamStart after the stream has already been started.")
  1929. ERROR_TO_STRING_DICT['49'] = ("STREAM_TABLE_INVALID", "")
  1930. ERROR_TO_STRING_DICT['50'] = ("STREAM_CONFIG_INVALID", "")
  1931. ERROR_TO_STRING_DICT['52'] = ("STREAM_NOT_RUNNING", "This error is raised when you call StopStream after the stream has already been stopped.")
  1932. ERROR_TO_STRING_DICT['53'] = ("STREAM_INVALID_TRIGGER", "")
  1933. ERROR_TO_STRING_DICT['54'] = ("STREAM_ADC0_BUFFER_OVERFLOW", "")
  1934. ERROR_TO_STRING_DICT['55'] = ("STREAM_SCAN_OVERLAP", "This error is raised when a scan interrupt is fired before the LabJack has completed the previous scan. The most common cause of this error is a configuration with a high sampling rate and a large number of channels.")
  1935. ERROR_TO_STRING_DICT['56'] = ("STREAM_SAMPLE_NUM_INVALID", "")
  1936. ERROR_TO_STRING_DICT['57'] = ("STREAM_BIPOLAR_GAIN_INVALID", "")
  1937. ERROR_TO_STRING_DICT['58'] = ("STREAM_SCAN_RATE_INVALID", "")
  1938. ERROR_TO_STRING_DICT['59'] = ("STREAM_AUTORECOVER_ACTIVE", "This error is to inform you that the autorecover feature has been activated. Autorecovery is usually triggered by not reading data fast enough from the LabJack.")
  1939. ERROR_TO_STRING_DICT['60'] = ("STREAM_AUTORECOVER_REPORT", "This error marks the packet as an autorecovery report packet which contains how many packets were lost.")
  1940. ERROR_TO_STRING_DICT['63'] = ("STREAM_AUTORECOVER_OVERFLOW", "")
  1941. ERROR_TO_STRING_DICT['64'] = ("TIMER_INVALID_MODE", "")
  1942. ERROR_TO_STRING_DICT['65'] = ("TIMER_QUADRATURE_AB_ERROR", "")
  1943. ERROR_TO_STRING_DICT['66'] = ("TIMER_QUAD_PULSE_SEQUENCE", "")
  1944. ERROR_TO_STRING_DICT['67'] = ("TIMER_BAD_CLOCK_SOURCE", "")
  1945. ERROR_TO_STRING_DICT['68'] = ("TIMER_STREAM_ACTIVE", "")
  1946. ERROR_TO_STRING_DICT['69'] = ("TIMER_PWMSTOP_MODULE_ERROR", "")
  1947. ERROR_TO_STRING_DICT['70'] = ("TIMER_SEQUENCE_ERROR", "")
  1948. ERROR_TO_STRING_DICT['71'] = ("TIMER_LINE_SEQUENCE_ERROR", "")
  1949. ERROR_TO_STRING_DICT['72'] = ("TIMER_SHARING_ERROR", "")
  1950. ERROR_TO_STRING_DICT['80'] = ("EXT_OSC_NOT_STABLE", "")
  1951. ERROR_TO_STRING_DICT['81'] = ("INVALID_POWER_SETTING", "")
  1952. ERROR_TO_STRING_DICT['82'] = ("PLL_NOT_LOCKED", "")
  1953. ERROR_TO_STRING_DICT['96'] = ("INVALID_PIN", "")
  1954. ERROR_TO_STRING_DICT['97'] = ("PIN_CONFIGURED_FOR_ANALOG", "This error is raised when you try to do a digital operation on a pin that's configured for analog. Use a command like ConfigIO to set the pin to digital.")
  1955. ERROR_TO_STRING_DICT['98'] = ("PIN_CONFIGURED_FOR_DIGITAL", "This error is raised when you try to do an analog operation on a pin which is configured for digital. Use a command like ConfigIO to set the pin to analog.")
  1956. ERROR_TO_STRING_DICT['99'] = ("IOTYPE_SYNCH_ERROR", "")
  1957. ERROR_TO_STRING_DICT['100'] = ("INVALID_OFFSET", "")
  1958. ERROR_TO_STRING_DICT['101'] = ("IOTYPE_NOT_VALID", "")
  1959. ERROR_TO_STRING_DICT['102'] = ("TC_PIN_OFFSET_MUST_BE_4-8", "This error is raised when you try to configure the Timer/Counter pin offset to be 0-3.")
  1960. def lowlevelErrorToString( errorcode ):
  1961. """Converts a low-level errorcode into a string.
  1962. """
  1963. try:
  1964. name, advice = ERROR_TO_STRING_DICT[str(errorcode)]
  1965. except KeyError:
  1966. name = "UNKNOWN_ERROR"
  1967. advice = "Unrecognized error code (%s)" % errorcode
  1968. if advice is not "":
  1969. msg = "%s (%s)\n%s" % (name, errorcode, advice)
  1970. else:
  1971. msg = "%s (%s)" % (name, errorcode)
  1972. return msg
  1973. #Windows
  1974. def ErrorToString(ErrorCode):
  1975. """Converts an LabJackUD valid error code to a String.
  1976. For Windows
  1977. Sample Usage:
  1978. >>> ErrorToString(1007)
  1979. 'LabJack not found'
  1980. @type ErrorCode: number
  1981. @param ErrorCode: Valid LabJackUD error code.
  1982. @rtype: String
  1983. @return: The string that represents the valid LabJackUD error code
  1984. """
  1985. if os.name == 'nt':
  1986. staticLib = ctypes.windll.LoadLibrary("labjackud")
  1987. pString = ctypes.create_string_buffer(256)
  1988. staticLib.ErrorToString(ctypes.c_long(ErrorCode), ctypes.byref(pString))
  1989. return pString.value
  1990. else:
  1991. raise LabJackException(0, "Function only supported for Windows")
  1992. #Windows, Linux, and Mac
  1993. def GetDriverVersion():
  1994. """Converts an LabJackUD valid error code to a String.
  1995. For Windows, Linux, and Mac
  1996. Sample Usage:
  1997. >>> GetDriverVersion()
  1998. 2.64
  1999. >>> GetDriverVersion()
  2000. Mac
  2001. @rtype: number/String
  2002. @return: Value of the driver version as a String
  2003. - For Mac machines the return type is "Mac"
  2004. - For Windows and Linux systems the return type is a number that represents the driver version
  2005. """
  2006. if os.name == 'nt':
  2007. staticLib.GetDriverVersion.restype = ctypes.c_float
  2008. return str(staticLib.GetDriverVersion())
  2009. elif os.name == 'posix':
  2010. staticLib.LJUSB_GetLibraryVersion.restype = ctypes.c_float
  2011. return "%.2f" % staticLib.LJUSB_GetLibraryVersion()
  2012. #Windows
  2013. def TCVoltsToTemp(TCType, TCVolts, CJTempK):
  2014. """Converts a thermo couple voltage reading to an appropriate temperature reading.
  2015. For Windows
  2016. Sample Usage:
  2017. >>> TCVoltsToTemp(LJ_ttK, 0.003141592, 297.038889)
  2018. 373.13353222244825
  2019. @type TCType: number
  2020. @param TCType: The type of thermo couple used.
  2021. @type TCVolts: number
  2022. @param TCVolts: The voltage reading from the thermo couple
  2023. @type CJTempK: number
  2024. @param CJTempK: The cold junction temperature reading in Kelvin
  2025. @rtype: number
  2026. @return: The thermo couples temperature reading
  2027. - pTCTempK
  2028. @raise LabJackException:
  2029. """
  2030. if os.name == 'nt':
  2031. staticLib = ctypes.windll.LoadLibrary("labjackud")
  2032. pTCTempK = ctypes.c_double()
  2033. ec = staticLib.TCVoltsToTemp(ctypes.c_long(TCType), ctypes.c_double(TCVolts),
  2034. ctypes.c_double(CJTempK), ctypes.byref(pTCTempK))
  2035. if ec != 0: raise LabJackException(ec)
  2036. return pTCTempK.value
  2037. else:
  2038. raise LabJackException(0, "Function only supported for Windows")
  2039. #Windows
  2040. def Close():
  2041. """Resets the driver and closes all open handles.
  2042. For Windows
  2043. Sample Usage:
  2044. >>> Close()
  2045. @rtype: None
  2046. @return: The function returns nothing.
  2047. """
  2048. opSys = os.name
  2049. if(opSys == 'nt'):
  2050. staticLib = ctypes.windll.LoadLibrary("labjackud")
  2051. staticLib.Close()
  2052. else:
  2053. raise LabJackException(0, "Function only supported for Windows")
  2054. #Windows, Linux and Mac
  2055. def DriverPresent():
  2056. try:
  2057. ctypes.windll.LoadLibrary("labjackud")
  2058. return True
  2059. except:
  2060. try:
  2061. ctypes.cdll.LoadLibrary("liblabjackusb.so")
  2062. return True
  2063. except:
  2064. try:
  2065. ctypes.cdll.LoadLibrary("liblabjackusb.dylib")
  2066. return True
  2067. except:
  2068. return False
  2069. return False
  2070. return False
  2071. def U12DriverPresent():
  2072. try:
  2073. ctypes.windll.LoadLibrary("ljackuw")
  2074. return True
  2075. except:
  2076. return False
  2077. #Windows only
  2078. def LJHash(hashStr, size):
  2079. """An approximation of the md5 hashing algorithms.
  2080. For Windows
  2081. An approximation of the md5 hashing algorithm. Used
  2082. for authorizations on UE9 version 1.73 and higher and u3
  2083. version 1.35 and higher.
  2084. @type hashStr: String
  2085. @param hashStr: String to be hashed.
  2086. @type size: number
  2087. @param size: Amount of bytes to hash from the hashStr
  2088. @rtype: String
  2089. @return: The hashed string.
  2090. """
  2091. print "Hash String:" + str(hashStr)
  2092. outBuff = (ctypes.c_char * 16)()
  2093. retBuff = ''
  2094. staticLib = ctypes.windll.LoadLibrary("labjackud")
  2095. ec = staticLib.LJHash(ctypes.cast(hashStr, ctypes.POINTER(ctypes.c_char)),
  2096. size,
  2097. ctypes.cast(outBuff, ctypes.POINTER(ctypes.c_char)),
  2098. 0)
  2099. if ec != 0: raise LabJackException(ec)
  2100. for i in range(16):
  2101. retBuff += outBuff[i]
  2102. return retBuff
  2103. def __listAllUE9Unix(connectionType):
  2104. """Private listAll function for use on unix and mac machines to find UE9s.
  2105. """
  2106. deviceList = {}
  2107. rcvDataBuff = []
  2108. if connectionType == LJ_ctUSB:
  2109. numDevices = staticLib.LJUSB_GetDevCount(LJ_dtUE9)
  2110. for i in xrange(numDevices):
  2111. try:
  2112. device = openLabJack(LJ_dtUE9, 1, firstFound = False, devNumber = i+1)
  2113. device.close()
  2114. deviceList[str(device.serialNumber)] = device.__dict__
  2115. except LabJackException:
  2116. pass
  2117. elif connectionType == LJ_ctETHERNET:
  2118. #Create a socket
  2119. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  2120. s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
  2121. s.settimeout(BROADCAST_SOCKET_TIMEOUT)
  2122. sndDataBuff = [0] * 6
  2123. sndDataBuff[0] = 0x22
  2124. sndDataBuff[1] = 0x78
  2125. sndDataBuff[3] = 0xa9
  2126. outBuff = ""
  2127. for item in sndDataBuff:
  2128. outBuff += chr(item)
  2129. s.sendto(outBuff, ("255.255.255.255", 52362))
  2130. try:
  2131. while True:
  2132. rcvDataBuff = s.recv(128)
  2133. try:
  2134. rcvDataBuff = [ord(val) for val in rcvDataBuff]
  2135. if verifyChecksum(rcvDataBuff):
  2136. #Parse the packet
  2137. macAddress = rcvDataBuff[28:34]
  2138. macAddress.reverse()
  2139. # The serial number is four bytes:
  2140. # 0x10 and the last three bytes of the MAC address
  2141. serialBytes = chr(0x10)
  2142. for j in macAddress[3:]:
  2143. serialBytes += chr(j)
  2144. serial = struct.unpack(">I", serialBytes)[0]
  2145. #Parse out the IP address
  2146. ipAddress = ""
  2147. for j in range(13, 9, -1):
  2148. ipAddress += str(int(rcvDataBuff[j]))
  2149. ipAddress += "."
  2150. ipAddress = ipAddress[0:-1]
  2151. #Local ID
  2152. localId = rcvDataBuff[8] & 0xff
  2153. deviceList[serial] = dict(devType = LJ_dtUE9, localId = localId, \
  2154. serialNumber = serial, ipAddress = ipAddress)
  2155. except Exception, e:
  2156. pass
  2157. except:
  2158. pass
  2159. return deviceList
  2160. def __listAllU3Unix():
  2161. """Private listAll function for unix and mac machines. Works on the U3 only.
  2162. """
  2163. deviceList = {}
  2164. numDevices = staticLib.LJUSB_GetDevCount(LJ_dtU3)
  2165. for i in xrange(numDevices):
  2166. try:
  2167. device = openLabJack(LJ_dtU3, 1, firstFound = False, devNumber = i+1)
  2168. device.close()
  2169. deviceList[str(device.serialNumber)] = device.__dict__
  2170. except LabJackException:
  2171. pass
  2172. return deviceList
  2173. def __listAllU6Unix():
  2174. """ List all for U6s """
  2175. deviceList = {}
  2176. numDevices = staticLib.LJUSB_GetDevCount(LJ_dtU6)
  2177. for i in xrange(numDevices):
  2178. try:
  2179. device = openLabJack(LJ_dtU6, 1, firstFound = False, devNumber = i+1)
  2180. device.close()
  2181. deviceList[str(device.serialNumber)] = device.__dict__
  2182. except LabJackException:
  2183. pass
  2184. return deviceList
  2185. def __listAllBridgesUnix():
  2186. """ List all for Bridges """
  2187. deviceList = {}
  2188. numDevices = staticLib.LJUSB_GetDevCount(0x501)
  2189. for i in xrange(numDevices):
  2190. try:
  2191. device = openLabJack(0x501, 1, firstFound = False, devNumber = i+1)
  2192. device.close()
  2193. deviceList[str(device.serialNumber)] = device.__dict__
  2194. except LabJackException:
  2195. pass
  2196. return deviceList
  2197. def setChecksum16(buffer):
  2198. total = 0;
  2199. for i in range(6, len(buffer)):
  2200. total += (buffer[i] & 0xff)
  2201. buffer[4] = (total & 0xff)
  2202. buffer[5] = ((total >> 8) & 0xff)
  2203. return buffer
  2204. def setChecksum8(buffer, numBytes):
  2205. total = 0
  2206. for i in range(1, numBytes):
  2207. total += (buffer[i] & 0xff)
  2208. buffer[0] = (total & 0xff) + ((total >> 8) & 0xff)
  2209. buffer[0] = (buffer[0] & 0xff) + ((buffer[0] >> 8) & 0xff)
  2210. return buffer
  2211. class LJSocketHandle(object):
  2212. """
  2213. Class to replace a device handle with a socket to a LJSocket server.
  2214. """
  2215. def __init__(self, ipAddress, port, devType, firstFound, pAddress):
  2216. try:
  2217. serverSocket = socket.socket()
  2218. serverSocket.connect((ipAddress, port))
  2219. serverSocket.settimeout(SOCKET_TIMEOUT)
  2220. f = serverSocket.makefile(bufsize = 0)
  2221. f.write("scan\r\n")
  2222. l = f.readline().strip()
  2223. try:
  2224. status, numLines = l.split(' ')
  2225. except ValueError:
  2226. raise Exception("Got invalid line from server: %s" % l)
  2227. if status.lower().startswith('ok'):
  2228. lines = []
  2229. marked = None
  2230. for i in range(int(numLines)):
  2231. l = f.readline().strip()
  2232. dev = parseline(l)
  2233. if devType == dev['prodId']:
  2234. lines.append(dev)
  2235. if not firstFound and (dev['localId'] == pAddress or dev['serial'] == pAddress):
  2236. marked = dev
  2237. f.close()
  2238. serverSocket.close()
  2239. #print "Result of scan:"
  2240. #print lines
  2241. if firstFound and len(lines) > 0:
  2242. marked = lines[0]
  2243. elif marked is not None:
  2244. pass
  2245. else:
  2246. raise Exception("LabJack not found.")
  2247. if marked['crPort'] != 'x':
  2248. self.crSocket = socket.socket()
  2249. self.crSocket.connect((ipAddress, marked['crPort']))
  2250. self.crSocket.settimeout(LJSOCKET_TIMEOUT)
  2251. else:
  2252. self.crSocket = None
  2253. if marked['modbusPort'] != 'x':
  2254. self.modbusSocket = socket.socket()
  2255. self.modbusSocket.connect((ipAddress, marked['modbusPort']))
  2256. self.modbusSocket.settimeout(LJSOCKET_TIMEOUT)
  2257. else:
  2258. self.modbusSocket = None
  2259. if marked['spontPort'] != 'x':
  2260. self.spontSocket = socket.socket()
  2261. self.spontSocket.connect((ipAddress, marked['spontPort']))
  2262. self.spontSocket.settimeout(LJSOCKET_TIMEOUT)
  2263. else:
  2264. self.spontSocket = None
  2265. else:
  2266. raise Exception("Got an error from LJSocket. It said '%s'" % l)
  2267. except Exception, e:
  2268. raise LabJackException(ec = LJE_LABJACK_NOT_FOUND, errorString = "Couldn't connect to a LabJack at %s:%s. The error was: %s" % (ipAddress, port, str(e)))
  2269. def close(self):
  2270. if self.crSocket is not None:
  2271. self.crSocket.close()
  2272. if self.modbusSocket is not None:
  2273. self.modbusSocket.close()
  2274. if self.spontSocket is not None:
  2275. self.spontSocket.close()
  2276. def parseline(line):
  2277. try:
  2278. prodId, crPort, modbusPort, spontPort, localId, serial = line.split(' ')
  2279. if not crPort.startswith('x'):
  2280. crPort = int(crPort)
  2281. if not modbusPort.startswith('x'):
  2282. modbusPort = int(modbusPort)
  2283. if not spontPort.startswith('x'):
  2284. spontPort = int(spontPort)
  2285. except ValueError:
  2286. raise Exception("")
  2287. return { 'prodId' : int(prodId), 'crPort' : crPort, 'modbusPort' : modbusPort, 'spontPort' : spontPort, 'localId' : int(localId), 'serial' : int(serial) }
  2288. #Class for handling UE9 TCP Connections
  2289. class UE9TCPHandle(object):
  2290. """__UE9TCPHandle(ipAddress)
  2291. Creates two sockets for the streaming and non streaming ports on the UE9.
  2292. Also, tries to create a socket for the Modbus port. Only works on
  2293. default ports (Data 52360, Stream 52361, Modbus 502).
  2294. """
  2295. def __init__(self, ipAddress, timeout = SOCKET_TIMEOUT):
  2296. try:
  2297. self.data = socket.socket()
  2298. self.data.settimeout(timeout)
  2299. self.data.connect((ipAddress, 52360))
  2300. self.stream = socket.socket()
  2301. self.stream.settimeout(timeout)
  2302. self.stream.connect((ipAddress, 52361))
  2303. try:
  2304. self.modbus = socket.socket()
  2305. self.modbus.settimeout(timeout)
  2306. self.modbus.connect((ipAddress, 502))
  2307. except socket.error, e:
  2308. self.modbus = None
  2309. except Exception, e:
  2310. print e
  2311. raise LabJackException("Couldn't open sockets to the UE9 at IP Address %s. Error was: %s" % (ipAddress, e))
  2312. def close(self):
  2313. try:
  2314. self.data.close()
  2315. self.stream.close()
  2316. self.modbus.close()
  2317. except Exception, e:
  2318. print "UE9 Handle close exception: ", e
  2319. pass
  2320. def toDouble(bytes):
  2321. """
  2322. Name: toDouble(buffer)
  2323. Args: buffer, an array with 8 bytes
  2324. Desc: Converts the 8 byte array into a floating point number.
  2325. """
  2326. right, left = struct.unpack("<Ii", struct.pack("B" * 8, *bytes[0:8]))
  2327. return float(left) + float(right)/(2**32)
  2328. def hexWithoutQuotes(l):
  2329. """ Return a string listing hex without all the single quotes.
  2330. >>> l = range(10)
  2331. >>> print hexWithoutQuotes(l)
  2332. [0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9]
  2333. """
  2334. return str([hex (i) for i in l]).replace("'", "")
  2335. # device types:
  2336. LJ_dtUE9 = 9
  2337. LJ_dtU3 = 3
  2338. LJ_dtU6 = 6
  2339. # connection types:
  2340. LJ_ctUSB = 1 # UE9 + U3 + U6
  2341. LJ_ctETHERNET = 2 # UE9 only
  2342. # Raw connection types are used to open a device but not communicate with it
  2343. # should only be used if the normal connection types fail and for testing.
  2344. # If a device is opened with the raw connection types, only LJ_ioRAW_OUT
  2345. # and LJ_ioRAW_IN io types should be used
  2346. LJ_ctUSB_RAW = 101 # UE9 + U3 + U6
  2347. LJ_ctETHERNET_RAW = 102 # UE9 only
  2348. LJ_ctLJSOCKET = 200 # Connection type for USB LabJack connected to LJSocket server
  2349. # io types:
  2350. LJ_ioGET_AIN = 10 # UE9 + U3 + U6. This is single ended version.
  2351. LJ_ioGET_AIN_DIFF = 15 # U3 + U6. Put second channel in x1. For U3, if 32 is
  2352. # passed as x1, Vref will be added to the result.
  2353. LJ_ioPUT_AIN_RANGE = 2000 # UE9 + U6
  2354. LJ_ioGET_AIN_RANGE = 2001 # UE9 + U6
  2355. # sets or reads the analog or digital mode of the FIO and EIO pins. FIO is Channel 0-7, EIO 8-15
  2356. LJ_ioPUT_ANALOG_ENABLE_BIT = 2013 # U3
  2357. LJ_ioGET_ANALOG_ENABLE_BIT = 2014 # U3
  2358. # sets or reads the analog or digital mode of the FIO and EIO pins. Channel is starting
  2359. # bit #, x1 is number of bits to read. The pins are set by passing a bitmask as a double
  2360. # for the value. The first bit of the int that the double represents will be the setting
  2361. # for the pin number sent into the channel variable.
  2362. LJ_ioPUT_ANALOG_ENABLE_PORT = 2015 # U3
  2363. LJ_ioGET_ANALOG_ENABLE_PORT = 2016 # U3
  2364. LJ_ioPUT_DAC = 20 # UE9 + U3 + U6
  2365. LJ_ioPUT_DAC_ENABLE = 2002 # UE9 + U3 (U3 on Channel 1 only)
  2366. LJ_ioGET_DAC_ENABLE = 2003 # UE9 + U3 (U3 on Channel 1 only)
  2367. LJ_ioGET_DIGITAL_BIT = 30 # UE9 + U3 + U6. Changes direction of bit to input as well.
  2368. LJ_ioGET_DIGITAL_BIT_DIR = 31 # U3 + U6
  2369. LJ_ioGET_DIGITAL_BIT_STATE = 32 # does not change direction of bit, allowing readback of output
  2370. # channel is starting bit #, x1 is number of bits to read
  2371. LJ_ioGET_DIGITAL_PORT = 35 # UE9 + U3 + U6. Changes direction of bits to input as well.
  2372. LJ_ioGET_DIGITAL_PORT_DIR = 36 # U3 + U6
  2373. LJ_ioGET_DIGITAL_PORT_STATE = 37 # does not change direction of bits, allowing readback of output
  2374. # digital put commands will set the specified digital line(s) to output
  2375. LJ_ioPUT_DIGITAL_BIT = 40 # UE9 + U3
  2376. # channel is starting bit #, value is output value, x1 is bits to write
  2377. LJ_ioPUT_DIGITAL_PORT = 45 # UE9 + U3
  2378. # Used to create a pause between two events in a U3 and U6 low-level feedback
  2379. # command. For example, to create a 100 ms positive pulse on FIO0, add a
  2380. # request to set FIO0 high, add a request for a wait of 100000, add a
  2381. # request to set FIO0 low, then Go. Channel is ignored. Value is
  2382. # microseconds to wait and should range from 0 to 8388480. The actual
  2383. # resolution of the wait is 128 microseconds on a U3 and 64 microseconds
  2384. # on a U6.
  2385. LJ_ioPUT_WAIT = 70 # U3 + U6
  2386. # counter. Input only.
  2387. LJ_ioGET_COUNTER = 50 # UE9 + U3 + U6
  2388. LJ_ioPUT_COUNTER_ENABLE = 2008 # UE9 + U3 + U6
  2389. LJ_ioGET_COUNTER_ENABLE = 2009 # UE9 + U3 + U6
  2390. # This will cause the designated counter to reset. If you want to reset the
  2391. # counter with every read, you have to use this command every time.
  2392. LJ_ioPUT_COUNTER_RESET = 2012 # UE9 + U3 + U6
  2393. # on UE9: timer only used for input. Output Timers don't use these. Only Channel used.
  2394. # on U3: Channel used (0 or 1).
  2395. # on U6: Channel used (0 to 3).
  2396. LJ_ioGET_TIMER = 60 # UE9 + U3 + U6
  2397. LJ_ioPUT_TIMER_VALUE = 2006 # UE9 + U3 + U6. Value gets new value
  2398. LJ_ioPUT_TIMER_MODE = 2004 # UE9 + U3 + U6. On both Value gets new mode.
  2399. LJ_ioGET_TIMER_MODE = 2005 # UE9
  2400. # IOTypes for use with SHT sensor. For LJ_ioSHT_GET_READING, a channel of LJ_chSHT_TEMP (5000) will
  2401. # read temperature, and LJ_chSHT_RH (5001) will read humidity.
  2402. LJ_ioSHT_GET_READING = 500 # UE9 + U3 + U6.
  2403. # Uses settings from LJ_chSPI special channels (set with LJ_ioPUT_CONFIG) to communcaite with
  2404. # something using an SPI interface. The value parameter is the number of bytes to transfer
  2405. # and x1 is the address of the buffer. The data from the buffer will be sent, then overwritten
  2406. # with the data read. The channel parameter is ignored.
  2407. LJ_ioSPI_COMMUNICATION = 503 # UE9 + U3 + U6
  2408. LJ_ioI2C_COMMUNICATION = 504 # UE9 + U3 + U6
  2409. LJ_ioASYNCH_COMMUNICATION = 505 # UE9 + U3 + U6
  2410. LJ_ioTDAC_COMMUNICATION = 506 # UE9 + U3 + U6
  2411. # Set's the U3 to it's original configuration. This means sending the following
  2412. # to the ConfigIO and TimerClockConfig low level functions
  2413. #
  2414. # ConfigIO
  2415. # Byte #
  2416. # 6 WriteMask 15 Write all parameters.
  2417. # 8 TimerCounterConfig 0 No timers/counters. Offset=0.
  2418. # 9 DAC1Enable 0 DAC1 disabled.
  2419. # 10 FIOAnalog 0 FIO all digital.
  2420. # 11 EIOAnalog 0 EIO all digital.
  2421. #
  2422. #
  2423. # TimerClockConfig
  2424. # Byte #
  2425. # 8 TimerClockConfig 130 Set clock to 24 MHz.
  2426. # 9 TimerClockDivisor 0 Divisor = 0.
  2427. LJ_ioPIN_CONFIGURATION_RESET = 2017 # U3
  2428. # the raw in/out are unusual, channel # corresponds to the particular comm port, which
  2429. # depends on the device. For example, on the UE9, 0 is main comm port, and 1 is the streaming comm.
  2430. # Make sure and pass a porter to a char buffer in x1, and the number of bytes desired in value. A call
  2431. # to GetResult will return the number of bytes actually read/written. The max you can send out in one call
  2432. # is 512 bytes to the UE9 and 16384 bytes to the U3.
  2433. LJ_ioRAW_OUT = 100 # UE9 + U3 + U6
  2434. LJ_ioRAW_IN = 101 # UE9 + U3 + U6
  2435. LJ_ioRAWMB_OUT = 104 # Used with LJ_ctETHERNET_MB to send raw modbus commands to the modbus TCP/IP Socket
  2436. LJ_ioRAWMB_IN = 105
  2437. # sets the default power up settings based on the current settings of the device AS THIS DLL KNOWS. This last part
  2438. # basically means that you should set all parameters directly through this driver before calling this. This writes
  2439. # to flash which has a limited lifetime, so do not do this too often. Rated endurance is 20,000 writes.
  2440. LJ_ioSET_DEFAULTS = 103 # U3
  2441. # Requests to create the list of channels to stream. Usually you will use the CLEAR_STREAM_CHANNELS request first, which
  2442. # will clear any existing channels, then use ADD_STREAM_CHANNEL multiple times to add your desired channels. Note that
  2443. # you can do CLEAR, and then all your ADDs in a single Go() as long as you add the requests in order.
  2444. LJ_ioADD_STREAM_CHANNEL = 200 # UE9 + U3 + U6
  2445. # Put negative channel in x1. If 32 is passed as x1, Vref will be added to the result.
  2446. LJ_ioADD_STREAM_CHANNEL_DIFF = 206 # U3 + U6
  2447. LJ_ioCLEAR_STREAM_CHANNELS = 201
  2448. LJ_ioSTART_STREAM = 202
  2449. LJ_ioSTOP_STREAM = 203
  2450. LJ_ioADD_STREAM_DAC = 207
  2451. # Get stream data has several options. If you just want to get a single channel's data (if streaming multiple channels), you
  2452. # can pass in the desired channel #, then the number of data points desired in Value, and a pointer to an array to put the
  2453. # data into as X1. This array needs to be an array of doubles. Therefore, the array needs to be 8 * number of
  2454. # requested data points in byte length. What is returned depends on the StreamWaitMode. If None, this function will only return
  2455. # data available at the time of the call. You therefore must call GetResult() for this function to retrieve the actually number
  2456. # of points retreived. If Pump or Sleep, it will return only when the appropriate number of points have been read or no
  2457. # new points arrive within 100ms. Since there is this timeout, you still need to use GetResult() to determine if the timeout
  2458. # occured. If AllOrNone, you again need to check GetResult.
  2459. # You can also retreive the entire scan by passing LJ_chALL_CHANNELS. In this case, the Value determines the number of SCANS
  2460. # returned, and therefore, the array must be 8 * number of scans requested * number of channels in each scan. Likewise
  2461. # GetResult() will return the number of scans, not the number of data points returned.
  2462. # Note: data is stored interleaved across all streaming channels. In other words, if you are streaming two channels, 0 and 1,
  2463. # and you request LJ_chALL_CHANNELS, you will get, Channel0, Channel1, Channel0, Channel1, etc. Once you have requested the
  2464. # data, any data returned is removed from the internal buffer, and the next request will give new data.
  2465. # Note: if reading the data channel by channel and not using LJ_chALL_CHANNELS, the data is not removed from the internal buffer
  2466. # until the data from the last channel in the scan is requested. This means that if you are streaming three channels, 0, 1 and 2,
  2467. # and you request data from channel 0, then channel 1, then channel 0 again, the request for channel 0 the second time will
  2468. # return the exact same amount of data. Also note, that the amount of data that will be returned for each channel request will be
  2469. # the same until you've read the last channel in the scan, at which point your next block may be a different size.
  2470. # Note: although more convenient, requesting individual channels is slightly slower then using LJ_chALL_CHANNELS. Since you
  2471. # are probably going to have to split the data out anyway, we have saved you the trouble with this option.
  2472. # Note: if you are only scanning one channel, the Channel parameter is ignored.
  2473. LJ_ioGET_STREAM_DATA = 204
  2474. # U3 only:
  2475. # Channel = 0 buzz for a count, Channel = 1 buzz continuous
  2476. # Value is the Period
  2477. # X1 is the toggle count when channel = 0
  2478. LJ_ioBUZZER = 300 # U3
  2479. # config iotypes:
  2480. LJ_ioPUT_CONFIG = 1000 # UE9 + U3 + U6
  2481. LJ_ioGET_CONFIG = 1001 # UE9 + U3 + U6
  2482. # channel numbers used for CONFIG types:
  2483. # UE9 + U3 + U6
  2484. LJ_chLOCALID = 0 # UE9 + U3 + U6
  2485. LJ_chHARDWARE_VERSION = 10 # UE9 + U3 + U6 (Read Only)
  2486. LJ_chSERIAL_NUMBER = 12 # UE9 + U3 + U6 (Read Only)
  2487. LJ_chFIRMWARE_VERSION = 11 # UE9 + U3 + U6 (Read Only)
  2488. LJ_chBOOTLOADER_VERSION = 15 # UE9 + U3 + U6 (Read Only)
  2489. LJ_chPRODUCTID = 8 # UE9 + U3 + U6 (Read Only)
  2490. # UE9 specific:
  2491. LJ_chCOMM_POWER_LEVEL = 1 # UE9
  2492. LJ_chIP_ADDRESS = 2 # UE9
  2493. LJ_chGATEWAY = 3 # UE9
  2494. LJ_chSUBNET = 4 # UE9
  2495. LJ_chPORTA = 5 # UE9
  2496. LJ_chPORTB = 6 # UE9
  2497. LJ_chDHCP = 7 # UE9
  2498. LJ_chPRODUCTID = 8 # UE9
  2499. LJ_chMACADDRESS = 9 # UE9
  2500. LJ_chCOMM_FIRMWARE_VERSION = 11 # UE9
  2501. LJ_chCONTROL_POWER_LEVEL = 13 # UE9
  2502. LJ_chCONTROL_FIRMWARE_VERSION = 14 # UE9 (Read Only)
  2503. LJ_chCONTROL_BOOTLOADER_VERSION = 15 # UE9 (Read Only)
  2504. LJ_chCONTROL_RESET_SOURCE = 16 # UE9 (Read Only)
  2505. LJ_chUE9_PRO = 19 # UE9 (Read Only)
  2506. # U3 only:
  2507. # sets the state of the LED
  2508. LJ_chLED_STATE = 17 # U3 value = LED state
  2509. LJ_chSDA_SCL = 18 # U3 enable / disable SDA/SCL as digital I/O
  2510. LJ_chU3HV = 22 # U3 (Read Only) Value will be 1 for a U3-HV and 0 for a U3-LV
  2511. # or a U3 with hardware version < 1.30
  2512. # U6 only:
  2513. LJ_chU6_PRO = 23
  2514. # Driver related:
  2515. # Number of milliseconds that the driver will wait for communication to complete
  2516. LJ_chCOMMUNICATION_TIMEOUT = 20
  2517. LJ_chSTREAM_COMMUNICATION_TIMEOUT = 21
  2518. # Used to access calibration and user data. The address of an array is passed in as x1.
  2519. # For the UE9, a 1024-element buffer of bytes is passed for user data and a 128-element
  2520. # buffer of doubles is passed for cal constants.
  2521. # For the U3, a 256-element buffer of bytes is passed for user data and a 12-element
  2522. # buffer of doubles is passed for cal constants.
  2523. # The layout of cal ants are defined in the users guide for each device.
  2524. # When the LJ_chCAL_CONSTANTS special channel is used with PUT_CONFIG, a
  2525. # special value (0x4C6C) must be passed in to the Value parameter. This makes it
  2526. # more difficult to accidently erase the cal constants. In all other cases the Value
  2527. # parameter is ignored.
  2528. LJ_chCAL_CONSTANTS = 400 # UE9 + U3 + U6
  2529. LJ_chUSER_MEM = 402 # UE9 + U3 + U6
  2530. # Used to write and read the USB descriptor strings. This is generally for OEMs
  2531. # who wish to change the strings.
  2532. # Pass the address of an array in x1. Value parameter is ignored.
  2533. # The array should be 128 elements of bytes. The first 64 bytes are for the
  2534. # iManufacturer string, and the 2nd 64 bytes are for the iProduct string.
  2535. # The first byte of each 64 byte block (bytes 0 and 64) contains the number
  2536. # of bytes in the string. The second byte (bytes 1 and 65) is the USB spec
  2537. # value for a string descriptor (0x03). Bytes 2-63 and 66-127 contain unicode
  2538. # encoded strings (up to 31 characters each).
  2539. LJ_chUSB_STRINGS = 404 # U3
  2540. # timer/counter related
  2541. LJ_chNUMBER_TIMERS_ENABLED = 1000 # UE9 + U3 + U6
  2542. LJ_chTIMER_CLOCK_BASE = 1001 # UE9 + U3 + U6
  2543. LJ_chTIMER_CLOCK_DIVISOR = 1002 # UE9 + U3 + U6
  2544. LJ_chTIMER_COUNTER_PIN_OFFSET = 1003 # U3 + U6
  2545. # AIn related
  2546. LJ_chAIN_RESOLUTION = 2000 # UE9 + U3 + U6
  2547. LJ_chAIN_SETTLING_TIME = 2001 # UE9 + U3 + U6
  2548. LJ_chAIN_BINARY = 2002 # UE9 + U3 + U6
  2549. # DAC related
  2550. LJ_chDAC_BINARY = 3000 # UE9 + U3 + U6
  2551. # SHT related
  2552. LJ_chSHT_TEMP = 5000 # UE9 + U3 + U6
  2553. LJ_chSHT_RH = 5001 # UE9 + U3 + U6
  2554. LJ_chSHT_DATA_CHANNEL = 5002 # UE9 + U3 + U6. Default is FIO0
  2555. LJ_chSHT_CLOCK_CHANNEL = 5003 # UE9 + U3 + U6. Default is FIO1
  2556. # SPI related
  2557. LJ_chSPI_AUTO_CS = 5100 # UE9 + U3 + U6
  2558. LJ_chSPI_DISABLE_DIR_CONFIG = 5101 # UE9 + U3 + U6
  2559. LJ_chSPI_MODE = 5102 # UE9 + U3 + U6
  2560. LJ_chSPI_CLOCK_FACTOR = 5103 # UE9 + U3 + U6
  2561. LJ_chSPI_MOSI_PINNUM = 5104 # UE9 + U3 + U6
  2562. LJ_chSPI_MISO_PINNUM = 5105 # UE9 + U3 + U6
  2563. LJ_chSPI_CLK_PINNUM = 5106 # UE9 + U3 + U6
  2564. LJ_chSPI_CS_PINNUM = 5107 # UE9 + U3 + U6
  2565. # I2C related :
  2566. # used with LJ_ioPUT_CONFIG
  2567. LJ_chI2C_ADDRESS_BYTE = 5108 # UE9 + U3 + U6
  2568. LJ_chI2C_SCL_PIN_NUM = 5109 # UE9 + U3 + U6
  2569. LJ_chI2C_SDA_PIN_NUM = 5110 # UE9 + U3 + U6
  2570. LJ_chI2C_OPTIONS = 5111 # UE9 + U3 + U6
  2571. LJ_chI2C_SPEED_ADJUST = 5112 # UE9 + U3 + U6
  2572. # used with LJ_ioI2C_COMMUNICATION :
  2573. LJ_chI2C_READ = 5113 # UE9 + U3 + U6
  2574. LJ_chI2C_WRITE = 5114 # UE9 + U3 + U6
  2575. LJ_chI2C_GET_ACKS = 5115 # UE9 + U3 + U6
  2576. LJ_chI2C_WRITE_READ = 5130 # UE9 + U3
  2577. # ASYNCH related :
  2578. # Used with LJ_ioASYNCH_COMMUNICATION
  2579. LJ_chASYNCH_RX = 5117 # UE9 + U3 + U6
  2580. LJ_chASYNCH_TX = 5118 # UE9 + U3 + U6
  2581. LJ_chASYNCH_FLUSH = 5128 # UE9 + U3 + U6
  2582. LJ_chASYNCH_ENABLE = 5129 # UE9 + U3 + U6
  2583. # Used with LJ_ioPUT_CONFIG and LJ_ioGET_CONFIG
  2584. LJ_chASYNCH_BAUDFACTOR = 5127 # UE9 + U3 + U6
  2585. # LJ TickDAC related :
  2586. LJ_chTDAC_SCL_PIN_NUM = 5119 # UE9 + U3 + U6: Used with LJ_ioPUT_CONFIG
  2587. # Used with LJ_ioTDAC_COMMUNICATION
  2588. LJ_chTDAC_SERIAL_NUMBER = 5120 # UE9 + U3 + U6: Read only
  2589. LJ_chTDAC_READ_USER_MEM = 5121 # UE9 + U3 + U6
  2590. LJ_chTDAC_WRITE_USER_MEM = 5122 # UE9 + U3 + U6
  2591. LJ_chTDAC_READ_CAL_CONSTANTS = 5123 # UE9 + U3 + U6
  2592. LJ_chTDAC_WRITE_CAL_CONSTANTS = 5124 # UE9 + U3 + U6
  2593. LJ_chTDAC_UPDATE_DACA = 5125 # UE9 + U3 + U6
  2594. LJ_chTDAC_UPDATE_DACB = 5126 # UE9 + U3 + U6
  2595. # stream related. Note, Putting to any of these values will stop any running streams.
  2596. LJ_chSTREAM_SCAN_FREQUENCY = 4000
  2597. LJ_chSTREAM_BUFFER_SIZE = 4001
  2598. LJ_chSTREAM_CLOCK_OUTPUT = 4002
  2599. LJ_chSTREAM_EXTERNAL_TRIGGER = 4003
  2600. LJ_chSTREAM_WAIT_MODE = 4004
  2601. LJ_chSTREAM_DISABLE_AUTORECOVERY = 4005 # U3 + U6
  2602. LJ_chSTREAM_SAMPLES_PER_PACKET = 4108
  2603. LJ_chSTREAM_READS_PER_SECOND = 4109
  2604. LJ_chAIN_STREAM_SETTLING_TIME = 4110 # U6
  2605. # readonly stream related
  2606. LJ_chSTREAM_BACKLOG_COMM = 4105
  2607. LJ_chSTREAM_BACKLOG_CONTROL = 4106
  2608. LJ_chSTREAM_BACKLOG_UD = 4107
  2609. # special channel #'s
  2610. LJ_chALL_CHANNELS = -1
  2611. LJ_INVALID_CONSTANT = -999
  2612. # Thermocouple Type constants.
  2613. LJ_ttB = 6001
  2614. LJ_ttE = 6002
  2615. LJ_ttJ = 6003
  2616. LJ_ttK = 6004
  2617. LJ_ttN = 6005
  2618. LJ_ttR = 6006
  2619. LJ_ttS = 6007
  2620. LJ_ttT = 6008
  2621. # other constants:
  2622. # ranges (not all are supported by all devices):
  2623. LJ_rgBIP20V = 1 # -20V to +20V
  2624. LJ_rgBIP10V = 2 # -10V to +10V
  2625. LJ_rgBIP5V = 3 # -5V to +5V
  2626. LJ_rgBIP4V = 4 # -4V to +4V
  2627. LJ_rgBIP2P5V = 5 # -2.5V to +2.5V
  2628. LJ_rgBIP2V = 6 # -2V to +2V
  2629. LJ_rgBIP1P25V = 7 # -1.25V to +1.25V
  2630. LJ_rgBIP1V = 8 # -1V to +1V
  2631. LJ_rgBIPP625V = 9 # -0.625V to +0.625V
  2632. LJ_rgBIPP1V = 10 # -0.1V to +0.1V
  2633. LJ_rgBIPP01V = 11 # -0.01V to +0.01V
  2634. LJ_rgUNI20V = 101 # 0V to +20V
  2635. LJ_rgUNI10V = 102 # 0V to +10V
  2636. LJ_rgUNI5V = 103 # 0V to +5V
  2637. LJ_rgUNI4V = 104 # 0V to +4V
  2638. LJ_rgUNI2P5V = 105 # 0V to +2.5V
  2639. LJ_rgUNI2V = 106 # 0V to +2V
  2640. LJ_rgUNI1P25V = 107 # 0V to +1.25V
  2641. LJ_rgUNI1V = 108 # 0V to +1V
  2642. LJ_rgUNIP625V = 109 # 0V to +0.625V
  2643. LJ_rgUNIP25V = 112 # 0V to +0.25V
  2644. LJ_rgUNIP500V = 110 # 0V to +0.500V
  2645. LJ_rgUNIP3125V = 111 # 0V to +0.3125V
  2646. LJ_rgUNIP025V = 113 # 0V to +0.025V
  2647. LJ_rgUNIP0025V = 114 # 0V to +0.0025V
  2648. # timer modes:
  2649. LJ_tmPWM16 = 0 # 16 bit PWM
  2650. LJ_tmPWM8 = 1 # 8 bit PWM
  2651. LJ_tmRISINGEDGES32 = 2 # 32-bit rising to rising edge measurement
  2652. LJ_tmFALLINGEDGES32 = 3 # 32-bit falling to falling edge measurement
  2653. LJ_tmDUTYCYCLE = 4 # duty cycle measurement
  2654. LJ_tmFIRMCOUNTER = 5 # firmware based rising edge counter
  2655. LJ_tmFIRMCOUNTERDEBOUNCE = 6 # firmware counter with debounce
  2656. LJ_tmFREQOUT = 7 # frequency output
  2657. LJ_tmQUAD = 8 # Quadrature
  2658. LJ_tmTIMERSTOP = 9 # stops another timer after n pulses
  2659. LJ_tmSYSTIMERLOW = 10 # read lower 32-bits of system timer
  2660. LJ_tmSYSTIMERHIGH = 11 # read upper 32-bits of system timer
  2661. LJ_tmRISINGEDGES16 = 12 # 16-bit rising to rising edge measurement
  2662. LJ_tmFALLINGEDGES16 = 13 # 16-bit falling to falling edge measurement
  2663. # timer clocks:
  2664. LJ_tc750KHZ = 0 # UE9: 750 khz
  2665. LJ_tcSYS = 1 # UE9: system clock
  2666. LJ_tc2MHZ = 10 # U3: Hardware Version 1.20 or lower
  2667. LJ_tc6MHZ = 11 # U3: Hardware Version 1.20 or lower
  2668. LJ_tc24MHZ = 12 # U3: Hardware Version 1.20 or lower
  2669. LJ_tc500KHZ_DIV = 13 # U3: Hardware Version 1.20 or lower
  2670. LJ_tc2MHZ_DIV = 14 # U3: Hardware Version 1.20 or lower
  2671. LJ_tc6MHZ_DIV = 15 # U3: Hardware Version 1.20 or lower
  2672. LJ_tc24MHZ_DIV = 16 # U3: Hardware Version 1.20 or lower
  2673. LJ_tc4MHZ = 20 # U3: Hardware Version 1.21 or higher
  2674. LJ_tc12MHZ = 21 # U3: Hardware Version 1.21 or higher
  2675. LJ_tc48MHZ = 22 # U3: Hardware Version 1.21 or higher
  2676. LJ_tc1000KHZ_DIV = 23 # U3: Hardware Version 1.21 or higher
  2677. LJ_tc4MHZ_DIV = 24 # U3: Hardware Version 1.21 or higher
  2678. LJ_tc12MHZ_DIV = 25 # U3: Hardware Version 1.21 or higher
  2679. LJ_tc48MHZ_DIV = 26 # U3: Hardware Version 1.21 or higher
  2680. # stream wait modes
  2681. LJ_swNONE = 1 # no wait, return whatever is available
  2682. LJ_swALL_OR_NONE = 2 # no wait, but if all points requested aren't available, return none.
  2683. LJ_swPUMP = 11 # wait and pump the message pump. Prefered when called from primary thread (if you don't know
  2684. # if you are in the primary thread of your app then you probably are. Do not use in worker
  2685. # secondary threads (i.e. ones without a message pump).
  2686. LJ_swSLEEP = 12 # wait by sleeping (don't do this in the primary thread of your app, or it will temporarily
  2687. # hang) This is usually used in worker secondary threads.
  2688. # BETA CONSTANTS
  2689. # Please note that specific usage of these constants and their values might change
  2690. # SWDT
  2691. # Sets parameters used to control the software watchdog option. The device is only
  2692. # communicated with and updated when LJ_ioSWDT_CONFIG is used with LJ_chSWDT_ENABLE
  2693. # or LJ_chSWDT_DISABLE. Thus, to change a value, you must use LJ_io_PUT_CONFIG
  2694. # with the appropriate channel constant so set the value inside the driver, then call
  2695. # LJ_ioSWDT_CONFIG to enable that change.
  2696. LJ_ioSWDT_CONFIG = 507 # UE9 + U3 + U6 - Use with LJ_chSWDT_ENABLE or LJ_chSWDT_DISABLE
  2697. LJ_ioSWDT_STROKE = 508 # UE9 - Used when SWDT_STRICT_ENABLE is turned on to renew the watchdog.
  2698. LJ_chSWDT_ENABLE = 5200 # UE9 + U3 + U6 - used with LJ_ioSWDT_CONFIG to enable watchdog. Value paramter is number of seconds to trigger
  2699. LJ_chSWDT_DISABLE = 5201 # UE9 + U3 + U6 - used with LJ_ioSWDT_CONFIG to disable watchdog.
  2700. # Used with LJ_io_PUT_CONFIG
  2701. LJ_chSWDT_RESET_DEVICE= 5202 # U3 + U6 - Reset U3 or U6 on watchdog reset. Write only.
  2702. LJ_chSWDT_RESET_COMM = 5203 # UE9 - Reset Comm on watchdog reset. Write only.
  2703. LJ_chSWDT_RESET_CONTROL = 5204 # UE9 - Reset Control on watchdog trigger. Write only.
  2704. LJ_chSWDT_UDPATE_DIOA = 5205 # UE9 + U3 + U6 - Update DIO0 settings after reset. Write only.
  2705. LJ_chSWDT_UPDATE_DIOB = 5206 # UE9 - Update DIO1 settings after reset. Write only.
  2706. LJ_chSWDT_DIOA_CHANNEL = 5207 # UE9 + U3 + U6 - DIO0 channel to be set after reset. Write only.
  2707. LJ_chSWDT_DIOA_STATE = 5208 # UE9 + U3 + U6 - DIO0 state to be set after reset. Write only.
  2708. LJ_chSWDT_DIOB_CHANNEL = 5209 # UE9 - DIO1 channel to be set after reset. Write only.
  2709. LJ_chSWDT_DIOB_STATE = 5210 # UE9 - DIO0 state to be set after reset. Write only.
  2710. LJ_chSWDT_UPDATE_DAC0 = 5211 # UE9 - Update DAC0 settings after reset. Write only.
  2711. LJ_chSWDT_UPDATE_DAC1 = 5212 # UE9 - Update DAC1 settings after reset. Write only.
  2712. LJ_chSWDT_DAC0 = 5213 # UE9 - voltage to set DAC0 at on watchdog reset. Write only.
  2713. LJ_chSWDT_DAC1 = 5214 # UE9 - voltage to set DAC1 at on watchdog reset. Write only.
  2714. LJ_chSWDT_DAC_ENABLE = 5215 # UE9 - Enable DACs on watchdog reset. Default is true. Both DACs are enabled or disabled togeather. Write only.
  2715. LJ_chSWDT_STRICT_ENABLE = 5216 # UE9 - Watchdog will only renew with LJ_ioSWDT_STROKE command.
  2716. LJ_chSWDT_INITIAL_ROLL_TIME = 5217 # UE9 - Watchdog timer for the first cycle when powered on, after watchdog triggers a reset the normal value is used. Set to 0 to disable.
  2717. # END BETA CONSTANTS
  2718. # error codes: These will always be in the range of -1000 to 3999 for labView compatibility (+6000)
  2719. LJE_NOERROR = 0
  2720. LJE_INVALID_CHANNEL_NUMBER = 2 # occurs when a channel that doesn't exist is specified (i.e. DAC #2 on a UE9), or data from streaming is requested on a channel that isn't streaming
  2721. LJE_INVALID_RAW_INOUT_PARAMETER = 3
  2722. LJE_UNABLE_TO_START_STREAM = 4
  2723. LJE_UNABLE_TO_STOP_STREAM = 5
  2724. LJE_NOTHING_TO_STREAM = 6
  2725. LJE_UNABLE_TO_CONFIG_STREAM = 7
  2726. LJE_BUFFER_OVERRUN = 8 # occurs when stream buffer overruns (this is the driver buffer not the hardware buffer). Stream is stopped.
  2727. LJE_STREAM_NOT_RUNNING = 9
  2728. LJE_INVALID_PARAMETER = 10
  2729. LJE_INVALID_STREAM_FREQUENCY = 11
  2730. LJE_INVALID_AIN_RANGE = 12
  2731. LJE_STREAM_CHECKSUM_ERROR = 13 # occurs when a stream packet fails checksum. Stream is stopped
  2732. LJE_STREAM_COMMAND_ERROR = 14 # occurs when a stream packet has invalid command values. Stream is stopped.
  2733. LJE_STREAM_ORDER_ERROR = 15 # occurs when a stream packet is received out of order (typically one is missing). Stream is stopped.
  2734. LJE_AD_PIN_CONFIGURATION_ERROR = 16 # occurs when an analog or digital request was made on a pin that isn't configured for that type of request
  2735. LJE_REQUEST_NOT_PROCESSED = 17 # When a LJE_AD_PIN_CONFIGURATION_ERROR occurs, all other IO requests after the request that caused the error won't be processed. Those requests will return this error.
  2736. # U3 Specific Errors
  2737. LJE_SCRATCH_ERROR = 19
  2738. LJE_DATA_BUFFER_OVERFLOW = 20
  2739. LJE_ADC0_BUFFER_OVERFLOW = 21
  2740. LJE_FUNCTION_INVALID = 22
  2741. LJE_SWDT_TIME_INVALID = 23
  2742. LJE_FLASH_ERROR = 24
  2743. LJE_STREAM_IS_ACTIVE = 25
  2744. LJE_STREAM_TABLE_INVALID = 26
  2745. LJE_STREAM_CONFIG_INVALID = 27
  2746. LJE_STREAM_BAD_TRIGGER_SOURCE = 28
  2747. LJE_STREAM_INVALID_TRIGGER = 30
  2748. LJE_STREAM_ADC0_BUFFER_OVERFLOW = 31
  2749. LJE_STREAM_SAMPLE_NUM_INVALID = 33
  2750. LJE_STREAM_BIPOLAR_GAIN_INVALID = 34
  2751. LJE_STREAM_SCAN_RATE_INVALID = 35
  2752. LJE_TIMER_INVALID_MODE = 36
  2753. LJE_TIMER_QUADRATURE_AB_ERROR = 37
  2754. LJE_TIMER_QUAD_PULSE_SEQUENCE = 38
  2755. LJE_TIMER_BAD_CLOCK_SOURCE = 39
  2756. LJE_TIMER_STREAM_ACTIVE = 40
  2757. LJE_TIMER_PWMSTOP_MODULE_ERROR = 41
  2758. LJE_TIMER_SEQUENCE_ERROR = 42
  2759. LJE_TIMER_SHARING_ERROR = 43
  2760. LJE_TIMER_LINE_SEQUENCE_ERROR = 44
  2761. LJE_EXT_OSC_NOT_STABLE = 45
  2762. LJE_INVALID_POWER_SETTING = 46
  2763. LJE_PLL_NOT_LOCKED = 47
  2764. LJE_INVALID_PIN = 48
  2765. LJE_IOTYPE_SYNCH_ERROR = 49
  2766. LJE_INVALID_OFFSET = 50
  2767. LJE_FEEDBACK_IOTYPE_NOT_VALID = 51
  2768. LJE_CANT_CONFIGURE_PIN_FOR_ANALOG = 67
  2769. LJE_CANT_CONFIGURE_PIN_FOR_DIGITAL = 68
  2770. LJE_TC_PIN_OFFSET_MUST_BE_4_TO_8 = 70
  2771. LJE_INVALID_DIFFERENTIAL_CHANNEL = 71
  2772. LJE_DSP_SIGNAL_OUT_OF_RANGE = 72
  2773. # other errors
  2774. LJE_SHT_CRC = 52
  2775. LJE_SHT_MEASREADY = 53
  2776. LJE_SHT_ACK = 54
  2777. LJE_SHT_SERIAL_RESET = 55
  2778. LJE_SHT_COMMUNICATION = 56
  2779. LJE_AIN_WHILE_STREAMING = 57
  2780. LJE_STREAM_TIMEOUT = 58
  2781. LJE_STREAM_CONTROL_BUFFER_OVERFLOW = 59
  2782. LJE_STREAM_SCAN_OVERLAP = 60
  2783. LJE_FIRMWARE_VERSION_IOTYPE = 61
  2784. LJE_FIRMWARE_VERSION_CHANNEL = 62
  2785. LJE_FIRMWARE_VERSION_VALUE = 63
  2786. LJE_HARDWARE_VERSION_IOTYPE = 64
  2787. LJE_HARDWARE_VERSION_CHANNEL = 65
  2788. LJE_HARDWARE_VERSION_VALUE = 66
  2789. LJE_LJTDAC_ACK_ERROR = 69
  2790. LJE_MIN_GROUP_ERROR = 1000 # all errors above this number will stop all requests, below this number are request level errors.
  2791. LJE_UNKNOWN_ERROR = 1001 # occurs when an unknown error occurs that is caught, but still unknown.
  2792. LJE_INVALID_DEVICE_TYPE = 1002 # occurs when devicetype is not a valid device type
  2793. LJE_INVALID_HANDLE = 1003 # occurs when invalid handle used
  2794. LJE_DEVICE_NOT_OPEN = 1004 # occurs when Open() fails and AppendRead called despite.
  2795. LJE_NO_DATA_AVAILABLE = 1005 # this is cause when GetData() called without calling DoRead(), or when GetData() passed channel that wasn't read
  2796. LJE_NO_MORE_DATA_AVAILABLE = 1006
  2797. LJE_LABJACK_NOT_FOUND = 1007 # occurs when the labjack is not found at the given id or address.
  2798. LJE_COMM_FAILURE = 1008 # occurs when unable to send or receive the correct # of bytes
  2799. LJE_CHECKSUM_ERROR = 1009
  2800. LJE_DEVICE_ALREADY_OPEN = 1010 # occurs when LabJack is already open via USB in another program or process
  2801. LJE_COMM_TIMEOUT = 1011
  2802. LJE_USB_DRIVER_NOT_FOUND = 1012
  2803. LJE_INVALID_CONNECTION_TYPE = 1013
  2804. LJE_INVALID_MODE = 1014
  2805. LJE_DEVICE_NOT_CONNECTED = 1015 # occurs when a LabJack that was opened is no longer connected to the system
  2806. # These errors aren't actually generated by the UD, but could be handy in your code to indicate an event as an error code without
  2807. # conflicting with LabJack error codes
  2808. LJE_DISCONNECT = 2000
  2809. LJE_RECONNECT = 2001
  2810. # and an area for your own codes. This area won't ever be used for LabJack codes.
  2811. LJE_MIN_USER_ERROR = 3000
  2812. LJE_MAX_USER_ERROR = 3999
  2813. # warning are negative
  2814. LJE_DEVICE_NOT_CALIBRATED = -1 # defaults used instead
  2815. LJE_UNABLE_TO_READ_CALDATA = -2 # defaults used instead
  2816. # depreciated constants:
  2817. LJ_ioANALOG_INPUT = 10
  2818. LJ_ioANALOG_OUTPUT = 20 # UE9 + U3
  2819. LJ_ioDIGITAL_BIT_IN = 30 # UE9 + U3
  2820. LJ_ioDIGITAL_PORT_IN = 35 # UE9 + U3
  2821. LJ_ioDIGITAL_BIT_OUT = 40 # UE9 + U3
  2822. LJ_ioDIGITAL_PORT_OUT = 45 # UE9 + U3
  2823. LJ_ioCOUNTER = 50 # UE9 + U3
  2824. LJ_ioTIMER = 60 # UE9 + U3
  2825. LJ_ioPUT_COUNTER_MODE = 2010 # UE9
  2826. LJ_ioGET_COUNTER_MODE = 2011 # UE9
  2827. LJ_ioGET_TIMER_VALUE = 2007 # UE9
  2828. LJ_ioCYCLE_PORT = 102 # UE9
  2829. LJ_chTIMER_CLOCK_CONFIG = 1001 # UE9 + U3
  2830. LJ_ioPUT_CAL_CONSTANTS = 400
  2831. LJ_ioGET_CAL_CONSTANTS = 401
  2832. LJ_ioPUT_USER_MEM = 402
  2833. LJ_ioGET_USER_MEM = 403
  2834. LJ_ioPUT_USB_STRINGS = 404
  2835. LJ_ioGET_USB_STRINGS = 405
  2836. LJ_ioSHT_DATA_CHANNEL = 501 # UE9 + U3
  2837. LJ_ioSHT_CLOCK_CHANNEL = 502 # UE9 + U3
  2838. LJ_chI2C_ADDRESS = 5108 # UE9 + U3
  2839. LJ_chASYNCH_CONFIG = 5116 # UE9 + U3
  2840. LJ_rgUNIP500V = 110 # 0V to +0.500V
  2841. LJ_ioENABLE_POS_PULLDOWN = 2018 # U6
  2842. LJ_ioENABLE_NEG_PULLDOWN = 2019 # U6
  2843. LJ_rgAUTO = 0