-
Notifications
You must be signed in to change notification settings - Fork 82
Expand file tree
/
Copy pathLabJackPython.py
More file actions
3822 lines (3109 loc) · 139 KB
/
Copy pathLabJackPython.py
File metadata and controls
3822 lines (3109 loc) · 139 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Multi-Platform Python wrapper that implements functions from the LabJack
Windows UD Driver, and the Exodriver.
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.
A typical user should start with their device's module, such as u3.py.
"""
# We use the 'with' keyword to manage the thread-safe device lock.
# It's built-in on 2.6; 2.5 requires an import.
from __future__ import with_statement
import atexit # For auto-closing devices
import socket
import ctypes # import after socket or cygwin crashes "Aborted (core dump)"
import errno
import sys
import threading # For a thread-safe device lock
import logging
from struct import pack, unpack
import Modbus
LABJACKPYTHON_VERSION = "2.0.5"
__version__ = LABJACKPYTHON_VERSION
SOCKET_TIMEOUT = 3
LJSOCKET_TIMEOUT = 62
BROADCAST_SOCKET_TIMEOUT = 1
MAX_USB_PACKET_LENGTH = 64
NUMBER_OF_UNIQUE_LABJACK_PRODUCT_IDS = 4
_os_name = "" # Set to "nt" or "posix" in _loadLibrary.
_use_ptr = True # Set to True or False in _loadLibrary. Indicates whether to use
# the Ptr version of certain UD calls or not. Windows only.
_use_py2 = sys.version_info < (3, 0) # Indicates to use Python 2.x or
# Python 3+ when needed.
class LabJackException(Exception):
"""Custom Exception meant for dealing specifically with LabJack Exceptions.
Error codes are either going to be a LabJackUD error code or a -1. The -1
implies a Python wrapper specific error.
WINDOWS ONLY
If errorString is not specified then errorString is set by errorCode.
"""
def __init__(self, ec = 0, errorString = ''):
self.errorCode = ec
self.errorString = errorString
if not self.errorString:
try:
pString = ctypes.create_string_buffer(256)
staticLib.ErrorToString(ctypes.c_long(self.errorCode), ctypes.byref(pString))
self.errorString = pString.value.decode("ascii").split("\0", 1)[0]
except:
self.errorString = str(self.errorCode)
def __str__(self):
return self.errorString
class LowlevelErrorException(LabJackException):
"""Raised when a low-level command raises an error."""
pass
class NullHandleException(LabJackException):
"""Raised when the return value of OpenDevice is null."""
def __init__(self, info=None):
if info is None:
# Default additional information message.
info = "Please check that the device you are trying to open is connected."
else:
# Set additional information message.
info = str(info)
self.errorString = "Couldn't open device. " + info
def errcheck(ret, func, args):
"""
Whenever a function is called through ctypes, the return value is passed to
this function to be checked for errors.
Support for errno didn't come until 2.6, so Python 2.5 people should
upgrade.
"""
if ret == -1:
try:
ec = ctypes.get_errno()
raise LabJackException(ec, "Exodriver returned error number %s" % ec)
except AttributeError:
raise LabJackException(-1, "Exodriver returned an error, but LabJackPython is unable to read the error code. Upgrade to Python 2.6 for this functionality.")
else:
return ret
def _loadLinuxSo():
"""
Attempts to load the liblabjackusb.so for Linux.
"""
l = ctypes.CDLL("liblabjackusb.so", use_errno=True)
l.LJUSB_StreamTO.errcheck = errcheck
l.LJUSB_Read.errcheck = errcheck
return l
def _loadMacDylib():
"""
Attempts to load the liblabjackusb.dylib for Mac OS X.
"""
try:
l = ctypes.CDLL("liblabjackusb.dylib", use_errno=True)
except:
#Try to load with full path.
l = ctypes.CDLL("/usr/local/lib/liblabjackusb.dylib", use_errno=True)
l.LJUSB_StreamTO.errcheck = errcheck
l.LJUSB_Read.errcheck = errcheck
return l
def _loadLibrary():
"""_loadLibrary()
Returns a ctypes dll pointer to the library.
"""
global _os_name
global _use_ptr
_os_name = "nt"
try:
wlib = None
if sys.platform.startswith("win32"):
#Windows detected
wlib = ctypes.WinDLL("labjackud.dll")
if sys.platform.startswith("cygwin"):
#Cygwin detected. WinDLL not available, but CDLL seems to work.
wlib = ctypes.CDLL("labjackud.dll")
if wlib is not None:
#eGetPtr may not be available on the UD driver version installed.
_use_ptr = hasattr(wlib, "eGetPtr")
return wlib
except Exception:
e = sys.exc_info()[1]
raise LabJackException("Could not load labjackud driver. Ethernet connectivity availability only.\n\n The error was: %s" % e)
_os_name = "posix"
addStr = "Exodriver"
try:
if sys.platform.startswith("linux"):
#Linux detected
addStr = "Linux SO"
return _loadLinuxSo()
if sys.platform.startswith("darwin"):
#Mac detected
addStr = "Mac Dylib"
return _loadMacDylib()
#Other OS? Just try to load the Exodriver like a Linux SO
addStr = "Other SO"
return _loadLinuxSo()
except OSError:
e = sys.exc_info()[1]
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)
except Exception:
e = sys.exc_info()[1]
raise LabJackException("Could not load the %s for some reason other than it not being installed. Ethernet connectivity only.\n\n The error was: %s" % (addStr, e))
try:
staticLib = _loadLibrary()
except LabJackException:
e = sys.exc_info()[1]
print("%s: %s" % (type(e), e))
staticLib = None
class Device(object):
"""Device(handle, localId = None, serialNumber = None, ipAddress = "", devType = None)
Creates a simple 0 with the following functions:
write(writeBuffer) -- Writes a buffer.
writeRegister(addr, value) -- Writes a value to a modbus register
read(numBytes) -- Reads until a packet is received.
readRegister(addr, numReg = None, format = None) -- Reads a modbus register.
ping() -- Pings the device. Returns true if communication worked.
close() -- Closes the device.
reset() -- Resets the device.
"""
def __init__(self, handle, localId = None, serialNumber = None, ipAddress = "", devType = None):
# Not saving the handle as a void* causes many problems on 64-bit machines.
if isinstance(handle, int):
self.handle = ctypes.c_void_p(handle)
else:
self.handle = handle
self.localId = localId
self.serialNumber = serialNumber
self.ipAddress = ipAddress
self.devType = devType
self.debug = False
self.streamConfiged = False
self.streamStarted = False
self.streamPacketOffset = 0
self._autoCloseSetup = False
self.modbusPrependZeros = True
self.deviceLock = threading.Lock()
self.deviceName = "LabJack"
def _writeToLJSocketHandle(self, writeBuffer, modbus):
#if modbus is True and self.modbusPrependZeros:
# writeBuffer = [ 0, 0 ] + writeBuffer
packFormat = "B" * len(writeBuffer)
tempString = pack(packFormat, *writeBuffer)
if modbus:
self.handle.modbusSocket.send(tempString)
else:
self.handle.crSocket.send(tempString)
return writeBuffer
def _writeToUE9TCPHandle(self, writeBuffer, modbus):
packFormat = "B" * len(writeBuffer)
tempString = pack(packFormat, *writeBuffer)
if modbus is True:
if self.handle.modbus is None:
raise LabJackException("Modbus port is not available. Please upgrade to UE9 Comm firmware 1.43 or higher.")
self.handle.modbus.send(tempString)
else:
self.handle.data.send(tempString)
return writeBuffer
def _writeToExodriver(self, writeBuffer, modbus):
if modbus is True and self.modbusPrependZeros:
writeBuffer = [ 0, 0 ] + writeBuffer
newA = (ctypes.c_byte*len(writeBuffer))(0)
for i in range(len(writeBuffer)):
newA[i] = ctypes.c_byte(writeBuffer[i])
writeBytes = staticLib.LJUSB_Write(self.handle, ctypes.byref(newA), len(writeBuffer))
if writeBytes != len(writeBuffer):
raise LabJackException( "Could only write %s of %s bytes." % (writeBytes, len(writeBuffer) ) )
return writeBuffer
def _writeToUDDriver(self, writeBuffer, modbus):
if modbus is True and self.devType == 9:
dataWords = len(writeBuffer)
writeBuffer = [0, 0xF8, 0, 0x07, 0, 0] + writeBuffer # Modbus low-level function
if dataWords % 2 != 0:
dataWords = (dataWords+1) // 2
writeBuffer.append(0)
else:
dataWords = dataWords // 2
writeBuffer[2] = dataWords
setChecksum(writeBuffer)
elif modbus is True and self.modbusPrependZeros:
writeBuffer = [0, 0] + writeBuffer
eGetRaw(self.handle, LJ_ioRAW_OUT, 0, len(writeBuffer), writeBuffer)
return writeBuffer
def _debugprint(self, msg):
"""Conditionally output msg.
If self.debug is a logging.Logger object, send the msg to it with
DEBUG priority. Otherwise, if self.debug is any truthy, just print
it to stdout.
"""
if self.debug:
if isinstance(self.debug, logging.Logger):
self.debug.debug(msg)
else:
print(msg)
def write(self, writeBuffer, modbus = False, checksum = True):
"""write([writeBuffer], modbus = False)
Writes the data contained in writeBuffer to the device. writeBuffer must be a list of
byte values.
"""
if self.handle is None:
raise LabJackException("The device handle is None.")
if checksum:
setChecksum(writeBuffer)
if isinstance(self.handle, LJSocketHandle):
wb = self._writeToLJSocketHandle(writeBuffer, modbus)
elif isinstance(self.handle, UE9TCPHandle):
wb = self._writeToUE9TCPHandle(writeBuffer, modbus)
else:
if _os_name == 'posix':
wb = self._writeToExodriver(writeBuffer, modbus)
elif _os_name == 'nt':
wb = self._writeToUDDriver(writeBuffer, modbus)
self._debugprint("Sent: " + hexWithoutQuotes(wb))
def read(self, numBytes, stream = False, modbus = False):
"""read(numBytes, stream = False, modbus = False)
Blocking read until a packet is received. Returns a list of
byte values when modbus is False. When modbus is true, returns
a string in Python 2.x, or a bytes object in Python 3+.
"""
if self.handle is None:
raise LabJackException("The device handle is None.")
result = []
if isinstance(self.handle, LJSocketHandle):
result = self._readFromLJSocketHandle(numBytes, modbus, stream)
elif isinstance(self.handle, UE9TCPHandle):
result = self._readFromUE9TCPHandle(numBytes, stream, modbus)
else:
if _os_name == 'posix':
result = self._readFromExodriver(numBytes, stream, modbus)
elif _os_name == 'nt':
result = self._readFromUDDriver(numBytes, stream, modbus)
return result
def _readFromLJSocketHandle(self, numBytes, modbus, spont = False):
"""
Reads from LJSocket. Returns the result as a list.
"""
if modbus:
rcvString = self.handle.modbusSocket.recv(numBytes)
elif spont:
rcvString = self.handle.spontSocket.recv(numBytes)
else:
rcvString = self.handle.crSocket.recv(numBytes)
readBytes = len(rcvString)
packFormat = "B" * readBytes
rcvDataBuff = unpack(packFormat, rcvString)
return list(rcvDataBuff)
def _readFromUE9TCPHandle(self, numBytes, stream, modbus):
if stream is True:
rcvString = self.handle.stream.recv(numBytes)
return rcvString
else:
if modbus is True:
if self.handle.modbus is None:
raise LabJackException("Modbus port is not available. Please upgrade to UE9 Comm firmware 1.43 or higher.")
rcvString = self.handle.modbus.recv(numBytes)
else:
rcvString = self.handle.data.recv(numBytes)
readBytes = len(rcvString)
packFormat = "B" * readBytes
rcvDataBuff = unpack(packFormat, rcvString)
return list(rcvDataBuff)
def _readFromExodriver(self, numBytes, stream, modbus):
newA = (ctypes.c_byte*numBytes)()
if stream:
readBytes = staticLib.LJUSB_StreamTO(self.handle, ctypes.byref(newA), numBytes, 1500)
if readBytes == 0:
return ''
# return the byte string in stream mode
return pack('b' * readBytes, *newA)
else:
readBytes = staticLib.LJUSB_Read(self.handle, ctypes.byref(newA), numBytes)
# return a list of integers in command/response mode
return [(newA[i] & 0xff) for i in range(readBytes)]
def _readFromUDDriver(self, numBytes, stream, modbus):
if modbus is True and self.devType == 9:
tempBuff = [0] * (8 + numBytes + numBytes%2)
eGetBuff = list()
eGetBuff = eGetRaw(self.handle, LJ_ioRAW_IN, 0, len(tempBuff), tempBuff)[1]
# Parse the Modbus response out (response is the Modbus extended
# low-level function)
retBuff = list()
if len(eGetBuff) >= 9 and eGetBuff[1] == 0xF8 and eGetBuff[3] == 0x07:
# Figuring out the length of the Modbus response
mbSize = len(eGetBuff) - 8
if len(eGetBuff) >= 14:
mbSize = min(mbSize, eGetBuff[13] + 6)
i = min(mbSize, numBytes)
i = max(i, 0)
retBuff = eGetBuff[8:8+i] # Getting the response only
return retBuff
tempBuff = [0] * numBytes
if stream:
return eGetRaw(self.handle, LJ_ioRAW_IN, 1, numBytes, tempBuff)[1]
return eGetRaw(self.handle, LJ_ioRAW_IN, 0, numBytes, tempBuff)[1]
def readRegister(self, addr, numReg = None, format = None, unitId = None):
"""Reads a specific register from the device and returns the value.
Requires Modbus.py
readHoldingRegister(addr, numReg = None, format = None)
addr: The address you would like to read
numReg: Number of consecutive addresses you would like to read
format: The unpack format of the returned value ( '>f' or '>I')
Modbus is supported for UE9s over USB from Comm Firmware 1.50 and above.
"""
pkt, numBytes = self._buildReadRegisterPacket(addr, numReg, unitId)
response = self._modbusWriteRead(pkt, numBytes)
return self._parseReadRegisterResponse(response, numBytes, addr, format, numReg)
def _buildReadRegisterPacket(self, addr, numReg, unitId):
"""
self._buildReadRegisterPacket(addr, numReg)
Builds a raw modbus "Read Register" packet to be written to a device
Returns a tuple:
(<Packet as a list>, <number of bytes to read>)
"""
# Calculates the number of registers for that request, or if numReg is
# specified, checks that it is a valid number.
numReg = Modbus.calcNumberOfRegisters(addr, numReg = numReg)
pkt = toList(Modbus.readHoldingRegistersRequest(addr, numReg = numReg, unitId = unitId))
numBytes = 9 + (2 * int(numReg))
return (pkt, numBytes)
def _parseReadRegisterResponse(self, response, numBytes, addr, format, numReg = None):
"""
self._parseReadRegisterReponse(reponse, numBytes, addr, format)
Takes a "Read Register" response and converts it to a value
Returns the value.
"""
if len(response) != numBytes:
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))
if isinstance(response, list):
packFormat = ">" + "B" * numBytes
response = pack(packFormat, *response)
if format is None:
format = Modbus.calcFormat(addr, numReg)
value = Modbus.readHoldingRegistersResponse(response, payloadFormat=format)
return value
def writeRegister(self, addr, value, unitId = None):
"""
Writes a value to a register. Returns the value to be written, if successful.
Requires Modbus.py
writeRegister(self, addr, value)
addr: The address you want to write to.
value: The value, or list of values, you want to write.
If you cannot write to that register, a LabJackException is raised.
Modbus is not supported for UE9s over USB. If you try it, a LabJackException is raised.
"""
pkt, numBytes = self._buildWriteRegisterPacket(addr, value, unitId)
response = self._modbusWriteRead(pkt, numBytes)
return self._parseWriteRegisterResponse(response, pkt, value)
def _buildWriteRegisterPacket(self, addr, value, unitId):
"""
self._buildWriteRegisterPacket(addr, value)
Builds a raw modbus "Write Register" packet to be written to a device.
Returns a tuple:
(<Packet as a list>, <number of bytes to read>)
"""
if isinstance(value, list):
return self._buildWriteMultipleRegisters(addr, value, unitId)
fmt = Modbus.calcFormat(addr)
if fmt != '>H':
return self._buildWriteFloatToRegister(addr, value, unitId, fmt)
request = toList(Modbus.writeRegisterRequest(addr, value, unitId))
numBytes = 12
return request, numBytes
def _buildWriteFloatToRegister(self, addr, value, unitId, fmt = '>f'):
if not isinstance(value, int) and not isinstance(value, float):
raise TypeError("Value must be a float or int.")
# Function, Address, Num Regs, Byte count, Data
payload = pack('>BHHB', 0x10, addr, 0x02, 0x04) + pack(fmt, value)
request = Modbus._buildHeaderBytes(length = len(payload)+1, unitId = unitId)
request += payload
request = toList(request)
numBytes = 12
return (request, numBytes)
def _buildWriteMultipleRegisters(self, startAddr, values, unitId = None):
request = toList(Modbus.writeRegistersRequest(startAddr, values, unitId))
numBytes = 12
return (request, numBytes)
def _parseWriteRegisterResponse(self, response, request, value):
response = list(response)
if request[2] != 0 and request[3] != 0:
protoID = (request[2] << 8) + request[3]
raise Modbus.ModbusException("Got an unexpected protocol ID: %s (expected 0). Please make sure that you have the latest firmware. UE9s need Comm Firmware of 1.50 or greater.\n\nThe packet you received: %s" % (protoID, hexWithoutQuotes(response)))
if request[7] != response[7]:
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)))
return value
def setDIOState(self, IOnum, state):
value = (int(state) & 0x01)
self.writeRegister(6000+IOnum, value)
return True
def _modbusWriteRead(self, request, numBytes):
with self.deviceLock:
self.write(request, modbus = True, checksum = False)
try:
result = self.read(numBytes, modbus = True)
self._debugprint("Response: " + hexWithoutQuotes(result))
return result
except LabJackException:
self.write(request, modbus = True, checksum = False)
result = self.read(numBytes, modbus = True)
self._debugprint("Response: " + hexWithoutQuotes(result))
return result
def _checkCommandBytes(self, results, commandBytes):
"""
Checks all the stuff from a command
"""
size = len(commandBytes)
if len(results) == 0:
raise LabJackException("Got a zero length packet.")
elif results[0] == 0xB8 and results[1] == 0xB8:
raise LabJackException("Device detected a bad checksum.")
elif results[1:(size+1)] != commandBytes:
raise LabJackException("Got incorrect command bytes.\nExpected: %s\nGot: %s\nFull packet: %s" % (hexWithoutQuotes(commandBytes), hexWithoutQuotes(results[1:(size+1)]), hexWithoutQuotes(results)))
elif not verifyChecksum(results):
raise LabJackException("Checksum was incorrect.")
elif results[6] != 0:
raise LowlevelErrorException(results[6], "\nThe %s returned an error:\n %s" % (self.deviceName , lowlevelErrorToString(results[6])) )
def _writeRead(self, command, readLen, commandBytes, checkBytes = True, stream=False, checksum = True):
# Acquire the device lock.
with self.deviceLock:
self.write(command, checksum = checksum)
result = self.read(readLen, stream=False)
self._debugprint("Response: " + hexWithoutQuotes(result))
if checkBytes:
self._checkCommandBytes(result, commandBytes)
return result
def ping(self):
try:
if self.devType == LJ_dtUE9:
writeBuffer = [0x70, 0x70]
self.write(writeBuffer)
try:
self.read(2)
except LabJackException:
self.write(writeBuffer)
self.read(2)
return True
if self.devType == LJ_dtU3:
writeBuffer = [0, 0xf8, 0x01, 0x2a, 0, 0, 0, 0]
writeBuffer = setChecksum(writeBuffer)
self.write(writeBuffer)
self.read(40)
return True
return False
except Exception:
e = sys.exc_info()[1]
print(e)
return False
def open(self, devType, Ethernet=False, firstFound = True, serial = None, localId = None, devNumber = None, ipAddress = None, handleOnly = False, LJSocket = None):
"""
Device.open(devType, Ethernet=False, firstFound = True, serial = None, localId = None, devNumber = None, ipAddress = None, handleOnly = False, LJSocket = None)
Open a device of type devType.
"""
if self.handle is not None:
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.")
ct = LJ_ctUSB
if Ethernet:
ct = LJ_ctETHERNET
if LJSocket is not None:
ct = LJ_ctLJSOCKET
d = None
if devNumber:
d = openLabJack(devType, ct, firstFound = False, devNumber = devNumber, handleOnly = handleOnly, LJSocket = LJSocket)
elif serial:
d = openLabJack(devType, ct, firstFound = False, pAddress = serial, handleOnly = handleOnly, LJSocket = LJSocket)
elif localId:
d = openLabJack(devType, ct, firstFound = False, pAddress = localId, handleOnly = handleOnly, LJSocket = LJSocket)
elif ipAddress:
d = openLabJack(devType, ct, firstFound = False, pAddress = ipAddress, handleOnly = handleOnly, LJSocket = LJSocket)
elif LJSocket:
d = openLabJack(devType, ct, handleOnly = handleOnly, LJSocket = LJSocket)
elif firstFound:
d = openLabJack(devType, ct, firstFound = True, handleOnly = handleOnly, LJSocket = LJSocket)
else:
raise LabJackException("You must use first found, or give a localId, devNumber, or IP Address")
self.handle = d.handle
if not handleOnly:
self._loadChangedIntoSelf(d)
self._registerAtExitClose()
def _loadChangedIntoSelf(self, d):
for key, value in d.changed.items():
self.__setattr__(key, value)
def _registerAtExitClose(self):
if not self._autoCloseSetup:
# Only need to register auto-close once per device.
atexit.register(self.close)
self._autoCloseSetup = True
def close(self):
"""
close()
Closes the device.
On Windows, this method only sets the device handle to None but does
not close the device. Instead use the Close function from the
LabJackPython module which closes all devices in the program, and is
the only device close function in the Windows UD driver.
On Linux and Mac, this function MUST be performed when finished with a
device. The reason for this close is so there cannot be more than one
program with a given device open at a time. If a device is not closed
before the program is finished it may still be held open and unable to
be used by other programs until properly closed.
For Windows, Linux, and Mac
"""
if isinstance(self.handle, UE9TCPHandle) or isinstance(self.handle, LJSocketHandle):
self.handle.close()
elif _os_name == 'posix':
staticLib.LJUSB_CloseDevice(self.handle)
self.handle = None
def reset(self):
"""
Reset the LabJack device.
For Windows, Linux, and Mac
Sample Usage:
>>> d = ue9.UE9()
>>> d.reset()
@type None
@param Function takes no arguments
@rtype: None
@return: Function returns nothing.
@raise LabJackException:
"""
if _os_name == 'nt':
ec = staticLib.ResetLabJack(self.handle)
if ec != 0: raise LabJackException(ec)
elif _os_name == 'posix':
sndDataBuff = [0] * 4
#Make the reset packet
sndDataBuff[0] = 0x9C #Checksum
sndDataBuff[1] = 0x99
sndDataBuff[2] = 0x03
try:
self._writeRead(sndDataBuff, 4, [], False, False, False)
except Exception:
e = sys.exc_info()[1]
raise LabJackException(0, "Unable to reset labjack: %s" % str(e))
def breakupPackets(self, packets, numBytesPerPacket):
"""
Name: Device.breakupPackets
Args: packets, a string or list of packets
numBytesPerPacket, how big each packe is
Desc: This function will break up a list into smaller chunks and return
each chunk one at a time.
>>> l = range(15)
>>> for packet in d.breakupPackets(l, 5):
... print(packet)
[ 0, 1, 2, 3, 4 ]
[ 5, 6, 7, 8, 9 ]
[ 10, 11, 12, 13, 14]
"""
start, end = 0, numBytesPerPacket
while end <= len(packets):
yield packets[start:end]
start, end = end, end + numBytesPerPacket
def samplesFromPacket(self, packet):
"""
Name: Device.samplesFromPacket
Args: packet, a packet of stream data
Desc: This function breaks a packet into all the two byte samples it
contains and returns them one at a time.
>>> packet = range(16) # fake packet with 1 sample in it
>>> for sample in d.samplesFromPacket(packet):
... print(sample)
[ 12, 13 ]
"""
HEADER_SIZE = 12
FOOTER_SIZE = 2
BYTES_PER_PACKET = 2
l = packet[HEADER_SIZE:-FOOTER_SIZE]
for i in range(0, len(l), BYTES_PER_PACKET):
yield l[i:i+BYTES_PER_PACKET]
def streamStart(self):
"""
Name: Device.streamStart()
Args: None
Desc: Starts streaming on the device.
Note: You must call streamConfig() before calling this function.
"""
if not self.streamConfiged:
raise LabJackException("Stream must be configured before it can be started.")
if self.streamStarted:
raise LabJackException("Stream already started.")
command = [0xA8, 0xA8]
results = self._writeRead(command, 4, [], False, False, False)
if results[2] != 0:
raise LowlevelErrorException(results[2], "StreamStart returned an error:\n %s" % lowlevelErrorToString(results[2]))
self.streamPacketOffset = 0
self.streamStarted = True
def streamData(self, convert=True):
"""
Name: Device.streamData()
Args: convert, should the packets be converted as they are read.
set to False to get much faster speeds, but you will
have to process the results later.
Desc: Reads stream data from a LabJack device. See our stream example
to get an idea of how this function should be called. The return
value of streamData is a dictionary with the following keys:
* errors: The number of errors in this block.
* numPackets: The number of USB packets collected to return this
block.
* missed: The number of readings that were missed because of
buffer overflow on the LabJack.
* firstPacket: The PacketCounter value in the first USB packet.
* result: The raw bytes returned from read(). The only way to get
data if called with convert = False. In Python 2 this
is a string, and in Python 3+ is a bytes object.
* AINi, where i is an entry in the passed in PChannels. If called
with convert = True, this is a list of all the readings
in this block.
Note: You must start the stream by calling streamStart() before calling
this function.
"""
if not self.streamStarted:
raise LabJackException("Please start streaming before reading.")
numBytes = 14 + (self.streamSamplesPerPacket * 2)
while True:
result = self.read(numBytes * self.packetsPerRequest, stream = True)
if len(result) == 0:
yield None
continue
numPackets = len(result) // numBytes
errors = 0
missed = 0
firstPacket = streamByteToInt(result[10])
for i in range(numPackets):
e = streamByteToInt(result[11+(i*numBytes)])
if e != 0:
errors += 1
if e != 60 and e != 59:
self._debugprint(e)
if e == 60:
missed += unpack('<I', result[6+(i*numBytes):10+(i*numBytes)])[0]
returnDict = dict(numPackets = numPackets, result = result, errors = errors, missed = missed, firstPacket = firstPacket)
if convert:
returnDict.update(self.processStreamData(result, numBytes = numBytes))
yield returnDict
def streamStop(self):
"""
Name: Device.streamStop()
Args: None
Desc: Stops streaming on the device.
"""
command = [0xB0, 0xB0]
results = self._writeRead(command, 4, [], False, False, False)
if results[2] != 0:
raise LowlevelErrorException(results[2], "StreamStop returned an error:\n %s" % lowlevelErrorToString(results[2]))
self.streamStarted = False
def getName(self):
"""
Name: Device.getName()
Args: None
Desc: Returns the name of a device.
Always returns a unicode string.
Works as of the following firmware versions:
U6 - 1.00
U3 - 1.22
UE9 - 2.00
>>> d = u3.U3()
>>> d.open()
>>> d.getName()
u'My LabJack U3'
"""
name = list(self.readRegister(58000, format='B'*48, numReg = 24))
if name[1] == 3:
# Old style string
name = "My %s" % self.deviceName
self._debugprint("Old UTF-16 name detected, replacing with %s" % name)
self.setName(name)
if _use_py2:
name = name.decode("UTF-8")
else:
try:
end = name.index(0x00)
name = pack("B"*end, *name[:end]).decode("UTF-8")
except ValueError:
name = "My %s" % self.deviceName
self._debugprint("Invalid name detected, replacing with %s" % name)
self.setName(name)
if _use_py2:
name = name.decode("UTF-8")
return name
def setName(self, name = "My LabJack U3"):
"""
Name: Device.setName(name = "My LabJack U3")
Args: name, the name you'd like to assign the the U3
Desc: Writes a new name to the device.
Names a limited to 30 characters or less.
Works as of the following firmware versions:
U6 - 1.00
U3 - 1.22
UE9 - 2.00
>>> d = u3.U3()
>>> d.open()
>>> d.getName()
u'My LabJack U3'
>>> d.setName("Johann")
>>> d.getName()
u'Johann'
"""
strLen = len(name)
if strLen > 47:
raise LabJackException("The name is too long, must be less than 48 characters.")
newname = name.encode('UTF-8')
bl = list(unpack("B"*strLen, newname)) + [0x00]
strLen += 1
if strLen%2 != 0:
bl = bl + [0x00]
strLen += 1
bl = unpack(">"+"H"*(strLen//2), pack("B" * strLen, *bl))
self.writeRegister(58000, list(bl))
name = property(getName, setName)
def setDefaults(self, SetToFactoryDefaults = False):
"""
Name: Device.setDefaults(SetToFactoryDefaults = False)
Args: SetToFactoryDefaults, set to True reset to factory defaults.
Desc: Executing this function causes the current or last used values
(or the factory defaults) to be stored in flash as the power-up
defaults.
>>> myU6 = U6()
>>> myU6.setDefaults()
"""
command = [ 0 ] * 8
#command[0] = Checksum8
command[1] = 0xF8
command[2] = 0x01
command[3] = 0x0E
#command[4] = Checksum16 (LSB)
#command[5] = Checksum16 (MSB)
command[6] = 0xBA
command[7] = 0x26
if SetToFactoryDefaults:
command[6] = 0x82
command[7] = 0xC7
self._writeRead(command, 8, [ 0xF8, 0x01, 0x0E ] )
def setToFactoryDefaults(self):
return self.setDefaults(SetToFactoryDefaults = True)
validDefaultBlocks = range(8)
def readDefaults(self, BlockNum, ReadCurrent = False):
"""
Name: Device.readDefaults(BlockNum)
Args: BlockNum, which block to read. Must be 0-7.
ReadCurrent, True = read current configuration
Desc: Reads the power-up defaults from flash.
>>> myU6 = U6()
>>> myU6.readDefaults(0)
[ 0, 0, ... , 0]
"""
if BlockNum not in self.validDefaultBlocks:
raise LabJackException("Defaults must be in range 0-7")
byte7 = (int(bool(ReadCurrent)) << 7) + BlockNum
command = [ 0, 0xF8, 0x01, 0x0E, 0, 0, 0, byte7 ]
result = self._writeRead(command, 40, [ 0xF8, 0x11, 0x0E ])
return result[8:]
def readCurrent(self, BlockNum):
self.readDefaults(BlockNum, ReadCurrent = True)
def loadGenericDevice(self, device):
""" Take a generic Device object, and loads it into the current object.
The generic Device is consumed in the process.
"""
self.handle = device.handle
self._loadChangedIntoSelf(device)
self._registerAtExitClose()
device = None
# --------------------- BEGIN LabJackPython ---------------------------------
def setChecksum(command):
"""Returns a command with checksums places in the proper locations
For Windows, Mac, and Linux
Sample Usage:
>>> from LabJackPython import setChecksum
>>> command = [0] * 12
>>> command[1] = 0xf8
>>> command[2] = 0x03