def write_vk(self, vk_code): # {{{ logging.debug('virtual key code' + str(vk_code)) li = INPUT_RECORD * 1 # create keyboard input ke = KEY_EVENT_RECORD() ke.uChar.UnicodeChar = u(chr(0)) ke.wVirtualKeyCode = ctypes.c_short(int(vk_code)) ke.wVirtualScanCode = ctypes.c_short(ctypes.windll.user32.MapVirtualKeyW(int(vk_code), 0)) ke.bKeyDown = ctypes.c_byte(1) ke.wRepeatCount = ctypes.c_short(1) # set enhanced key mode for arrow keys if vk_code in CONQUE_WINDOWS_VK_ENHANCED: logging.debug('enhanced key!') ke.dwControlKeyState = ENHANCED_KEY kc = INPUT_RECORD(KEY_EVENT) kc.Event.KeyEvent = ke list_input = li(kc) # write input array events_written = ctypes.c_int() res = ctypes.windll.kernel32.WriteConsoleInputW(self.stdin, list_input, 1, ctypes.byref(events_written)) logging.debug('bar') logging.debug('events written ' + str(events_written)) logging.debug(str(res)) logging.debug(str(ctypes.GetLastError())) logging.debug(str(ctypes.FormatError(ctypes.GetLastError())))
def addc(self, a, b, c): if 0 == self.pc_state.P.get_D(): r = ctypes.c_short(a + b + c).value rc = ctypes.c_byte(a + b + c).value self.pc_state.P.set_N((0,1)[0x80 == (rc & 0x80)]) self.pc_state.P.set_Z((0,1)[rc == 0x0]) self.pc_state.P.set_V((0,1)[rc != r]) # Overflow r = ((a & 0xFF) + (b & 0xFF) + c) & 0xFFFF self.pc_state.P.set_C((0,1)[0x100 == (r & 0x100)]) result = (a + b + c) elif 1 == self.pc_state.P.get_D(): # Decimal Addition # FIXME need to fix flags # r = ctypes.c_short(((a >> 4) & 0xF)* 10+ ((a & 0xF) %10) + ((b>>4) & 0xF)* 10 + ((b & 0xF) %10) + c).value rc = ctypes.c_byte(a + b + c).value # ???? TODO self.pc_state.P.set_N((0,1)[r < 0]) self.pc_state.P.set_Z((0,1)[rc == 0x0]) # self.pc_state.P.V = (rc != r) ? 1:0; # Overflow self.pc_state.P.set_C((0,1)[(r > 99) or (r < 0)]) result = ((((int(r/10) % 10) << 4) & 0xf0) + (r%10)) return result & 0xFF
def getBearing(): """ Read I2C compass and compute for the heading vector :return: Bearing in degrees """ # Get bytes from the I2C compass xu = smb.read_byte_data(0x1e, 0x03) xl = smb.read_byte_data(0x1e, 0x04) zu = smb.read_byte_data(0x1e, 0x05) zl = smb.read_byte_data(0x1e, 0x06) yu = smb.read_byte_data(0x1e, 0x07) yl = smb.read_byte_data(0x1e, 0x08) # Bit shift higher bytes and add lower bytes to get value x = (xu << 8) + xl y = (yu << 8) + yl z = (zu << 8) + zl # Convert bytes to signed integer (Convert from two's compliment) x = ctypes.c_short(x).value y = ctypes.c_short(y).value z = ctypes.c_short(z).value # Compute for vector's angle using its component t = math.atan2(y, z) * (180 / math.pi) t += 180 return {"x": x, "y": y, "z": z, "t": t}
def subc(self, a, b, c): if 0 == self.pc_state.P.get_D(): r = ctypes.c_short(ctypes.c_byte(a).value - ctypes.c_byte(b).value - ctypes.c_byte(c).value).value rs = ctypes.c_byte((a - b - c) & 0xFF).value self.pc_state.P.set_N((0,1)[0x80 == (rs & 0x80)]) # Negative self.pc_state.P.set_Z((0,1)[rs == 0]) # Zero self.pc_state.P.set_V((0,1)[r != rs]) # Overflow r = a - b - c self.pc_state.P.set_C((1,0)[0x100 == (r & 0x100)]) # Carry (not borrow result = a - b - c elif 1 == self.pc_state.P.get_D(): # Decimal subtraction # FIXME need to fix flags r = ctypes.c_short(((a >> 4) & 0xF)* 10+ ((a & 0xF) %10) - (((b>>4) & 0xF)* 10 + ((b & 0xF) %10)) - c).value # rc = a + b + c self.pc_state.P.set_N((0,1)[r < 0]) self.pc_state.P.set_Z((0,1)[r == 0x0]) # Need to check/fix conditions for V # self.pc_state.P.V = (rc != r) ? 1:0; # Overflow self.pc_state.P.set_V(1) # Overflow self.pc_state.P.set_C((0,1)[(r >= 0) and (r <= 99)]) result = (((int(r/10) % 10) << 4) & 0xf0) + (r%10) return result & 0xFF
def show_p1_analog_inputs(packet): if SWAT_P1_RIO_AI in packet: level = ctypes.c_short(packet[SWAT_P1_RIO_AI].level).value flow = ctypes.c_short(packet[SWAT_P1_RIO_AI].flow).value slevel = ctypes.c_short(packet[SWAT_P1_RIO_AI].level) sflow = ctypes.c_short(packet[SWAT_P1_RIO_AI].flow) slevel = current_to_signal(slevel.value, P1Level) sflow = current_to_signal(sflow.value, P1Flow) print('level: {:2f} mm ({}) flow: {:2f} m^2/h ({})'.format(slevel, level, sflow, flow))
def show_p1_w_analog_inputs(packet): # TODO: this function needs to be tested if SWAT_P1_WRIO_AI in packet: level = ctypes.c_short(packet[SWAT_P1_WRIO_AI].level).value flow = ctypes.c_short(packet[SWAT_P1_WRIO_AI].flow).value slevel = ctypes.c_short(packet[SWAT_P1_WRIO_AI].level) sflow = ctypes.c_short(packet[SWAT_P1_WRIO_AI].flow) slevel = current_to_signal(slevel.value, P1Level) sflow = current_to_signal(sflow.value, P1Flow) print('level: {:2f} mm ({}) flow: {:2f} m^2/h ({})'.format(slevel, level, sflow, flow))
def read_real_level(packet): if SWAT_P1_RIO_AI in packet: l = ctypes.c_short(packet[SWAT_P1_RIO_AI].level).value slevel = ctypes.c_short(packet[SWAT_P1_RIO_AI].level) l = current_to_signal(slevel.value, P1Level) global _olevel, _elevel, _is_first_pck _olevel = l * 0.001 if _is_first_pck: _elevel = _olevel _is_first_pck = False
def get_model_parameters(packet): if SWAT_P1_RIO_AI in packet: global _rlevel, _flow l = ctypes.c_short(packet[SWAT_P1_RIO_AI].level) l = current_to_signal(l.value, P1Level) f = ctypes.c_short(packet[SWAT_P1_RIO_AI].flow) _flow = current_to_signal(f.value, P1Flow) _rlevel = l * 0.001 if SWAT_P1_RIO_DI in packet: global _pump1_in, _pump _valve = packet[SWAT_P1_RIO_DI].valve_open _pump = packet[SWAT_P1_RIO_DI].pump1_run
def write_plain(self, text): """ Write simple text to subprocess. """ li = INPUT_RECORD * len(text) list_input = li() for i in range(0, len(text)): # create keyboard input ke = KEY_EVENT_RECORD() ke.bKeyDown = ctypes.c_byte(1) ke.wRepeatCount = ctypes.c_short(1) cnum = ord(text[i]) logging.debug('writing char: ' + str(cnum)) ke.wVirtualKeyCode = ctypes.windll.user32.VkKeyScanW(cnum) ke.wVirtualScanCode = ctypes.c_short(ctypes.windll.user32.MapVirtualKeyW(int(cnum), 0)) if cnum > 31: ke.uChar.UnicodeChar = uchr(cnum) elif cnum == 3: ctypes.windll.kernel32.GenerateConsoleCtrlEvent(0, self.pid) ke.uChar.UnicodeChar = uchr(cnum) ke.wVirtualKeyCode = ctypes.windll.user32.VkKeyScanW(cnum + 96) ke.dwControlKeyState |= LEFT_CTRL_PRESSED else: ke.uChar.UnicodeChar = uchr(cnum) if cnum in CONQUE_WINDOWS_VK_INV: ke.wVirtualKeyCode = cnum else: ke.wVirtualKeyCode = ctypes.windll.user32.VkKeyScanW(cnum + 96) ke.dwControlKeyState |= LEFT_CTRL_PRESSED logging.info(str(ord(text[i])) + ' ' + text[i]) logging.info(ke.dwControlKeyState) kc = INPUT_RECORD(KEY_EVENT) kc.Event.KeyEvent = ke list_input[i] = kc #logging.debug(kc.to_str()) # write input array events_written = ctypes.c_int() res = ctypes.windll.kernel32.WriteConsoleInputW(self.stdin, list_input, len(text), ctypes.byref(events_written)) logging.debug('foo') logging.debug('events written ' + str(events_written)) logging.debug(str(res)) logging.debug(str(ctypes.GetLastError())) logging.debug(str(ctypes.FormatError(ctypes.GetLastError())))
def __init__( self, boardNumber = 0, lowChan = 0, highChan = 0, counts = 50, rate = SAMPLE_RATE, fileNamePath = ".\\data\\raw\\" ): ''' Initialize meilhaus class :param verbose: The higher the more output ''' self.deviceNr = ctypes.c_int(boardNumber) # Meilhaus card/board number to deal with # - starts from 0 where 0 is the dummy/test # board, when dealing with USB devices self.lowChan = ctypes.c_short(lowChan) # first input chanel we scan self.highChan = ctypes.c_short(highChan) # last input chanel we scan self.counts = ctypes.c_long(counts) # number of measurements - we are using (aquire time) self.rate = ctypes.c_long(rate) # frequency of measurement [Hz] #self.options = ctypes.c_int(BACKGROUND + CONTINUOUS) # measurement runs in background # # as long as we do not stop it self.options = ctypes.c_int(0) self.range = ctypes.c_int(BIP2VOLTS) # signal alternate between +/- 2V self.fileNamePath = fileNamePath # path of the directory where we want to # save the raw data to self.stopSignalCollection = threading.Event() # we set this event when we want # to finish self.signalCollectionFinished = threading.Event() # is set after the last sum signal # is generated # here we try to connect the dataArray param with the memory handle so we can access the # scan result more easyly # cast(obj, type) # This function is similar to the cast operator in C. It returns a new instance # of type which points to the same memory block as obj. type must be a pointer # type, and obj must be an object that can be interpreted as a pointer. #self.memHandle = meDLL.cbWinBufAlloc(MAX_COUNT_FOR_CONT_SCAN) # reserve some memory # returns a int value #self.dataArray = ctypes.cast( self.memHandle, ctypes.POINTER( ctypes.wintypes.WORD ) ) # here we collect the signals # each entry is the sum of one sampling run (samping rate = 50kHz, count number # give by user) # self.sumSignalArray = [] # error string self.errString = ctypes.c_char_p( "a" * ERRSTRLEN )
def get_data_bmp(): params = i2c.readList(0xAA, 22) #read 12 coefficients from EEPROM AC1 = c_short((params[0] <<8) + params[1]).value AC2 = c_short((params[2] <<8) + params[3]).value AC3 = c_short((params[4] <<8) + params[5]).value AC4 = (params[6] <<8) + params[7] AC5 = (params[8] <<8) + params[9] AC6 = (params[10] <<8) + params[11] B1 = c_short((params[12] <<8) + params[13]).value B2 = c_short((params[14] <<8) + params[15]).value MB = c_short((params[16] <<8) + params[17]).value MC = c_short((params[18] <<8) + params[19]).value MD = c_short((params[20] <<8) + params[21]).value #start conversion and read temperature i2c.write8(0xF4, 0x2E) time.sleep(0.01) #10 ms wait time for conversion msb = i2c.readU8(0xF6) lsb = i2c.readU8(0xF7) ut = (msb <<8) + lsb #uncompensated temperature #start conversion and read pressure oss = 3 #over_sampling setting [0-3], 3 = 8 samples i2c.write8(0xF4, 0x34+(oss<<6)) time.sleep(0.05) #50 ms wait time for 8 samples msb = i2c.readU8(0xF6) lsb = i2c.readU8(0xF7) xlsb = i2c.readU8(0xF8) up = ((msb<<16)+(lsb<<8)+(xlsb)) >> (8-oss) #uncompensated pressure #True Temperature X1 = (ut - AC6)*AC5/(2**15) X2 = (MC*(2**11))/(X1+MD) B5 = X1 + X2 temp = (B5+8)/(2**4) #True Pressure B6 = B5 - 4000 X1 = (B2*(B6*B6 >>12)) >>11 X2 = (AC2*B6) >>11 X3 = X1 + X2 B3 = (((AC1*4+X3)<<oss)+2)/4 X1 = (AC3*B6) >>13 X2 = (B1*((B6*B6)>>12)) >>16 X3 = ((X1+X2)+2) >>2 B4 = (AC4*(X3+32768)) >>15 B7 = (up-B3)*(50000>>oss) if (B7< 0x80000000): p = (B7*2)/B4 else: p = (B7/B4)*2 X1 = (p >>8)*(p >>8) X1 = (X1*3038) >>16 X2 = (-7357*p) >>16 pres = p+((X1+X2+3791)>>4) return (temp/10.0, pres) #temp = C/ pres = Pa
def convert_linear(val) : mantissa_raw = ctypes.c_short(val & 0x3ff) if mantissa_raw.value & 0x200 : mantissa_raw.value |= 0xfc00 mantissa = float(mantissa_raw.value) exp_raw = ctypes.c_short(val >> 11) if exp_raw.value & 0x10 : exp_raw.value |= 0xffe0 exp = float(exp_raw.value) factor = pow(2.0, exp) return mantissa*factor
def write_vk(self, vk_code): """ Write special characters to console subprocess. """ logging.debug('virtual key code' + str(vk_code)) code = None ctrl_pressed = False # this could be made more generic when more attributes # other than ctrl_pressed are available vk_attributes = vk_code.split(';') logging.debug(vk_attributes) for attr in vk_attributes: if attr == CONQUE_VK_ATTR_CTRL_PRESSED: ctrl_pressed = True else: code = attr li = INPUT_RECORD * 1 # create keyboard input ke = KEY_EVENT_RECORD() ke.uChar.UnicodeChar = uchr(0) ke.wVirtualKeyCode = ctypes.c_short(int(code)) ke.wVirtualScanCode = ctypes.c_short(ctypes.windll.user32.MapVirtualKeyW(int(code), 0)) ke.bKeyDown = ctypes.c_byte(1) ke.wRepeatCount = ctypes.c_short(1) # set enhanced key mode for arrow keys if code in CONQUE_WINDOWS_VK_ENHANCED: logging.debug('enhanced key!') ke.dwControlKeyState |= ENHANCED_KEY if ctrl_pressed: ke.dwControlKeyState |= LEFT_CTRL_PRESSED kc = INPUT_RECORD(KEY_EVENT) kc.Event.KeyEvent = ke list_input = li(kc) # write input array events_written = ctypes.c_int() res = ctypes.windll.kernel32.WriteConsoleInputW(self.stdin, list_input, 1, ctypes.byref(events_written)) logging.debug('events written ' + str(events_written)) logging.debug(str(res)) logging.debug(str(ctypes.GetLastError())) logging.debug(str(ctypes.FormatError(ctypes.GetLastError())))
def writeI16(self, i16): try: self.writeBuffer(str(ctypes.c_short(i16).value)) except TypeError: self._logger.error('TXML Protocol: Invalid i16 value %s') % (i16) return -1 return 0
def rotate(mem): mydll.tdeskew.restype = ctypes.c_double for x in range(0, max_deskew_attempts): result = mydll.tdeskew(mem, ctypes.c_short(1), #Subsampling ctypes.c_double(90), #Range ctypes.c_double(0.1), #DeskewAngle_res ctypes.c_double(4.0), #line resolution c_byte(0)) #DeskewGrayValue print 'tdeskew: %s' % result class RECT(Structure): _fields_ = [("x", c_int), ("y", c_int), ("w", c_int), ("h", c_int)] rect = RECT(0,0,2550,3300) #Need to read this dynamically result = -result #rotate in other direction to current skew #if result > 0: #result = - (360 - result) mem = mydll.ILRotate(mem, ctypes.c_double(result), byref(rect), 0xFFFFFF) #We then need to resize (CopyCropDib) as this will have grown or shrunk the image size print 'ILRotate: %s' % result return mem
def get_wlm_output(self, c): value = yield self.wmdll.GetOperationState(ctypes.c_short(0)) if value == 2: value = True else: value = False returnValue(value)
def cmp(self, a, b): r = ctypes.c_short(ctypes.c_byte(a).value - ctypes.c_byte(b).value).value rs = ctypes.c_byte(a - b).value self.pc_state.P.set_N((0,1)[0x80 == (rs & 0x80)]) # Negative self.pc_state.P.set_Z((0,1)[rs == 0]) # Zero r = (a & 0xFF) - (b & 0xFF) self.pc_state.P.set_C((1,0)[0x100 == (r & 0x100)]) # Carry (not borrow)
def distanceUSEV3(self): self.setType(self.PS_SENSOR_TYPE_EV3) self.setModeEV3(0) self.EV3Retrieve() raw1 = self.EV3Cache[4][0] raw2 = self.EV3Cache[4][1] return ctypes.c_short(raw1 | (raw2*256)).value
def chmod(self, path, mode): """Change access control of given path Exactly what permissions the file will get depends on HDFS configurations. Parameters ---------- path : string file/directory to change mode : integer As with the POSIX standard, each octal digit refers to user-group-all, in that order, with read-write-execute as the bits of each group. Examples -------- >>> hdfs.chmod('/path/to/file', 0o777) # make read/writeable to all # doctest: +SKIP >>> hdfs.chmod('/path/to/file', 0o700) # make read/writeable only to user # doctest: +SKIP >>> hdfs.chmod('/path/to/file', 0o100) # make read-only to user # doctest: +SKIP """ if not self.exists(path): raise FileNotFoundError(path) out = _lib.hdfsChmod(self._handle, ensure_bytes(path), ctypes.c_short(mode)) if out != 0: msg = ensure_string(_lib.hdfsGetLastError()) raise IOError("chmod failed on %s %s" % (path, msg))
def wm_add_default(C): # from wm.c idcode = blender.BKE_idcode_from_name( "WindowManager" ) print('winman idcode', idcode) _wm = blender.wmWindowManager() wm = blender.alloc_libblock( # returns void pointer _wm, # pointer to ListBase idcode, "WinMan" ) wm = blender.wmWindowManager( pointer=wm, cast=True ) print('wm', wm) print('CTX wm screen...') screen = blender.CTX_wm_screen(C) print( screen ) print('CTX wm manager set...') blender.CTX_wm_manager_set(C, wm); print('wm window new...') win = blender.wm_window_new(C); print(win) wm.winactive = win.POINTER wm.file_saved = ctypes.c_short(1) blender.wm_window_make_drawable(C, win) print('----------------------') main = blender.CTX_data_main(C)
def update_gas_status(self, xxx_todo_changeme): (id, data) = xxx_todo_changeme if id == 0x181: assert len(data)==2, data self.gas = ctypes.c_short(data[1]*256 + data[0]).value if self.verbose: print("GAS", self.gas)
def _bindcol(self, col_num): """Get col description and then bind the col""" col_name = ctypes.create_string_buffer(256) col_name_size = ctypes.c_short() col_type = ctypes.c_short() col_type_size = ctypes.c_ssize_t() col_dec_digits = ctypes.c_short() col_nullable = ctypes.c_short() rc = self.conn.api.SQLDescribeColW( self.handle, col_num, ctypes.byref(col_name), ctypes.sizeof(col_name), ctypes.byref(col_name_size), ctypes.byref(col_type), ctypes.byref(col_type_size), ctypes.byref(col_dec_digits), ctypes.byref(col_nullable)) check_error(self, rc, 'request col {}'.format(col_num)) col_name_decoded = col_name[:col_name_size.value*2].decode('utf_16_le') nullable = bool(1-col_nullable.value) # print('col #{} name: {}, type: {}, size: {} nullable: {}'.format( # col_num, col_name_decoded, col_type.value, col_type_size.value, # nullable)) c_col_type = SQL_TYPE_MAP[col_type.value] charsize = None is_char_array = False is_fixed_width = False if col_type.value in ALL_SQL_CHAR: is_char_array = True c_col_type = ctypes.c_char charsize = col_type_size.value + 1 if col_type.value in (SQL_CHAR, SQL_WCHAR): is_fixed_width = True col_type.value = SQL_CHAR elif col_type.value in (SQL_WCHAR, SQL_WVARCHAR, SQL_WLONGVARCHAR): # ODBC Unicode != utf-8; can't use the ctypes c_wchar charsize = col_type_size.value * 2 + 2 col_type.value = SQL_WCHAR col_buff = ((c_col_type * charsize) * self.arraysize)() else: col_buff = (c_col_type * self.arraysize)() if col_type.value == SQL_BIGINT: col_type.value = -25 # SQL_C_BIGINT col_indicator = (ctypes.c_ssize_t * self.arraysize)() self.return_buffer.append((col_num, col_buff, col_indicator, is_char_array, is_fixed_width, nullable)) # Bind the column rc = self.conn.api.SQLBindCol(self.handle, col_num, col_type.value, ctypes.byref(col_buff), charsize, ctypes.byref(col_indicator)) check_error(self, rc, 'bind col {}'.format(col_num))
def test_byref_pointer(self): from ctypes import c_short, c_uint, c_int, c_long, pointer, POINTER, byref LPINT = POINTER(c_int) LPINT.from_param(byref(c_int(42))) self.assertRaises(TypeError, LPINT.from_param, byref(c_short(22))) if c_int != c_long: self.assertRaises(TypeError, LPINT.from_param, byref(c_long(22))) self.assertRaises(TypeError, LPINT.from_param, byref(c_uint(22)))
def get_console_title(): """Get the title of current console""" strbuffer = ctypes.create_string_buffer(1024) size = ctypes.c_short(1024) ctypes.windll.kernel32.GetConsoleTitleA(strbuffer, size) # remove the hard coded launch shell name filterdTitle = strbuffer.value.replace(" - pc", "") return filterdTitle
def _refreshState(self) : receivedData = self.transfer(self._FunctionGetPosition, [], 2) if receivedData is not None : self._position = ctypes.c_short(receivedData[0] | (receivedData[1] << 8)).value receivedData = self.transfer(self._FunctionGetButton, [], 1) if receivedData is not None : self._button = bool(receivedData[0])
def _set_handle(self): out = _lib.hdfsOpenFile(self._fs, ensure_byte(self.path), mode_numbers[self.mode], self.buff, ctypes.c_short(self.repl), ctypes.c_int64(self.block_size)) if not out: raise IOError("Could not open file: %s, mode: %s" % (self.path, self.mode)) self._handle = out
def if_stage(self, instruction_cache, pc): """ IF You will fetch the next instruction out of the Instruction Cache. Put it in the WRITE version of the IF/ID pipeline register. """ w_register = self.ifidregisters[0] instruction = instruction_cache[pc] if instruction_cache[pc] == 0: w_register.function = 0 w_register.opcode = None return opcodes = { 0x20: 'lb', 0x28: 'sb', } functions = { 0x20: 'add', 0x22: 'sub', 0: 'nop' } opcode_mask = 0b111111 << 26 src1reg_mask = 0b11111 << 21 src2reg_mask = 0b11111 << 16 destreg_mask = 0b11111 << 11 function_mask = 0b111111 offset_mask = 0xffff pc += 4 opcode = (instruction & opcode_mask) >> 26 src1reg = (instruction & src1reg_mask) >> 21 src2reg = (instruction & src2reg_mask) >> 16 destreg = (instruction & destreg_mask) >> 11 function = instruction & function_mask offset = c_short(instruction & offset_mask).value w_register.incr_pc = pc w_register.inst = instruction if not opcode: w_register.opcode = None w_register.function = function w_register.mips_inst = "{} ${}, ${}, ${}".format( functions[function], destreg, src1reg, src2reg) else: w_register.opcode = opcode w_register.function = None w_register.mips_inst = "{} ${}, {}(${})".format( opcodes[opcode], src2reg, offset, src1reg) return
def read_short(runtime): runtime.step() byte1 = runtime.pc() runtime.step() byte2 = runtime.pc() val = ctypes.c_short((byte1 << 8) | byte2).value return val, [byte1, byte2]
def cbGetStatus(BoardNum, Status, CurCount, CurIndex, FunctionType): """Returns status about potentially currently running background operation""" Status = ctypes.c_short(Status) CurCount = ctypes.c_long(CurCount) CurIndex = ctypes.c_long(CurIndex) CHK( cbw.cbGetStatus(BoardNum, byref(Status), byref(CurCount), byref(CurIndex), FunctionType)) return Status.value, CurCount.value, CurIndex.value
def __init__(self, dtsVersion=24, exporterVersion=0): self.dtsVersion = dtsVersion self.exporterVersion = exporterVersion self.sequence32 = c_int(0) self.sequence16 = c_short(0) self.sequence8 = c_byte(0) self.buffer32 = [] self.buffer16 = [] self.buffer8 = []
def write_quat(self, quat): self.write16( c_short(int(quat.x * 32767)).value, c_short(int(quat.y * 32767)).value, c_short(int(quat.z * 32767)).value, c_short(int(quat.w * -32767)).value)
if DUMMY: power = r(180, 300) ac_bv = r(56, 3) else: res1 = client.read_holding_registers(15, 4, unit=246) ac_bv = client.read_holding_registers(26, 1, unit=246).registers[0]/100.0 power = res1.registers[0]/10.0 * res1.registers[3]/10.0 print("ac power-usage=%f,batt-voltage=%f" % (power, ac_bv)) #### Battery status if DUMMY: bv = r(56, 3) current = r(20, 5) soc = r(95, 5) else: bv = client.read_holding_registers(259, 3, unit=247).registers[0]/100.0 res2 = client.read_holding_registers(266, 1, unit=247) current = ctypes.c_short(res1.registers[2]).value/10.0 soc = res2.registers[0]/10.0 print("battery voltage=%f,current=%f,state-of-charge=%f" % (bv, current, soc)) #### Generator Input if DUMMY: res = r(800, 900) else: res = client.read_holding_registers(12, 4, unit=246).registers[0] * 10 print("ac generator-input=%f" % (res)) #except: # sys.exit(1)
########################### # Read library via ctypes # ########################### libadd = ctypes.cdll.LoadLibrary("../fortran/libfort.so") ######################## # 1. print "hello world" ######################## libadd.__hello_mod_MOD_print_hello(None) ################################### # 2. print int scalar and r8 scalar ################################### # fairly intuitive way to declare scalar ctypes int_scalar = ctypes.c_short(1) r8_scalar = ctypes.c_double(2.801) libadd.__pass_ints_mod_MOD_print_val(ctypes.byref(int_scalar)) libadd.__pass_reals_mod_MOD_print_val(ctypes.byref(r8_scalar)) ################################# # 3. print int array and r8 array ################################# # unintuitive way to declare arrays of ctypes... int_array = (ctypes.c_short*10)(1,2,3,4,5,6,7,8,9,10) r8_array = (ctypes.c_double*10)(1.1,1.2,1.3,1.4,1.5,1.6,1.7,1.8,1.9,2.0) libadd.__pass_ints_mod_MOD_print_array(int_array) libadd.__pass_reals_mod_MOD_print_array(r8_array)
def sint16_diff(a, b): '''clip integer value (a - b) to signed int16''' assert 0 <= a <= 0xFFFF, a assert 0 <= b <= 0xFFFF, b return ctypes.c_short(a - b).value
def read_memory_short(address): offset = ctypes.c_void_p(address) buff = ctypes.c_short(0) win32.ReadProcessMemory(pvz_handle, offset, ctypes.byref(buff), 2, None) return buff.value
def get_temperature_setpoint(self): val = ct.c_short() self.controller.pl_get_param(self.hCam, self.cst.PARAM_TEMP_SETPOINT, self.cst.ATTR_CURRENT, ct.byref(val)) return val.value / 100 # to get it in degrees
def __init__(self, vals): MI_Value.__init__(self, MI_SINT16A) self.value = [] if vals is not None: for val in vals: self.value.append(ctypes.c_short(val))
# data compression and archiving (CH 12) a['TarInfoType'] = tarfile.TarInfo() # generic operating system services (CH 15) a['LoggerType'] = logging.getLogger() a['FormatterType'] = logging.Formatter() # pickle ok a['FilterType'] = logging.Filter() # pickle ok a['LogRecordType'] = logging.makeLogRecord(_dict) # pickle ok a['OptionParserType'] = _oparser = optparse.OptionParser() # pickle ok a['OptionGroupType'] = optparse.OptionGroup(_oparser, "foo") # pickle ok a['OptionType'] = optparse.Option('--foo') # pickle ok if HAS_CTYPES: a['CCharType'] = _cchar = ctypes.c_char() a['CWCharType'] = ctypes.c_wchar() # fail == 2.6 a['CByteType'] = ctypes.c_byte() a['CUByteType'] = ctypes.c_ubyte() a['CShortType'] = ctypes.c_short() a['CUShortType'] = ctypes.c_ushort() a['CIntType'] = ctypes.c_int() a['CUIntType'] = ctypes.c_uint() a['CLongType'] = ctypes.c_long() a['CULongType'] = ctypes.c_ulong() a['CLongLongType'] = ctypes.c_longlong() a['CULongLongType'] = ctypes.c_ulonglong() a['CFloatType'] = ctypes.c_float() a['CDoubleType'] = ctypes.c_double() a['CSizeTType'] = ctypes.c_size_t() a['CLibraryLoaderType'] = ctypes.cdll a['StructureType'] = _Struct a['BigEndianStructureType'] = ctypes.BigEndianStructure() #NOTE: also LittleEndianStructureType and UnionType... abstract classes #NOTE: remember for ctypesobj.contents creates a new python object
def get_short(data, index): return c_short((data[index] << 8) + data[index + 1]).value
def read_data_fromplc(): dave = libnodave.libnodave() dave.open_socket("192.168.6.14") dave.new_interface("test", 0, 122, 1) dave.init_adapter() dave.connect_plc(0, 0, 1) print "from dave = %s" % dave bf = ctypes.c_short(0) bf_p = ctypes.pointer(bf) bf_float = ctypes.c_float(11.29) #bb = ctypes.c_float(a.myToPlcFloat(11.29)) #print type(bb) while True: sleep(5) temp = ctypes.c_float(0.0) do = ctypes.c_float(0.0) pH = ctypes.c_float(0.0) stir = ctypes.c_float(0.0) feed = ctypes.c_float(0.0) acid = ctypes.c_float(0.0) base = ctypes.c_float(0.0) ca = ctypes.c_float(0.0) o2 = ctypes.c_float(0.0) n2 = ctypes.c_float(0.0) co2 = ctypes.c_float(0.0) dave.read_bytes(0x84, 1, 16, 4, byref(temp)) dave.read_bytes(0x84, 10, 16, 4, byref(do)) dave.read_bytes(0x84, 25, 16, 4, byref(pH)) dave.read_bytes(0x84, 30, 36, 4, byref(stir)) dave.read_bytes(0x84, 30, 0, 4, byref(feed)) dave.read_bytes(0x84, 30, 4, 4, byref(acid)) dave.read_bytes(0x84, 25, 142, 4, byref(base)) dave.read_bytes(0x84, 10, 108, 4, byref(ca)) dave.read_bytes(0x84, 10, 112, 4, byref(o2)) dave.read_bytes(0x84, 10, 116, 4, byref(n2)) dave.read_bytes(0x84, 25, 84, 4, byref(co2)) temp = round(dave.myToPlcFloat(temp), 2) do = round(dave.myToPlcFloat(do), 2) pH = round(dave.myToPlcFloat(pH), 2) stir = dave.myToPlcFloat(stir) feed = round(dave.myToPlcFloat(feed), 2) acid = round(dave.myToPlcFloat(acid), 2) base = round(dave.myToPlcFloat(base), 2) ca = round(dave.myToPlcFloat(ca), 2) o2 = round(dave.myToPlcFloat(o2), 2) n2 = round(dave.myToPlcFloat(n2), 2) co2 = round(dave.myToPlcFloat(co2), 2) print "temp = %s do = %s pH = %s stir = %s feed = %s acid = %s base = %s ca = %s o2 = %s n2 = %s co2 = %s" % ( temp, do, pH, stir, feed, acid, base, ca, o2, n2, co2) name = 'br20140010' conn = cur = None try: conn = MySQLdb.connect(host='127.0.0.1', user='******', passwd='123456', db='plcdb') cur = conn.cursor() cur.execute( "REPLACE INTO plc_data_one(deviceName,currentDate,temp,do,pH,stir,feed,acid,base,ca,o2,n2,co2) VALUES(%s,NOW(),%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", (name, temp, do, pH, stir, feed, acid, base, ca, o2, n2, co2)) except MySQLdb.Error as e: raise e finally: if cur: cur.close() if conn: conn.commit() conn.close() dave.disconnect()
def read_setting_value(): dave = libnodave.libnodave() dave.open_socket("192.168.6.14") dave.new_interface("test", 0, 122, 1) dave.init_adapter() dave.connect_plc(0, 0, 1) temp = ctypes.c_float(0.0) do = ctypes.c_float(0.0) pH = ctypes.c_float(0.0) stir = ctypes.c_float(0.0) feed = ctypes.c_float(0.0) acid = ctypes.c_float(0.0) switch_value = ctypes.c_short(0) bf = ctypes.c_short(0) bf_p = ctypes.pointer(bf) bf_float = ctypes.c_float(11.29) dave.read_bytes(0x84, 1, 40, 4, byref(temp)) dave.read_bytes(0x84, 10, 52, 4, byref(do)) dave.read_bytes(0x84, 25, 52, 4, byref(pH)) dave.read_bytes(0x84, 30, 20, 4, byref(stir)) dave.read_bytes(0x84, 30, 12, 4, byref(feed)) dave.read_bytes(0x84, 30, 16, 4, byref(acid)) dave.read_bytes(0x84, 8, 0, 1, byref(switch_value)) print "switch_value = %s" % switch_value.value temp_list = libnodave.int_to_bitarr(switch_value.value) temp = round(dave.myToPlcFloat(temp), 2) do = round(dave.myToPlcFloat(do), 2) pH = round(dave.myToPlcFloat(pH), 2) stir = dave.myToPlcFloat(stir) feed = round(dave.myToPlcFloat(feed), 2) acid = round(dave.myToPlcFloat(feed), 2) temp_switch = temp_list[1] do_switch = temp_list[2] ph_switch = temp_list[3] stir_switch = temp_list[4] feed_switch = temp_list[5] acid_switch = temp_list[6] print "******* SV: temp = %s do = %s ph = %s stir = %s feed = %s acid = %s " % ( temp, do, pH, stir, feed, acid) name = 'br20140010' conn = cur = None try: conn = MySQLdb.connect(host='127.0.0.1', user='******', passwd='123456', db='plcdb') cur = conn.cursor() cur.execute( "REPLACE INTO plc_data_one_settings(deviceName,currentDate,temp,do,pH,stir,feed,acid,tempSwitch,doSwitch,phSwitch,stirSwitch,feedSwitch,acidSwitch) VALUES(%s,NOW(),%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", (name, temp, do, pH, stir, feed, acid, temp_switch, do_switch, ph_switch, stir_switch, feed_switch, acid_switch)) except MySQLdb.Error as e: raise e finally: if cur: cur.close() if conn: conn.commit() conn.close() dave.disconnect()
def ReadCalibrationData(self): bus = smbus.SMBus(1) self.calibration_data[0:26] = bus.read_i2c_block_data(0x76, 0x88, 26) self.calibration_data[26:42] = bus.read_i2c_block_data(0x76, 0xE1, 16) bus.close() self.dig_T1 = ctypes.c_ushort(self.calibration_data[0] | (self.calibration_data[1]<<8)).value self.dig_T2 = ctypes.c_short(self.calibration_data[2] | (self.calibration_data[3]<<8)).value self.dig_T3 = ctypes.c_short(self.calibration_data[4] | (self.calibration_data[5]<<8)).value self.dig_P1 = ctypes.c_ushort(self.calibration_data[6] | (self.calibration_data[7]<<8)).value self.dig_P2 = ctypes.c_short(self.calibration_data[8] | (self.calibration_data[9]<<8)).value self.dig_P3 = ctypes.c_short(self.calibration_data[10] | (self.calibration_data[11]<<8)).value self.dig_P4 = ctypes.c_short(self.calibration_data[12] | (self.calibration_data[13]<<8)).value self.dig_P5 = ctypes.c_short(self.calibration_data[14] | (self.calibration_data[15]<<8)).value self.dig_P6 = ctypes.c_short(self.calibration_data[16] | (self.calibration_data[17]<<8)).value self.dig_P7 = ctypes.c_short(self.calibration_data[18] | (self.calibration_data[19]<<8)).value self.dig_P8 = ctypes.c_short(self.calibration_data[20] | (self.calibration_data[21]<<8)).value self.dig_P9 = ctypes.c_short(self.calibration_data[22] | (self.calibration_data[23]<<8)).value self.dig_H1 = ctypes.c_ubyte(self.calibration_data[25]).value self.dig_H2 = ctypes.c_short(self.calibration_data[26] | (self.calibration_data[27]<<8)).value self.dig_H3 = ctypes.c_ubyte(self.calibration_data[28]).value self.dig_H4 = ctypes.c_short((self.calibration_data[29]<<4) | (self.calibration_data[30] & 0x0F)).value self.dig_H5 = ctypes.c_short((self.calibration_data[32]<<4) | ((self.calibration_data[31] & 0xF)>>4)).value self.dig_H6 = ctypes.c_byte(self.calibration_data[32]).value '''print 'dig_T1 =', self.dig_T1
def link_type(self, link_type): self.__link_type = struct.pack("!h", ctypes.c_short(link_type).value)
def __init__(self, camera_name='Camera1'): # OPEN CAMERA # ===================================================================== self.name = camera_name.encode('utf-8') self.hCam = ct.c_ushort() self.controller.pl_cam_open(ct.c_char_p(self.name), ct.byref(self.hCam), self.cst.OPEN_EXCLUSIVE) # SEQUENCE CONFIGURATION # ===================================================================== # CCD Number of pixels in one line ccd_nb_pixels = ct.c_ushort() self.controller.pl_get_param(self.hCam, self.cst.PARAM_SER_SIZE, self.cst.ATTR_CURRENT, ct.byref(ccd_nb_pixels)) ccd_nb_pixels = ccd_nb_pixels.value # CCD Number of lines ccd_nb_lines = ct.c_ushort() self.controller.pl_get_param(self.hCam, self.cst.PARAM_PAR_SIZE, self.cst.ATTR_CURRENT, ct.byref(ccd_nb_lines)) ccd_nb_lines = ccd_nb_lines.value # Region self.region = Region( region_ref=[0, 0, ccd_nb_pixels - 1, ccd_nb_lines - 1], binning=[1, 1]) # Others parameters nb_exposures = ct.c_ushort(1) # 1 spectrum acquired each time nb_roi = ct.c_ushort(1) fake_exposure_time = ct.c_uint(1) # ignored in variable_timed_mode exposure_mode = self.cst.VARIABLE_TIMED_MODE # allow to change only the exposure time between two acquisition (see manual) stream_size = ct.c_uint() # Send configuration self.controller.pl_exp_setup_seq(self.hCam, nb_exposures, nb_roi, ct.byref(self.region), exposure_mode, fake_exposure_time, ct.byref(stream_size)) # EXPOSURE TIME # ===================================================================== # Unit (ms) val = ct.c_short(self.cst.EXP_RES_ONE_MILLISEC) self.controller.pl_set_param(self.hCam, self.cst.PARAM_EXP_RES, ct.byref(val)) # Initial value self.set_exposure_time(1) # OTHER INITIALIZATION STEPS # ===================================================================== val = ct.c_short(self.cst.OPEN_PRE_SEQUENCE) self.controller.pl_set_param(self.hCam, self.cst.PARAM_SHTR_OPEN_MODE, ct.byref(val)) val = ct.c_short(2) self.controller.pl_set_param(self.hCam, self.cst.PARAM_CLEAR_CYCLES, ct.byref(val))
def __init__(self, val): MI_Value.__init__(self, MI_SINT16) if val is not None: self.value = ctypes.c_short(val)
def set_waveform(self, type=0, frequency=1000, waveform_parameters=None): """ set the the waveform signal generator from basic shapes (see ps5000aSetSigGenArbitrary for arbitrary waveforms) PICO_STATUS ps5000aSetSigGenBuiltIn ( short handle, long offsetVoltage, unsigned long pkToPk, PS5000A_WAVE_TYPE waveType, float startFrequency, float stopFrequency, float increment, float dwellTime, PS5000A_SWEEP_TYPE sweepType, PS5000A_EXTRA_OPERATIONS operation, unsigned long shots, unsigned long sweeps, PS5000A_SIGGEN_TRIG_TYPE triggerType, PS5000A_SIGGEN_TRIG_SOURCE triggerSource, short extInThreshold ) Parameters ---------- type: enum (or int) gives the shape of the waveform 0: sine 1: square 2: triangle 3: DC 4: ramp_up 5: ramp down 6: sinc sinus cardinal 7: gaussian 8: half sine frequency: the main frequency waveform_parameters: dictionnary containing the needed parameters Returns ------- pico_status : string indicating the status of the controller """ try: if waveform_parameters is None: # set the default (square like TTL) waveform_parameters = self.waveform_parameters_default offset_voltage = ctypes.c_long( waveform_parameters['offset_voltage']) # in microvolt pkTopk = ctypes.c_ulong(int( waveform_parameters['pkTopk'])) # in microvolt wave_type = waveform_parameters['wave_type'] start_frequency = ctypes.c_float( waveform_parameters['start_frequency']) stop_frequency = ctypes.c_float( waveform_parameters['stop_frequency']) increment_frequency = ctypes.c_float( waveform_parameters['increment_frequency']) dwell_time = ctypes.c_float(waveform_parameters['dwell_time']) sweep_type = waveform_parameters[ 'sweep_type'] #either PS5000A_UP ,PS5000A_DOWN, PS5000A_UPDOWN,PS5000A_DOWNUP operation = waveform_parameters['operation'] """either PS5000A_ES_OFF, normal signal generator operation specified by wavetype. PS5000A_WHITENOISE, the signal generator produces white noise and ignores all settings except pkToPk and offsetVoltage. PS5000A_PRBS, produces a random bitstream with a bit rate specified by the start and stop frequency.""" shots = ctypes.c_long(waveform_parameters['shots']) """0: sweep the frequency as specified by sweeps 1...PS5000A_MAX_SWEEPS_SHOTS: the number of cycles of thewaveform to be produced after a trigger event. sweeps must be zero.PS5000A_SHOT_SWEEP_TRIGGER_CONTINUOUS_RUN: start and run continuously after trigger occurs""" sweeps = ctypes.c_long(waveform_parameters['sweeps']) """ 0: produce number of cycles specified by shots 1..PS5000A_MAX_SWEEPS_SHOTS: the number of times to sweepthe frequency after a trigger event, according to sweepType.shots must be zero.PS5000A_SHOT_SWEEP_TRIGGER_CONTINUOUS_RUN: start a sweep and continue after trigger occurs""" trigger_type = waveform_parameters['trigger_type'] """PS5000A_SIGGEN_RISING trigger on rising edge PS5000A_SIGGEN_FALLING trigger on falling edge PS5000A_SIGGEN_GATE_HIGH run while trigger is high PS5000A_SIGGEN_GATE_LOW run while trigger is low""" trigger_source = waveform_parameters['trigger_source'] """PS5000A_SIGGEN_NONE run without waiting for trigger PS5000A_SIGGEN_SCOPE_TRIG use scope trigger PS5000A_SIGGEN_EXT_IN use EXT input PS5000A_SIGGEN_SOFT_TRIG wait for software trigger provided by ps5000aSigGenSoftwareControl PS5000A_SIGGEN_TRIGGER_RAW reserved""" extInThreshold = ctypes.c_short( waveform_parameters['extInThreshold'] ) #used to set trigger level for external trigger. err_code = self._picolib.ps5000aSetSigGenBuiltIn( self._handle.contents, offset_voltage, pkTopk, wave_type, start_frequency, stop_frequency, increment_frequency, dwell_time, sweep_type, operation, shots, sweeps, trigger_type, trigger_source, extInThreshold) pico_status = self._translate_error(err_code) except Exception as e: pico_status = str(e) return pico_status
from ctypes import (Structure, cdll, c_bool, c_short, c_int, c_uint, c_int16, c_int32, c_char, c_byte, c_long, c_float, c_double, POINTER, CFUNCTYPE, c_ushort, c_ulong) c_word = c_ushort c_dword = c_ulong # enum FT_Status FT_OK = c_short(0x00) FT_InvalidHandle = c_short(0x01) FT_DeviceNotFound = c_short(0x02) FT_DeviceNotOpened = c_short(0x03) FT_IOError = c_short(0x04) FT_InsufficientResources = c_short(0x05) FT_InvalidParameter = c_short(0x06) FT_DeviceNotPresent = c_short(0x07) FT_IncorrectDevice = c_short(0x08) FT_Status = c_short # enum MOT_MotorTypes MOT_NotMotor = c_int(0) MOT_DCMotor = c_int(1) MOT_StepperMotor = c_int(2) MOT_BrushlessMotor = c_int(3) MOT_CustomMotor = c_int(100) MOT_MotorTypes = c_int # enum MOT_TravelModes MOT_TravelModeUndefined = c_int(0x00) MOT_Linear = c_int(0x01) MOT_Rotational = c_int(0x02)
def init(self): self.debugPrint('================= PXI 6368 Init ===============') ##self.restoreInfo() #Acquisition in progress module check if self.restoreInfo() == self.DEV_IS_OPEN : try: self.restoreWorker() print( 'Check Start Store') if self.worker.isAlive(): print('stop Store') self.stop_store() self.restoreInfo() except: pass aiConf = c_void_p(0) try: inputMode = self.inputModeDict[self.input_mode.data()] except: Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid Input Mode') raise DevBAD_PARAMETER dev_fd = 0; fileName = '/dev/pxie-6368.'+str(self.boardId); dev_fd = os.open(fileName, os.O_RDWR); #self.debugPrint('Open ai_fd: ', self.ai_fd) device_info = self.XSERIES_DEV_INFO(0,"",0,0,0,0,0,0,0,0,0,0,0,0,0,0) # get card info status = NI6368AI.niInterfaceLib._xseries_get_device_info(c_int(dev_fd), byref(device_info)); if status: Data.execute('DevLogErr($1,$2)', self.getNid(), 'Error reading card information') raise mdsExceptions.TclFAILED_ESSENTIAL os.close(dev_fd) try: self.serial_num.putData(device_info.serial_number) except: pass #self.debugPrint('OK xseries_get_device_info') #Stop the segment TODO is this necessary since the reset is next NI6368AI.niLib.xseries_stop_ai(c_int(self.ai_fd)) #reset AI segment status = NI6368AI.niLib.xseries_reset_ai(c_int(self.ai_fd)) if ( status ): errno = NI6368AI.niInterfaceLib.getErrno(); Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot reset AI segment: (%d) %s' % (errno, os.strerror( errno )) ) raise mdsExceptions.TclFAILED_ESSENTIAL #Check Acquisition Configuration try: bufSize = self.buf_size.data() except: Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve acquisition buffer size') raise DevBAD_PARAMETER try: segmentSize = self.seg_length.data() except: Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve acquisition segment size') raise DevBAD_PARAMETER #Acquisition management try: acqMode = self.acq_mode.data() except: Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve acquisition mode management') raise DevBAD_PARAMETER #trigger mode try: trigMode = self.trig_mode.data() except: Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid triger mode definition') raise DevBAD_PARAMETER #trigger source try: trigSource = ( self.trig_source.data() ) except: if(trigMode == 'EXTERNAL'): Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve Trigger source') raise DevBAD_PARAMETER else: trigSource = 0. self.trig_source.putData( Float32(trigSource) ) self.debugPrint('PXI 6368 Trigger source: ', trigSource) try: numTrigger = len(trigSource) - 1 """ Trigger time must be set to 0. in multi trigger acquisition for correct evaluation of the number of samples to acquire for each trigger """ trigTime = 0. except: numTrigger = 1 trigTime = trigSource #self.debugPrint('Trigger number: ', numTrigger) #clock mode try: clockMode = self.clock_mode.data() if(clockMode == 'INTERNAL'): frequency = self.clock_freq.data() if( frequency > 2000000. ): self.debugPrint('Frequency out of limits') frequency = 2000000. clockSource = Range(None,None, Float64(1./frequency)) self.clock_source.putData(clockSource) else: #self.debugPrint('External') clockSource = self.clock_source.evaluate() self.debugPrint('PXI 6368 External CLOCK: ', clockSource) except: Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid clock definition') raise mdsExceptions.TclFAILED_ESSENTIAL self.debugPrint('PXI 6368 CLOCK: ', clockSource) #Time management try: useTime = self.use_time.data() except: Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot resolve time or samples management') raise mdsExceptions.TclFAILED_ESSENTIAL if acqMode == 'TRANSIENT REC.': if useTime == 'YES': try: startTime = float( self.start_time.data() ) endTime = float( self.end_time.data() ) self.debugPrint('PXI 6368 startTime = ', startTime) self.debugPrint('PXI 6368 endTime = ', endTime) self.debugPrint('PXI 6368 trigTime = ', trigTime) except: Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot Read Start or End time') raise mdsExceptions.TclFAILED_ESSENTIAL #Originale startIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigTime), clockSource), startTime) #self.debugPrint("Originale startIdx ", startIdx endIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigTime), clockSource), endTime) + 1 #self.debugPrint("Originale endIdx ", endIdx) """ if endTime > 0: endIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigTime), clockSource), endTime + trigTime) else: endIdx = -Data.execute('x_to_i($1,$2)', Dimension(Window(0, None, trigTime + endTime), clockSource), trigTime) if startTime > 0: startIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigTime), clockSource), startTime + trigTime) else: startIdx = -Data.execute('x_to_i($1,$2)', Dimension(Window(0, None, trigTime + startTime), clockSource), trigTime) `""" self.debugPrint('PXI 6368 startIdx = ', Int32(int(startIdx))) self.start_idx.putData(Int32(int(startIdx))) self.debugPrint('PXI 6368 endIdx = ', Int32(int(endIdx))) self.end_idx.putData(Int32(int(endIdx))) else: endIdx = self.end_idx.data() startIdx = self.start_idx.data() nSamples = endIdx - startIdx postTrigger = nSamples + startIdx preTrigger = nSamples - endIdx self.debugPrint('PXI 6368 nSamples = ', Int32(int(nSamples))) self.debugPrint('PXI 6368 seg_length = ', self.seg_length.data()) else: #Continuous Acquisition if useTime == 'YES': try: startTime = float( self.start_time.data() ) self.debugPrint('PXI 6368 startTime = ', startTime) self.debugPrint('PXI 6368 trigTime = ', trigTime) startIdx = Data.execute('x_to_i($1, $2)', Dimension(Window(0, None, trigTime), clockSource), startTime) except: startIdx = 0 self.start_idx.putData(Int32(int(startIdx))) else: startIdx = self.start_idx.data() nSamples = -1 if acqMode == 'TRANSIENT REC.': if startIdx >= 0 : NI6368AI.niInterfaceLib.xseries_create_ai_conf_ptr(byref(aiConf), c_int(0), c_int(startIdx + nSamples), (numTrigger)) #niInterfaceLib.xseries_create_ai_conf_ptr(byref(aiConf), c_int(0), c_int(0), 0) else: self.debugPrint('PXI 6368 preTrigger = ', Int32(int(preTrigger))) self.debugPrint('PXI 6368 postTrigger = ', Int32(int(postTrigger))) if trigTime > startTime or trigMode == 'INTERNAL' : self.debugPrint ('PXI 6368 Acquire only post trigger when triger time > start Time or trigger mode internal') nSamples = postTrigger startIdx = 0 self.start_idx.putData(Int32(int(0))) self.start_time.putData(Float32(trigTime)) NI6368AI.niInterfaceLib.xseries_create_ai_conf_ptr(byref(aiConf), c_int(-startIdx), c_int(nSamples), (numTrigger)) #niInterfaceLib.xseries_create_ai_conf_ptr(byref(aiConf), c_int(0), c_int(0), 0) else: NI6368AI.niInterfaceLib.xseries_create_ai_conf_ptr(byref(aiConf), c_int(0), c_int(0), 0) """ if(status != 0): Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot Set Number of Samples') raise mdsExceptions.TclFAILED_ESSENTIAL """ #XSERIES_AI_DMA_BUFFER_SIZE = 0 status = NI6368AI.niLib.xseries_set_ai_attribute(aiConf, c_int(0) , c_int(80)); if(status != 0): errno = NI6368AI.niInterfaceLib.getErrno(); Data.execute('DevLogErr($1,$2)', self.getNid(), 'Set DMA buffer size : (%d) %s' % (errno, os.strerror( errno )) ) raise mdsExceptions.TclFAILED_ESSENTIAL #disable external gate status = NI6368AI.niLib.xseries_set_ai_external_gate(aiConf, self.XSERIES_AI_EXTERNAL_GATE_DISABLED, self.XSERIES_AI_POLARITY_ACTIVE_LOW_OR_FALLING_EDGE) if( status != 0 ): errno = NI6368AI.niInterfaceLib.getErrno(); Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot disable external gate!: (%d) %s' % (errno, os.strerror( errno )) ) raise mdsExceptions.TclFAILED_ESSENTIAL #SET trigger if (trigMode == 'EXTERNAL'): #if(acqMode == 'TRANSIENT REC.'): self.debugPrint ("PXI 6368 select start trigger External (START1 signal)") status = NI6368AI.niLib.xseries_set_ai_start_trigger(aiConf, self.XSERIES_AI_START_TRIGGER_PFI1, self.XSERIES_AI_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE ,1) #test #status = niLib.xseries_set_ai_reference_trigger(aiConf, self.XSERIES_AI_START_TRIGGER_PFI1, self.XSERIES_AI_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE ,1) if( status != 0 ): errno = NI6368AI.niInterfaceLib.getErrno(); Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot set external trigger: (%d) %s' % (errno, os.strerror( errno )) ) raise mdsExceptions.TclFAILED_ESSENTIAL else: self.debugPrint ("PXI 6368 select start trigger Internal (START1 signal)") #status = niLib.xseries_set_ai_start_trigger(aiConf, self.XSERIES_AI_START_TRIGGER_SW_PULSE, self.XSERIES_AI_POLARITY_ACTIVE_LOW_OR_FALLING_EDGE, 0) status = NI6368AI.niLib.xseries_set_ai_start_trigger(aiConf, self.XSERIES_AI_START_TRIGGER_LOW, self.XSERIES_AI_POLARITY_ACTIVE_LOW_OR_FALLING_EDGE, 0) if( status != 0 ): errno = NI6368AI.niInterfaceLib.getErrno(); Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot set auto start trigger: (%d) %s' % (errno, os.strerror( errno )) ) raise mdsExceptions.TclFAILED_ESSENTIAL #SET clock if(clockMode == 'INTERNAL'): period = int( 100000000/frequency ) #TB3 clock 100MHz self.debugPrint ("PXI 6368 Internal CLOCK TB3 period ", period) status = NI6368AI.niLib.xseries_set_ai_scan_interval_counter(aiConf, self.XSERIES_SCAN_INTERVAL_COUNTER_TB3, self.XSERIES_SCAN_INTERVAL_COUNTER_POLARITY_RISING_EDGE, c_int(period), c_int(2)); if(status != 0): errno = NI6368AI.niInterfaceLib.getErrno(); Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot Set internal sample clock: (%d) %s' % (errno, os.strerror( errno )) ) raise mdsExceptions.TclFAILED_ESSENTIAL else: self.debugPrint("PXI 6368 Program the sample clock (START signal) to start on a rising edge") status = NI6368AI.niLib.xseries_set_ai_sample_clock(aiConf, self.XSERIES_AI_SAMPLE_CONVERT_CLOCK_PFI0, self.XSERIES_AI_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE, c_int(1)) if( status == 0): #Program the convert to be the same as START. status = NI6368AI.niLib.xseries_set_ai_convert_clock(aiConf, self.XSERIES_AI_SAMPLE_CONVERT_CLOCK_INTERNALTIMING, self.XSERIES_AI_POLARITY_ACTIVE_HIGH_OR_RISING_EDGE) self.debugPrint ("xseries_set_ai_convert_clock ", self.XSERIES_AI_SAMPLE_CONVERT_CLOCK_INTERNALTIMING) if(status == 0): #Program the sample and convert clock timing specifications status = NI6368AI.niLib.xseries_set_ai_scan_interval_counter(aiConf, self.XSERIES_SCAN_INTERVAL_COUNTER_TB3, self.XSERIES_SCAN_INTERVAL_COUNTER_POLARITY_RISING_EDGE, c_int(100), c_int(2)); self.debugPrint ("xseries_set_ai_scan_interval_counter ", self.XSERIES_SCAN_INTERVAL_COUNTER_TB3) if(status != 0): errno = NI6368AI.niInterfaceLib.getErrno(); Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot configure external device clock: (%d) %s' % (errno, os.strerror( errno )) ) raise mdsExceptions.TclFAILED_ESSENTIAL #Channel configuration numChannels = 16 activeChan = 0; for chan in range(1, numChannels+1): try: #Empy the node which will contain the segmented data getattr(self, 'channel_%d_data_raw'%(chan)).deleteData() getattr(self, 'channel_%d_data_raw'%(chan)).setCompressOnPut(False) enabled = self.enableDict[getattr(self, 'channel_%d_state'%(chan)).data()] gain = self.gainDict[getattr(self, 'channel_%d_range'%(chan)).data()] data = Data.compile("NIanalogInputScaled( build_path($), build_path($) )", getattr(self, 'channel_%d_data_raw'%(chan)).getPath(), getattr(self, 'channel_%d_calib_param'%(chan)).getPath() ) data.setUnits("Volts") getattr(self, 'channel_%d_data'%(chan)).putData(data) except: #self.debugPrint(sys.exc_info()[0]) self.debugPrint(traceback.format_exc()) Data.execute('DevLogErr($1,$2)', self.getNid(), 'Invalid Configuration for channel '+str(chan)) raise mdsExceptions.TclFAILED_ESSENTIAL if(enabled): #self.debugPrint(' GAIN: ' + str(gain) + ' INPUT MODE: ' + str(inputMode) status = NI6368AI.niLib.xseries_add_ai_channel(aiConf, c_short(chan-1), gain, inputMode, c_byte(1)) if(status != 0): Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot add channel '+str(chan)) raise mdsExceptions.TclFAILED_ESSENTIAL #self.debugPrint ('PXI 6368 CHAN '+ str(chan) + ' CONFIGURED') activeChan = chan #else: #self.debugPrint ('PXI 6368 CHAN '+ str(chan) + ' DISABLED' ) #endfor NI6368AI.niLib.xseries_stop_ai(c_int(self.ai_fd)) try: status = NI6368AI.niInterfaceLib.xseries_set_ai_conf_ptr(c_int(self.ai_fd), aiConf) #status = NI6368AI.niLib.xseries_load_ai_conf( c_int(self.ai_fd), aiConf) if(status != 0): errno = NI6368AI.niInterfaceLib.getErrno(); Data.execute('DevLogErr($1,$2)', self.getNid(), 'Cannot load ai configuration : (%d) %s' % (errno, os.strerror( errno )) ) raise mdsExceptions.TclFAILED_ESSENTIAL except IOError: Data.execute('DevLogErr($1,$2)', self.getNid(), 'Exception: cannot load ai configuration: (%d) %s' % (errno, os.strerror( errno )) ) raise mdsExceptions.TclFAILED_ESSENTIAL """ if(acqMode == 'TRANSIENT REC.'): status = NI6368AI.niLib.xseries_start_ai(c_int(self.ai_fd)) if(status != 0): Data.execute('DevLogErr($1,$2)', self.device.getNid(), 'Cannot Start Acquisition ') return """ self.saveInfo() self.debugPrint("===============================================") return 1
self.speed_average = FRAC * self.speed_raw + ( 1 - FRAC) * self.speed_average if self.verbose: print "SPEED", self.time, self.speed_raw, self.speed_average self.prev_enc_raw = arr if self.verbose: print "ENC\t{}\t{}\t{}".format(self.time, self.dist_left_raw, self.dist_right_raw) if id == 0x184: # change report assert len(data) == 1, data # print "CHANGE", data[0] & 0x3, (data[0] >> 2) & 0x3, self.dist_right_raw def update_wheel_angle_status(self, (id, data)): if id == 0x182: assert (len(data) == 2) self.wheel_angle_raw = ctypes.c_short(data[1] * 256 + data[0]).value if self.verbose: print "WHEEL", self.time, self.wheel_angle_raw def update(self, packet): self.update_gas_status(packet) self.update_encoders(packet) self.update_wheel_angle_status(packet) def set_time(self, time): self.time = time def send_speed(self): # and turning commands if self.cmd == 'go': if self.filteredGas < GO_LIMIT: self.can.sendData(0x201, [0xC]) # pulse forward
def set_temperature_setpoint(self, temperature): new_setpoint = ctypes.c_short(int(temperature*100.0)) rs_bool = pvlib.pl_set_param(self._handle, ctypes.c_int(PARAM_TEMP_SETPOINT), ctypes.byref(new_setpoint)) return self.pv_check()
def conv(self, msb, lsb): value = lsb | (msb << 8) return ctypes.c_short(value).value
def get_cam_total(self): total_cams = ctypes.c_short(0) rs_bool = pvlib.pl_cam_get_total(ctypes.byref(total_cams)) return self.pv_check()
def value(self): logger = lldb.formatters.Logger.Logger() global statistics # we need to skip the ISA, then the next byte tells us what to read # we then skip one other full pointer worth of data and then fetch the contents # if we are fetching an int64 value, one more pointer must be skipped to get at our data data_type_vo = self.valobj.CreateChildAtOffset("dt", self.sys_params.pointer_size, self.sys_params.types_cache.char) data_type = ((data_type_vo.GetValueAsUnsigned(0) % 256) & 0x1F) data_offset = 2 * self.sys_params.pointer_size if data_type == 0B00001: data_vo = self.valobj.CreateChildAtOffset("data", data_offset, self.sys_params.types_cache.char) statistics.metric_hit('code_notrun',self.valobj) return '(char)' + str(ord(ctypes.c_char(chr(data_vo.GetValueAsUnsigned(0))).value)) elif data_type == 0B0010: data_vo = self.valobj.CreateChildAtOffset("data", data_offset, self.sys_params.types_cache.short) statistics.metric_hit('code_notrun',self.valobj) return '(short)' + str(ctypes.c_short(data_vo.GetValueAsUnsigned(0) % (256*256)).value) # IF tagged pointers are possible on 32bit+v2 runtime # (of which the only existing instance should be iOS) # then values of this type might be tagged elif data_type == 0B0011: data_vo = self.valobj.CreateChildAtOffset("data", data_offset, self.sys_params.types_cache.int) statistics.metric_hit('code_notrun',self.valobj) return '(int)' + str(ctypes.c_int(data_vo.GetValueAsUnsigned(0)% (256*256*256*256)).value) # apparently, on is_64_bit architectures, these are the only values that will ever # be represented by a non tagged pointers elif data_type == 0B10001: data_offset = data_offset + 8 # 8 is needed even if we are on 32bit data_vo = self.valobj.CreateChildAtOffset("data", data_offset, self.sys_params.types_cache.longlong) statistics.metric_hit('code_notrun',self.valobj) return '(long)' + str(ctypes.c_long(data_vo.GetValueAsUnsigned(0)).value) elif data_type == 0B0100: if self.sys_params.is_64_bit: data_offset = data_offset + self.sys_params.pointer_size data_vo = self.valobj.CreateChildAtOffset("data", data_offset, self.sys_params.types_cache.longlong) statistics.metric_hit('code_notrun',self.valobj) return '(long)' + str(ctypes.c_long(data_vo.GetValueAsUnsigned(0)).value) elif data_type == 0B0101: data_vo = self.valobj.CreateChildAtOffset("data", data_offset, self.sys_params.types_cache.longlong) data_plain = int(str(data_vo.GetValueAsUnsigned(0) & 0x00000000FFFFFFFF)) packed = struct.pack('I', data_plain) data_float = struct.unpack('f', packed)[0] statistics.metric_hit('code_notrun',self.valobj) return '(float)' + str(data_float) elif data_type == 0B0110: data_vo = self.valobj.CreateChildAtOffset("data", data_offset, self.sys_params.types_cache.longlong) data_plain = data_vo.GetValueAsUnsigned(0) data_double = struct.unpack('d', struct.pack('Q', data_plain))[0] statistics.metric_hit('code_notrun',self.valobj) return '(double)' + str(data_double) statistics.metric_hit('unknown_class',str(valobj.GetName()) + " had unknown data_type " + str(data_type)) return 'absurd: dt = ' + str(data_type)
def test_mutate_short(self): a = ctypes.c_short() a.value = 2 r = ctest.mutate_short(a) self.assertEqual(a.value, 4)
def ConvertToFloat(data, reg): return float(ctypes.c_short(data.registers[reg]).value) / 10
def readIntegerSigned(self, reg): a = self.readInteger(reg) signed_a = ctypes.c_short(a).value return signed_a
def getShort(self, data, index): # return two bytes from data as a signed 16-bit value return c_short((data[index + 1] << 8) + data[index]).value
def _read_fs(self, raw_value, low=0, high=10, base=32768): # full-scale conversion value = ctypes.c_short(raw_value).value return (value * high / float(base)) + low
"Sample code for homing." from ctypes import ( c_short, c_int, c_char_p, ) from time import sleep from thorlabs_kinesis import benchtop_stepper_motor as bsm if __name__ == "__main__": serial_no = c_char_p(bytes("40875459", "utf-8")) channel = c_short(1) milliseconds = c_int(100) if bsm.TLI_BuildDeviceList() == 0: if bsm.SBC_Open(serial_no) == 0: sleep(1.0) bsm.SBC_StartPolling(serial_no, channel, milliseconds) bsm.SBC_ClearMessageQueue(serial_no, channel) sleep(1.0) err = bsm.SBC_Home(serial_no, channel) sleep(1.0) if err == 0: while True: current_pos = int(bsm.SBC_GetPosition(serial_no, channel)) if current_pos == 0: print("At home.") break else:
def write16(self, *values): #for value in values: # assert -32768 <= value <= 32767, "value {} out of range".format(value) # assert type(value) == int, "type is {}, must be {}".format(type(value), int) #self.buffer16.extend(values) self.buffer16.extend(map(lambda v: c_short(int(v)).value, values))