def homing(): ip_address = device_ip.galil_ip # make an instance of the gclib python class g = gclib.py() # print('gclib version:', self.g.GVersion()) #Connection of galil card through ip address try: g.GOpen(ip_address + ' --direct -s ALL') # self.g.GOpen('COM1 --direct') print(g.GInfo()) except: print("\033[1;31;45m[WARN] Galil connection failed\033[0m") print("\033[1;31;45m[WARN] Stopping Galil script\033[0m") sys.exit() g.GCommand('ST') #stop motion g.GCommand('MO') #motor g.GCommand('DP 0,0,0,0,0,0') #set main encoder position as 0 g.GCommand( 'DE 0,0,0,0,0,0' ) #set dual encoder position as 0, for stepper motor mode, need set DE as 0 for homing g.GClose()
def zero_rotary_motor(): g = gclib.py() c = g.GCommand g.GOpen('172.25.100.168 --direct') print(' Attempting to zero the rotary motor now, sudden error or break in code expected') print(' Rerun motor_movement.py to continue') # zero = rotary_set_zero() # while (zero > 10) and (zero < 16374): # zero = rotary_set_zero() b = False move = 25000 c('AB') c('MO') c('SHD') c('SPD=50000') c('ACD=300000') c('BCD=300000') print(' Starting move...') try: while True: c('PRD={}'.format(move)) c('BGD') #begin motion g.GMotionComplete('D') enc_pos = rotary_read_pos() print(f"encoder position: {enc_pos}") if b == False: if (enc_pos > 8092) and (enc_pos < 8292): print(' encoder position good, continuing') theta = enc_pos * 360 / 2**14 print(theta, ' compared with 180') else: print(' WARNING: Motor did not move designated counts, aborting move') g.GClose() exit() if b == True: if (enc_pos < 100) or (enc_pos > 16284): print(' encoder position good, continuing') theta = enc_pos * 360 / 2**14 print(theta, ' compared with 0 or 360') else: print(' WARNING1: Motor did not move designated counts, aborting move') g.GClose() exit() b = not b except gclib.GclibError: print('Rotary stage is zeroed') g.GClose()
def run_motion(mip, axis, mspd, n_steps): # must be global for multiprocessing to work. # connect to controller gp = gclib.py() gc = gp.GCommand try: gp.GOpen(f"{mip} --direct") except: print("ERROR: couldn't connect to Newmark controller!") # initial motor setup commands gc('AB') gc('MO') gc(f'SH{axis}') gc(f'SP{axis}={mspd}') gc(f'DP{axis}=0') gc(f'AC{axis}={mspd}') gc(f'BC{axis}={mspd}') # begin motion gc(f'PR{axis}={n_steps}') gc(f'BG{axis}') gp.GMotionComplete(axis) time.sleep(.1) print('i did a thing')
def __init__(self): self.config = load(open( os.path.join(os.path.dirname(os.path.realpath(__file__)), 'local_config.yaml'), 'rb'), Loader=Loader) self.g = gclib.py() self.open() self.x = 0 self.x_counts = 0 x_config = self.config['servos']['x'] self.x_motor = x_config['motor_name'] self.x_mm_per_count = x_config['pitch'] / x_config[ 'steps_per_revolution'] / x_config['step_down'] self.y = 0 self.y_counts = 0 y_config = self.config['servos']['y'] self.y_motor = y_config['motor_name'] self.y_mm_per_count = y_config['pitch'] / y_config[ 'steps_per_revolution'] / y_config['step_down'] self.z = 0 self.z_counts = 0 z_config = self.config['servos']['z'] self.z_motor = z_config['motor_name'] self.z_mm_per_count = z_config['pitch'] / z_config[ 'steps_per_revolution'] / z_config['step_down'] # the end effector is a voice coil not an stepper motor self.ef_motor = self.config['ef']['motor_name'] self.ef_up_voltage = self.config['ef']['up'] self.ef_down_voltage = self.config['ef']['down']
def position_publisher(): ################### Establish the connection to controller through Ethernet ############ g = gclib.py() g.GOpen('169.254.93.220 --direct') print(g.GInfo()) c = g.GCommand # alias the command callable ########## publisher ########### pub = rospy.Publisher('stage_pos', Float32MultiArray, queue_size=10) rospy.init_node('stage_position_node', anonymous=True) rate = rospy.Rate(100) # 100hz # data_msg = Int32MultiArray() data_msg = Float32MultiArray() # data_msg.layout.dim[0].size = 1 # data_msg.layout.dim[0].stride = 3 # data_msg.layout.dim[0].label = 'x,y,z' data_msg.data = [] while not rospy.is_shutdown(): pos_all = c('TP') pos = pos_all.split(',') # pos_x = c('TPA') # pos_y = c('TPB') # pos_z = c('TPC') data_msg.data = [ int(pos[0]) * ScaleLinearStage, int(pos[1]) * ScaleLinearStage, int(pos[2]) * ScaleRotaryStageEncoder ] pub.publish(data_msg) rate.sleep()
def emergency_stop(motor_name, mconf, ipconf): """ called by move_motor. must be global for multiprocessing to work, and requires we set up a whole separate communication session (because this is called in an independent Python thread.) """ print('\nGot Emergency Stop signal! Attempting to stop motion ...') mip = ipconf['newmark'] axis = mconf[motor_name]['axis'] # connect to controller gp = gclib.py() gc = gp.GCommand try: gp.GOpen(f"{mip} --direct") except: print("ERROR: couldn't connect to Newmark controller!") # -- emergency stop signal -- res = gc(f'ST{axis}') success = res is not None print('Did we succeed at stopping the motion?', success) gp.GMotionComplete(axis) time.sleep(.1) print("WARNING: You've just used Emergency Stop. The motor may still be\n", " 'humming', i.e. powered but not moving. Sometimes this is\n", " audible, but not always. You can either try \n", " another (safe) motion to reset it, or reset the Newmark\n", " motor controller.")
def runMoveLoop(GC: gclib.py()): loopCount = int(input("How many loops would you like to run? ")) distance = float( input( "What distance would you like to index [mm]?\n(Max stroke is 18mm)\n" )) if ((distance > 18) or (distance < 0)): print('Invalid Distance. Exiting IKO Linear Motor Loop') return encoderDist = distance / 0.0001 # 0.1um accuracy encoder i = 0 try: print( '\nStarting Move Loop. Press Ctrl+C to exit loop after next move completes.\n' ) while (i < loopCount): GC.GCommand('PAD=%i' % encoderDist) GC.GCommand('BG D') GC.GMotionComplete('D') GC.GCommand('PAD=0') GC.GCommand('BG D') GC.GMotionComplete('D') print('Loop %i' % i) i += 1 except KeyboardInterrupt: print('Exiting loop - Keyboard interrupt\n') return print() return
def test_readout(): g = gclib.py() c = g.GCommand g.GOpen('172.25.100.168 --direct') print(type(g.GInfo())) print(g.GAddresses()) motor_name = "DMC2142sH2a"
def __init__(self): # if this is the main instance let us make a galil connection self.g = gclib.py() print('gclib version:', self.g.GVersion()) self.g.GOpen('%s --direct -s ALL' % (setupd['galil_ip_str'])) print(self.g.GInfo()) self.c = self.g.GCommand # alias the command callable self.cycle_lights = False
def __init__(self): self.software_version: str = '' self.software_title: str = '' self.ip_address: str = '' self.mer_ip_address: str = '' self.speed: str = '' self.speed_out: str = '' self._debug: bool = False self.connected: bool = False self.g = gclib.py()
def __init__(self, address=None, baud=None): '''Initializes a Galil Controller.''' self._g = gclib.py() # instance of gclib class self._g.lock = Lock() # insert a lock for thread safe interactions self.connected = False # connection flag if address is not None: self.open(address, baud) # open connection self.disable() # turn off motors
def __init__(self, ip_address=None, frequency=100, duration=2): QtCore.QThread.__init__(self) self.frequency = frequency self.duration = duration # Caller is responsible to make sure that ip address is ok self.galil_handle = gclib.py(); try: self.galil_handle.GOpen('%s --direct -s ALL' % ip_address) except gclib.GclibError: print("ERROR: recording thread uanble to connect to controller")
def main(): g = gclib.py() #make an instance of the gclib python class try: print('gclib version:', g.GVersion()) ########################################################################### # Network Utilities ########################################################################### ''' #Get Ethernet controllers requesting IP addresses print('Listening for controllers requesting IP addresses...') ip_requests = g.GIpRequests() for id in ip_requests.keys(): print(id, 'at mac', ip_requests[id]) #define a mapping of my hardware to ip addresses ips = {} ips['DMC4000-783'] = '192.168.0.42' ips['DMC4103-9998'] = '192.168.0.43' for id in ips.keys(): if id in ip_requests: #if our controller needs an IP print("\nAssigning", ips[id], "to", ip_requests[id]) g.GAssign(ips[id], ip_requests[id]) #send the mapping g.GOpen(ips[id] + ' --direct') #connect to it print(g.GInfo()) g.GCommand('BN') #burn the IP g.GClose() #disconnect print('\nAvailable addresses:') #print ready connections available = g.GAddresses() for a in sorted(available.keys()): print(a, available[a]) print('\n') ''' ########################################################################### # Connect ########################################################################### g.GOpen('192.168.42.100 --direct -s ALL') #g.GOpen('COM1 --direct') print(g.GInfo()) g.GCommand('AB') g.GCommand('MO') except gclib.GclibError as e: print('Unexpected GclibError:', e) finally: g.GClose() #don't forget to close connections! return
def _execute(self, command): try: g = gclib.py() g.GOpen(ADDRESS) g.timeout = 5000 val = g.GCommand(command) g.timeout = 5000 return val except gclib.GclibError as e: print('Unexpected GclibError:', e) finally: g.GClose()
def source_limit_check(): """ source motor only has one limit switch """ g = gclib.py() g.GOpen('172.25.100.168 --direct') # send the command (can check against GalilTools) status = int(float(g.GCommand('MG _LF A'))) # status = int(g.GCommand('MG _LR A')) # reverse isn't used label = "OFF" if status == 1 else "ON" print(f"Source motor limit switch: {label}")
def __init__(self, name: str, address: str, **kwargs: Any) -> None: """ Initializes and opens the connection to the Galil Motion Controller Args: name: name for the instrument address: address of the controller """ super().__init__(name=name, **kwargs) self.g = gclib.py() self._address = address self.open() self.connect_message()
def linear_limit_check(): """ linear motor has two limit switches """ g = gclib.py() c = g.GCommand g.GOpen('172.25.100.168 --direct') lf_status = float(c('MG _LF B')) label = "OFF" if lf_status == 1 else "ON" print(f"Linear motor forward limit switch: {label}") lr_status = float(c('MG _LR B')) label = "OFF" if lr_status == 1 else "ON" print(f"Linear motor reverse limit switch: {label}")
def create_connection(mock=False, log=None): """ Creates a connection to the galil. :param mock: Whether to create a mock connection (used for testing) :param log: The log to print any mock messages. :return: An instance of the galil connection object """ g = MockGalil(log) if mock else gclib.py() if not open_connection(g): raise IOError("Error, cannot communicate with galil") g.GCommand(CONFIGURE) return g
def stop_motion(mip, axis): # connect to controller gp = gclib.py() gc = gp.GCommand try: gp.GOpen(f"{mip} --direct") except: print("ERROR: couldn't connect to Newmark controller!") # -- emergency stop signal -- res = gc(f'ST{axis}') success = res is not None print('Did we succeed at stopping the motion?', success) gp.GMotionComplete(axis) time.sleep(.1)
def source_limit_check(): g = gclib.py() c = g.GCommand g.GOpen('172.25.100.168 --direct') lf_status = float(c('MG _LF C')) lr_status = float(c('MG _LR C')) if lf_status == 1: print('Forward switch, source motor: off') else: print('Forward switch, source motor: ON') if lr_status == 1: print('Reverse switch, source motor off') else: print('Reverse switch, source motor: ON')
def linear_limit_check(): g = gclib.py() c = g.GCommand g.GOpen('172.25.100.168 --direct') lf_status = float(c('MG _LF B')) lr_status = float(c('MG _LR B')) if lf_status == 1: print('Forward switch, linear stage: off') else: print('Forward switch, linear stage: ON') if lr_status == 1: print('Reverse switch, linear stage: off') else: print('Reverse switch, linear stage: ON')
def updateIP(GC: gclib.py(), newIPAddr: string, currentIPAddr: string): GC.GOpen(currentIPAddr + ' --direct') sendstring = 'IA %s' % newIPAddr sendstring = sendstring.replace('.', ',') try: GC.GCommand(sendstring) except gclib.GclibError as e: GC.GClose() print( 'exception caught, waiting for IP to update and attempting reconnect' ) time.sleep(5000) GC.GOpen(newIPAddr + ' --direct') GC.GCommand('BN') #burn the IP disconnectController(GC) #disconnect return newIPAddr
def __init__(self): super().__init__() self.handle = gclib.py() # Initialize the library object self.axes = ['x', 'y', 'z'] self.jogging = False self.jogSpeed = {} self.jogSpeed['x'] = 16785 # default speed 15 mm/s self.jogSpeed['y'] = 16785 self.jogSpeed['z'] = 16785 self.speed = {} self.speed['x'] = 20000 # YAML FILE self.speed['y'] = 20000 self.speed['z'] = 20000 self.xCal = 10 # YAML FILE
def main(): g = gclib.py() try: print('gclib version:', g.GVersion()) g.GOpen('192.168.0.155 --direct -s ALL') print(g.GInfo()) g.timeout = 300000 with open('dmc/merlin.dmc') as prog: lines = prog.read() #program = lines.replace("\n", ";") out = [] for l in lines.split('\n'): l = l.rstrip() #if not l: # l += '\'' if l: out.append(l + ';\r') #out.append('\\\r') print out # exit() g.GProgramDownload(''.join(out), '') print(' Uploaded program:\n%s' % g.GProgramUpload()) g.GCommand('XQ') g.GCommand('BP') g.GSleep(20) print g.GMessage() #g.GCommand('BP') #burn program #g.GSleep(10) #print g.GMessage() except gclib.GclibError as e: print('Unexpected GclibError:', e) finally: g.GClose() return
def Declare_Variable(): global Device Device = "FE-DI-XBPM-051" #Declare Variable for Motor Control global g g = gclib.py() global Galil_IP Galil_IP = "172.18.171.5" global SP,PR SP = 20000 PR = 12500 global DelayTime DelayTime=0.8 global Hori_flag, Vert_flag Hori_flag = 1 Vert_flag = 0 #down #Declare Array Size global ArraySize_Y,ArraySize_X ArraySize_X = 40 ArraySize_Y = 40 #Declare Scan Status Variable and Array global count_X, count_Y global Signal_Status count_X = 0 count_Y = 0 Signal_Status = np.zeros((ArraySize_Y,ArraySize_X)) #Declare EPICS Data Array global Signal_A, Signal_B, Signal_C, Signal_D global Signal_X, Signal_Y Signal_A = np.zeros((ArraySize_Y,ArraySize_X)) Signal_B = np.zeros((ArraySize_Y,ArraySize_X)) Signal_C = np.zeros((ArraySize_Y,ArraySize_X)) Signal_D = np.zeros((ArraySize_Y,ArraySize_X)) Signal_X = np.zeros((0)) Signal_Y = np.zeros((0))
def configureIKOLinear(GC: gclib.py()): GC.GCommand('STD') GC.GMotionComplete('D') GC.GCommand('MOD') GC.GCommand('BAD') GC.GCommand('AGD=0') GC.GCommand('AUD=8') GC.GCommand('BZD=2') GC.GCommand('TM=1000.0') GC.GCommand('KDD=60.0') GC.GCommand('KPD=5.0') GC.GCommand('KID=0.05') GC.GCommand('TLD=5.0') # GC.GCommand('ERD=20000.0') # Set position error limit GC.GCommand('OED=0') # Disable "MO on Position Error Exceeded" GC.GCommand('SPD=100000.0') GC.GCommand('ACD=150000.0') GC.GCommand('DCD=150000.0')
def __init__(self, ip='10.10.1.12'): self.Galil = gclib.py() self.Galil.GOpen(ip + ' --direct -s ALL') self.CurrentPosition = {} self.AxisKeys = {'X': 'A', 'Y': 'B', 'Z': 'C', 'Rotation': 'D'} for k in list(self.AxisKeys.keys()): self.ZeroEncoder(k) self.StepsPerMeasure = { 'X': 1000., 'Y': 801.721016, 'Z': 1000., 'Rotation': 160. * 1000. / 360. }
def test_program(): g = gclib.py() c = g.GCommand g.GOpen('172.25.100.168 --direct') zero = set_zero() while (zero > 10) and (zero < 16374): zero = set_zero() angle = float( input( ' How many degrees would you like to rotate source motor?\n -->')) cts = angle / 360 * 50000 ratio1 = cts / 50000 c('AB') c('MO') c('SHC') c('SPC=5000') c('DPC=0') c('PRC={}'.format(cts)) c('ACC=5000') c('BCC=5000') print(' Starting move...') c('BGC') #begin motion g.GMotionComplete('C') print(' done.') print(' Checking position...') enc_pos = read_pos() ratio2 = enc_pos / (2**14) print(ratio1, '\n', ratio2) if (ratio2 < .95 * ratio1) or (ratio2 > 1.05 * ratio1): print(' WARNING: Motor did not move designated counts') else: print('Motor moved designated counts') del c #delete the alias g.GClose()
def __init__(self,servostatus='OFF'): #set default ip address here ip_address = device_ip.galil_ip # make an instance of the gclib python class self.g = gclib.py() print('gclib version:', self.g.GVersion()) #Connection of galil card through ip address try: self.g.GOpen(ip_address + ' --direct -s ALL') # self.g.GOpen('COM1 --direct') print(self.g.GInfo()) except: print("\033[1;31;45m[WARN] Galil connection failed\033[0m") print("\033[1;31;45m[WARN] Stopping Galil script\033[0m") sys.exit() if(servostatus == 'ON'): #load motors configuration galil_config.galil_config(self.g) self.g.GCommand('SH') #servo on print("Motor servos are on!")
def center_source_motor(): zero = source_set_zero() while (zero > 10) and (zero < 16374): zero = source_set_zero() print(' Centering source beam, normal to the detector surface.') g = gclib.py() c = g.GCommand g.GOpen('172.25.100.168 --direct') b = False move = 25000 c('AB') c('MO') c('SHC') c('SPC=5000') c('ACC=5000') c('BCC=5000') print(' Starting move...') c('PRC={}'.format(move)) c('BGC') #begin motion g.GMotionComplete('C') print(' encoder check') enc_pos = source_read_pos() if (enc_pos > 8092) and (enc_pos < 8292): print(' encoder position good, beam centered') theta = enc_pos * 360 / 2**14 print(theta, ' compared with 180') else: print(' WARNING: Motor did not move designated counts, aborting move') del c #delete the alias g.GClose() exit() del c #delete the alias