// Disconnects from the Pololu Maestro servo controller. // Based on the 'TryToDisconnect' method from MaestroAdvancedExample in the pololu-usb-sdk. public void DisconnectFromHardware() { lock (uscLock) { if (uscDevice == null) { // Already disconnected return; } try { uscDevice.Dispose(); // Disconnect } catch (Exception ex) { ErrorLogging.AddMessage(ErrorLogging.LoggingLevel.Error, "DisconnectFromHardware failed to cleaning disconnect the servo hardware: " + ex.Message); } finally { // do this no matter what uscDevice = null; } } }
private void updateStatus() { if (owner == null) { return; } Device = null; if (string.IsNullOrWhiteSpace(SerialNumber)) { Error = null; } else { DeviceListItem availablePololuMaestro = PololuMaestroEnumerator.Singleton.AvailablePololuMaestroList.FirstOrDefault(item => item.serialNumber == SerialNumber); if (availablePololuMaestro == null) { Error = Translations.Main.PololuMaestroNotFoundError; } else { try { Device = new Usc(availablePololuMaestro); Error = null; } catch (Exception e) { Error = e.Message; } } } }
public void ConnectHardware() { if (usbdevice == null) { usbdevice = connectToDevice(); } }
// function for evaluating a text file program for the motors public static void runScript(Usc usc, string fileName) { //Getting program text from text file string text = new StreamReader(fileName).ReadToEnd(); MessageBox.Show(text); BytecodeProgram program = BytecodeReader.Read(text, usc.servoCount != 6); BytecodeReader.WriteListing(program, fileName + ".lst"); // Stops any previous scripts that are running usc.setScriptDone(1); // ??? usc.eraseScript(); List <byte> byteList = program.getByteList(); if (byteList.Count > usc.maxScriptLength) { MessageBox.Show("Script too long for device (" + byteList.Count + " bytes)"); } if (byteList.Count < usc.maxScriptLength) { byteList.Add((byte)Opcode.QUIT); } // Setting up subroutines usc.setSubroutines(program.subroutineAddresses, program.subroutineCommands); // Loading the bytes usc.writeScript(byteList); // Restarting usc.reinitialize(); }
private void BtnEditarMoto_Click(object sender, RoutedEventArgs e) { try { Moto moto = new Moto(); if (ValidaCamposEmBranco()) { moto.Placa = Parameter; moto = (Moto)VeiculoDAO.Get(null, moto); moto.Nome = txtNome.Text; moto.Cor = txtCor.Text; moto.Modelo = txtModelo.Text; moto.Status = txtStatus.Text; moto.ValorPorDia = Convert.ToDouble(txtValorPorDia.Text); moto.ValorPorHora = Convert.ToDouble(txtValorPorHora.Text); VeiculoDAO.AlterarDadosVeiculo(null, moto); MessageBox.Show("Dados alterados com sucesso!!", "", MessageBoxButton.OK, MessageBoxImage.Information); LimparCampos(); Usc.ListarMoto(); Close(); } else { MessageBox.Show("Favor preencher as informações!", "Mensagem", MessageBoxButton.OK, MessageBoxImage.Error); } } catch (Exception ex) { MessageBox.Show(ex.ToString(), "LocadoraWPF", MessageBoxButton.OK, MessageBoxImage.Error); } }
/// <summary> /// Attempts to disconnect /// </summary> public void TryToDisconnect() { if (usc == null) { //Log("Connecting stopped."); return; } try { //Log("Disconnecting..."); usc.Dispose(); // Disconnect } catch (Exception e) { //Log(e); //Log("Failed to disconnect cleanly."); } finally { // do this no matter what usc = null; //Log("Disconnected from #" + SerialNumberTextBox.Text + "."); } }
/// <summary> /// Connects to a Maestro using native USB and returns the Usc object /// representing that connection. When you are done with the /// connection, you should close it using the Dispose() method so that /// other processes or functions can connect to the device later. The /// "using" statement can do this automatically for you. /// </summary> private Usc connectToDevice(int index) { // Get a list of all connected devices of this type. List <DeviceListItem> connectedDevices = Usc.getConnectedDevices(); connectedDevices.Sort(deviceComparer); // we must have all three devices online, or we will be commanding a wrong device. if (connectedDevices.Count() != 3) { throw new Exception("Not all Pololu devices are online - found " + connectedDevices.Count() + " expected 3"); } DeviceListItem dli = connectedDevices[index]; //foreach (DeviceListItem dli in connectedDevices) { // If you have multiple devices connected and want to select a particular // device by serial number, you could simply add a line like this: // if (dli.serialNumber != "00012345"){ continue; } Usc device = new Usc(dli); // Connect to the device. return(device); // Return the device. } throw new Exception("Could not find Pololu device.\r\nMake sure it's plugged into USB\r\nCheck your Device Manager.\r\nPololu Mini Maestro 12 needed."); }
private void TrySetTarget(List <ChannelValuePair> channelValues) { try { var groupedByDevice = from a in channelValues group a by a.Channel / CHANNELS_PER_DEVICE into g select new { deviceIndex = g.Key, deviceChannelValues = g }; foreach (var devGrp in groupedByDevice) { using (Usc device = connectToDevice(devGrp.deviceIndex)) // Find a device and temporarily connect. { foreach (ChannelValuePair cvp in devGrp.deviceChannelValues) { byte channel = (byte)(cvp.Channel % CHANNELS_PER_DEVICE); //Console.WriteLine(" (m) device: {0} channel: {1} target: {2}", device.getSerialNumber(), channel, cvp.Target); device.setTarget(channel, cvp.Target); } // device.Dispose() is called automatically when the "using" block ends, // allowing other functions and processes to use the device. } } } catch (Exception exception) // Handle exceptions by displaying them to the user. { Console.WriteLine(exception); } }
private void outputShow() { //make textblocks visible outempName.Visibility = Visibility.Visible; outpayeeName.Visibility = Visibility.Visible; outDate.Visibility = Visibility.Visible; outAddress.Visibility = Visibility.Visible; outWage.Visibility = Visibility.Visible; outPaye.Visibility = Visibility.Visible; outPrsi.Visibility = Visibility.Visible; outUsc.Visibility = Visibility.Visible; outNet.Visibility = Visibility.Visible; savepayslip.Visibility = Visibility.Visible; //output text to textblocks outempName.Text = (Localization.Get("outempName")).ToString() + empname.ToString(); outpayeeName.Text = (Localization.Get("outpayeeName")) + payeename.ToString(); outDate.Text = (Localization.Get("outDate")) + date.ToString(); outAddress.Text = (Localization.Get("outAddress")) + payeeaddress.ToString(); outWage.Text = (Localization.Get("outWage")) + wage.ToString("$0.00"); outPaye.Text = (Localization.Get("outPaye")) + Paye.ToString("$0.00"); outPrsi.Text = (Localization.Get("outPrsi")) + Prsi.ToString("$0.00"); outUsc.Text = (Localization.Get("outUsc")) + Usc.ToString("$0.00"); outNet.Text = (Localization.Get("outNet")) + netpay.ToString("$0.00"); }
// Connects to the Pololu Maestro servo controller through USB. Only one controller is // currently expected, so this method just connects to the first controller it sees. // Based on the 'connectToDevice' method from MaestroEasyExample in the pololu-usb-sdk. public void ConnectToHardware() { try { DisconnectFromHardware(); // Get a list of all connected devices of this type. List <DeviceListItem> connectedDevices = Usc.getConnectedDevices(); foreach (DeviceListItem dli in connectedDevices) { // If you have multiple devices connected and want to select a particular // device by serial number, you could simply add a line like this: // if (dli.serialNumber != "00012345"){ continue; } uscDevice = new Usc(dli); // Connect to the device. break; // Use first device (should only be one, anyway). } if (uscDevice == null) { ErrorLogging.AddMessage(ErrorLogging.LoggingLevel.Error, "ConnectToHardware() failed, no servo hardware found."); } else { ErrorLogging.AddMessage(ErrorLogging.LoggingLevel.Info, "ConnectToHardware() succeeded, connected to servo hardware."); } InitializeHardware(); } catch (System.Exception ex) { ErrorLogging.AddMessage(ErrorLogging.LoggingLevel.Error, "Caught exception in Initialize(): " + ex.Message); } }
/// <summary> /// Update all Servo Positions /// </summary> public static void UpdateServos() { if (!PWM.ImmediateMode) { Usc.SetAllChannels(channels); } }
public int TryGetTarget(Byte channel) { int ret = 0; try { int index = channel / ServoChannelMap.CHANNELS_PER_DEVICE; channel = (byte)(channel % ServoChannelMap.CHANNELS_PER_DEVICE); using (Usc device = connectToDevice(index)) // Find a device and temporarily connect. { ServoStatus[] servos; device.getVariables(out servos); ret = servos[channel].position; // device.Dispose() is called automatically when the "using" block ends, // allowing other functions and processes to use the device. } } catch (Exception exception) // Handle exceptions by displaying them to the user. { Console.WriteLine(exception); } return(ret); }
static void program(Usc usc, string filename) { string text = (new StreamReader(filename)).ReadToEnd(); BytecodeProgram program = BytecodeReader.Read(text, usc.servoCount != 6); BytecodeReader.WriteListing(program, filename + ".lst"); usc.setScriptDone(1); usc.eraseScript(); List <byte> byteList = program.getByteList(); if (byteList.Count > usc.maxScriptLength) { throw new Exception("Script too long for device (" + byteList.Count + " bytes)"); } if (byteList.Count < usc.maxScriptLength) { byteList.Add((byte)Opcode.QUIT); } System.Console.WriteLine("Setting up subroutines..."); usc.setSubroutines(program.subroutineAddresses, program.subroutineCommands); System.Console.WriteLine("Loading " + byteList.Count + " bytes..."); usc.writeScript(byteList); System.Console.WriteLine("Restarting..."); usc.reinitialize(); }
static unsafe void displayStatus(Usc usc) { MaestroVariables variables; ServoStatus[] servos; short[] stack; ushort[] call_stack; usc.getVariables(out variables, out stack, out call_stack, out servos); Console.WriteLine(" # target speed accel pos"); for (int i = 0; i < usc.servoCount; i++) { Console.WriteLine("{0,2}{1,8}{2,8}{3,8}{4,8}", i, servos[i].target, servos[i].speed, servos[i].acceleration, servos[i].position); } Console.Write("errors: 0x"+variables.errors.ToString("X4")); foreach (var error in Enum.GetValues(typeof(uscError))) { if((variables.errors & (1<<(int)(uscError)error)) != 0) { Console.Write(" "+error.ToString()); } } usc.clearErrors(); Console.WriteLine(); // end the line if(variables.scriptDone == 0) Console.WriteLine("SCRIPT RUNNING"); else Console.WriteLine("SCRIPT DONE"); Console.WriteLine("program counter: "+variables.programCounter.ToString()); Console.Write("stack: "); for (int i = 0; i < variables.stackPointer; i++) { if(i > stack.Length) { Console.Write(" OVERFLOW (stack pointer = "+variables.stackPointer+")"); break; } Console.Write(stack[i].ToString().PadLeft(8, ' ')); } Console.WriteLine(); Console.Write("call stack: "); for (int i = 0; i < variables.callStackPointer; i++) { if(i > call_stack.Length) { Console.Write(" OVERFLOW (call stack pointer = "+variables.callStackPointer+")"); break; } Console.Write(call_stack[i].ToString().PadLeft(8, ' ')); } Console.WriteLine(); }
static void getConf(Usc usc, string filename) { Stream file = File.Open(filename, FileMode.Create); StreamWriter sw = new StreamWriter(file); ConfigurationFile.save(usc.getUscSettings(), sw); sw.Close(); file.Close(); }
public static void Main(string[] args) { LCM.LCM.LCM myLCM = null; try { Console.WriteLine("Starting Maestro driver..."); myLCM = new LCM.LCM.LCM("udpm://239.255.76.67:7667?ttl=1"); Console.WriteLine("LCM Connected!"); } catch (Exception ex) { Console.Error.WriteLine("Ex: " + ex); Environment.Exit(1); } List <DeviceListItem> connectedDevices = Usc.getConnectedDevices(); Console.WriteLine("Number of MicroMaestros detected=" + connectedDevices.Count); GoalFlags[] goals = new GoalFlags[4]; Dictionary <string, int> goalIDs = new Dictionary <string, int>(); goalIDs.Add("00032615", 3); //D goalIDs.Add("00031531", 2); //C goalIDs.Add("00032614", 1); //B goalIDs.Add("00032598", 0); //A foreach (DeviceListItem dli in connectedDevices) { Console.WriteLine( "Detected Maestro: {serialNumber=" + dli.serialNumber + ", text=" + dli.text + "}"); goals[goalIDs[dli.serialNumber]] = new GoalFlags(new Usc(dli)); } CubeRouteField field = new CubeRouteField(goals); foreach (GoalFlags flags in goals) { for (int i = 0; i < 5; i++) { flags.setFlagPosition(i, 0); } } // GoalLightsConnection conn = new GoalLightsConnection(null, "127.0.0.1", 9001, 9000); GoalFlagsConnection conn = new GoalFlagsConnection(myLCM, field); Console.WriteLine("Running..."); conn.Run(); }
static void configure(Usc usc, string filename) { Stream file = File.Open(filename, FileMode.Open); StreamReader sr = new StreamReader(file); List<String> warnings = new List<string>(); UscSettings settings = ConfigurationFile.load(sr, warnings); usc.fixSettings(settings, warnings); usc.setUscSettings(settings, true); sr.Close(); file.Close(); usc.reinitialize(); }
/// <summary> /// Connects to the device if it is found in the device list. /// </summary> public void TryToReconnect() { foreach (DeviceListItem d in Usc.getConnectedDevices()) { if (d.serialNumber == serialNumber) { usc = new Usc(d); //Log("Connected to #" + SerialNumberTextBox.Text + "."); return; } } }
// This function is called when the device connections need to be updated. public static void UpdateDeviceConnections() { // Start by removing any previous connections. disconnectDevices(); // Preparing a list of all of the currently connected devices. List <DeviceListItem> listOfJrks = Jrk.getConnectedDevices(); List <DeviceListItem> listOfMaestros = Usc.getConnectedDevices(); // Store the number of connected devices in these public // variables for use throughout all classes. NumOfConnectedJrks = listOfJrks.Count; NumOfConnectedMaestros = listOfMaestros.Count; // Attempting to connect to all available devices. if (NumOfConnectedMaestros > 0) { item1 = listOfMaestros[0]; usc = new Usc(item1); } else { MessageBox.Show("There are no Maestros connected, so no operations can be done. Please connect to a Maestro and try again."); return; } if (NumOfConnectedJrks > 0) { item = listOfJrks[0]; Jrk1 = new Jrk(item); } else { MessageBox.Show("There are no Jrks connected, so no operations can be done. Please connect to a Jrk and try again."); return; } if (NumOfConnectedJrks > 1) { item = listOfJrks[1]; Jrk2 = new Jrk(item); } if (NumOfConnectedJrks > 2) { item = listOfJrks[2]; Jrk3 = new Jrk(item); } if (NumOfConnectedJrks > 3) { item = listOfJrks[3]; Jrk4 = new Jrk(item); } }
static void configure(Usc usc, string filename) { Stream file = File.Open(filename, FileMode.Open); StreamReader sr = new StreamReader(file); List <String> warnings = new List <string>(); UscSettings settings = ConfigurationFile.load(sr, warnings); usc.fixSettings(settings, warnings); usc.setUscSettings(settings, true); sr.Close(); file.Close(); usc.reinitialize(); }
/// <summary> /// Get the serial number of the first connected Maestro, since this is /// probably what you want to connect to. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MainWindow_Shown(object sender, EventArgs e) { var device_list = Usc.getConnectedDevices(); if (device_list.Count > 0) { SerialNumberTextBox.Text = device_list[0].serialNumber; ConnectButton.Focus(); } else { SerialNumberTextBox.Focus(); } }
/// <summary> /// Attempts to set the target (width of pulses sent) of a channel. /// </summary> /// <param name="channel">Channel number from 0 to 23.</param> /// <param name="target"> /// Target, in units of quarter microseconds. For typical servos, /// 6000 is neutral and the acceptable range is 4000-8000. /// </param> void TrySetTarget(Byte channel, UInt16 target) { try { using (Usc device = connectToDevice()) // Find a device and temporarily connect. { device.setTarget(channel, target); // device.Dispose() is called automatically when the "using" block ends, // allowing other functions and processes to use the device. } } catch (Exception exception) // Handle exceptions by displaying them to the user. { displayException(exception); } }
/// <summary> /// Connects to a Maestro using native USB and returns the Usc object /// representing that connection. When you are done with the /// connection, you should close it using the Dispose() method so that /// other processes or functions can connect to the device later. The /// "using" statement can do this automatically for you. /// </summary> Usc connectToDevice() { // Get a list of all connected devices of this type. List <DeviceListItem> connectedDevices = Usc.getConnectedDevices(); foreach (DeviceListItem dli in connectedDevices) { // If you have multiple devices connected and want to select a particular // device by serial number, you could simply add a line like this: // if (dli.serialNumber != "00012345"){ continue; } Usc device = new Usc(dli); // Connect to the device. return(device); // Return the device. } throw new Exception("Could not find device. Make sure it is plugged in to USB " + "and check your Device Manager (Windows) or run lsusb (Linux)."); }
/// <summary> /// Attempts to set the target (width of pulses sent) of a channel. /// </summary> /// <param name="channel">Channel number from 0 to 23.</param> /// <param name="target"> /// Target, in units of quarter microseconds. For typical servos, /// 6000 is neutral and the acceptable range is 4000-8000. /// </param> void TrySetTarget(Byte channel, int target) { try { // using () // Find a device and temporarily connect. { try{ //Console.WriteLine(this.Name+" Target :"+target*4); if ((target * 4) < UInt16.MaxValue) { //Console.WriteLine("Servo:"+channel+" target:"+target) channels[channel] = Convert.ToUInt16(target * 4); //usbdevice.SetAllChannels(channels); if (ImmediateMode) { if (usbdevice == null) { connectToDevice(); } Console.WriteLine("immediate Set"); usbdevice.setTarget(channel, Convert.ToUInt16(target * 4)); } } else { Console.WriteLine("Invalid Target: " + target + " for Channel: " + this.channel); } }catch (Exception ex) { Console.WriteLine("Invalid Target " + target + ex.Message + ex.StackTrace.ToString()); usbdevice.disconnect(); usbdevice = null; connectToDevice(); } // Console.WriteLine("Servo: "+channel+" mit wert "+target); // device.Dispose() is called automatically when the "using" block ends, // allowing other functions and processes to use the device. } } catch (Exception exception) // Handle exceptions by displaying them to the user. { Console.WriteLine(exception.Message + "\n" + exception.StackTrace.ToString()); // displayException(exception); } }
static void listDevices() { List <DeviceListItem> list = Usc.getConnectedDevices(); if (list.Count == 1) { Console.WriteLine("1 " + Usc.englishName + " device found:"); } else { Console.WriteLine(list.Count + " " + Usc.englishName + " devices found:"); } foreach (DeviceListItem item in list) { Console.WriteLine(item.text); } }
/// <summary> /// Connects to a Maestro using native USB and returns the Usc object /// representing that connection. When you are done with the /// connection, you should close it using the Dispose() method so that /// other processes or functions can connect to the device later. The /// "using" statement can do this automatically for you. /// </summary> void connectToDevice() { try{ // Get a list of all connected devices of this type. if (usbdevice == null) { List <DeviceListItem> connectedDevices = Usc.getConnectedDevices(); foreach (DeviceListItem dli in connectedDevices) { if ((device == null))//|| (this.device == dli.serialNumber) { // If you have multiple devices connected and want to select a particular // device by serial number, you could simply add a line like this: // if (dli.serialNumber != "00012345"){ continue; } Usc uscdevice = new Usc(dli); // Connect to the device. usbdevice = uscdevice; // Return the device. } } } if (usbdevice != null) { usbdevice.clearErrors(); var settings = usbdevice.getUscSettings(); settings.channelSettings[channel].mode = ChannelMode.Servo; Console.WriteLine("Set Startup Position Servo " + channel + " to " + settings.channelSettings[channel].home); settings.servoPeriod = 20; usbdevice.setUscSettings(settings, false); // usbdevice.setAcceleration(channel, 0); usbdevice.setSpeed(channel, 0); } else { throw new Exception("Could not find device. Make sure it is plugged in to USB " + "and check your Device Manager (Windows) or run lsusb (Linux)."); } }catch (Exception ex) { Console.WriteLine("Fehler beim Verbinden mit dem Servo " + ex.Message + ex.StackTrace.ToString()); } }
public static void Main(string[] args) { Usched req = new Usc(); UschedEntry[] result; req.SetHostname("192.168.1.1"); req.SetPort("7600"); req.SetUsername("win32user"); req.SetPassword("win32password"); req.Request("show all"); result = req.ResultShow(); /* Print some results */ for (int i = 0; i < result.Length; i ++) { Console.WriteLine("ID: " + result[i].Id.ToString("X") + ", Command: " + result[i].Command); } }
/// <summary> /// Connects to a Maestro using native USB and returns the Usc object /// representing that connection. When you are done with the /// connection, you should close it using the Dispose() method so that /// other processes or functions can connect to the device later. The /// "using" statement can do this automatically for you. /// </summary> public Usc connectToDevice(int index) { // Get a list of all connected devices of this type. List <DeviceListItem> connectedDevices = Usc.getConnectedDevices(); connectedDevices.Sort(deviceComparer); DeviceListItem dli = connectedDevices[index]; //foreach (DeviceListItem dli in connectedDevices) { // If you have multiple devices connected and want to select a particular // device by serial number, you could simply add a line like this: // if (dli.serialNumber != "00012345"){ continue; } Usc device = new Usc(dli); // Connect to the device. return(device); // Return the device. } throw new Exception("Could not find Pololu device.\r\nMake sure it's plugged into USB\r\nCheck your Device Manager.\r\nPololu Mini Maestro 12 needed."); }
public static void Main(string[] args) { Usched req = new Usc(); UschedEntry[] result; req.SetHostname("192.168.1.1"); req.SetPort("7600"); req.SetUsername("win32user"); req.SetPassword("win32password"); req.Request("show all"); result = req.ResultShow(); /* Print some results */ for (int i = 0; i < result.Length; i++) { Console.WriteLine("ID: " + result[i].Id.ToString("X") + ", Command: " + result[i].Command); } }
/// <summary> /// This function will be called once every 100 ms to do an update. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void UpdateTimer_Tick(object sender, EventArgs e) { if (usc == null) { // Display a message in the position box PositionTextBox.Text = "(disconnected)"; // Try connecting to a device. try { TryToReconnect(); } catch (Exception e2) { Log(e2); Log("Failed connecting to #" + SerialNumberTextBox.Text + "."); usc = null; } } else { // Update the GUI and the device. try { DisplayPosition(); if (ActivateCheckBox.Checked) { RunSequence(); } } catch (Exception e2) { // If any exception occurs, log it, set usc to null, and keep trying.. Log(e2); Log("Disconnected from #" + SerialNumberTextBox.Text + "."); usc = null; } } }
/// <summary> /// Attempts to set the target (width of pulses sent) of a channel. /// </summary> /// <param name="channel">Channel number - from 0 to 23.</param> /// <param name="target"> /// Target, in units of quarter microseconds. For typical servos, /// 6000 is neutral and the acceptable range is 4000-8000. /// A good servo will take 880 to 2200 us (3520 to 8800 in quarters) /// </param> private void TrySetTarget(Byte channel, UInt16 target) { try { int index = channel / CHANNELS_PER_DEVICE; channel = (byte)(channel % CHANNELS_PER_DEVICE); using (Usc device = connectToDevice(index)) // Find a device and temporarily connect. { //Console.WriteLine(" (s) device: {0} channel: {1} target: {2}", device.getSerialNumber(), channel, target); device.setTarget(channel, target); // device.Dispose() is called automatically when the "using" block ends, // allowing other functions and processes to use the device. } } catch (Exception exception) // Handle exceptions by displaying them to the user. { Console.WriteLine(exception); } }
public GoalFlags(Usc maestro) { this.maestro = maestro; }
static void Main(string[] args) { CommandOptions opts = new CommandOptions(Assembly.GetExecutingAssembly().GetName()+"\n"+ "Select one of the following actions:\n"+ " --list list available devices\n"+ " --configure FILE load configuration file into device\n"+ " --getconf FILE read device settings and write configuration file\n"+ " --restoredefaults restore factory settings\n"+ " --program FILE compile and load bytecode program\n"+ " --status display complete device status\n"+ " --bootloader put device into bootloader (firmware upgrade) mode\n"+ " --stop stops the script running on the device\n"+ " --start starts the script running on the device\n"+ " --restart restarts the script at the beginning\n"+ " --step runs a single instruction of the script\n"+ " --sub NUM calls subroutine n (can be hex or decimal)\n"+ " --sub NUM,PARAMETER calls subroutine n with a parameter (hex or decimal)\n"+ " placed on the stack\n"+ " --servo NUM,TARGET sets the target of servo NUM in units of\n" + " 1/4 microsecond\n"+ " --speed NUM,SPEED sets the speed limit of servo NUM\n"+ " --accel NUM,ACCEL sets the acceleration of servo NUM to a value 0-255\n"+ "Select which device to perform the action on (optional):\n"+ " --device 00001430 (optional) select device #00001430\n", args); if (opts["list"] != null) { if (opts.Count > 1) opts.error(); listDevices(); return; } if (opts.Count == 0) opts.error(); // otherwise, they must connect to a device List<DeviceListItem> list = Usc.getConnectedDevices(); if (list.Count == 0) { System.Console.WriteLine("No " + Usc.englishName + " devices found."); return; } DeviceListItem item = null; // see if the device they specified was in the list if (opts["device"] == null) { // Conenct to the first item in the list. item = list[0]; } else { // Remove the leading # sign. It is not standard to put it there, // but if someone writes it, the program should still work. string check_serial_number = opts["device"].TrimStart('#'); // Find the device with the specified serial number. foreach (DeviceListItem check_item in list) { if (check_item.serialNumber == check_serial_number) { item = check_item; break; } } if (item == null) { Console.WriteLine("Could not find a " + Usc.englishName + " device with serial number " + opts["device"] + "."); Console.WriteLine("To list devices, use the --list option."); return; } } Usc usc = new Usc(item); if (opts["bootloader"] != null) { if (opts.Count > 2) opts.error(); usc.startBootloader(); return; } else if (opts["status"] != null) { if (opts["status"] != "") opts.error(); displayStatus(usc); } else if (opts["getconf"] != null) { getConf(usc, opts["getconf"]); } else if (opts["configure"] != null) { configure(usc, opts["configure"]); } else if (opts["restoredefaults"] != null) { if (opts["restoredefaults"] != "") opts.error(); restoreDefaultConfiguration(usc); } else if (opts["program"] != null) { program(usc, opts["program"]); } else if (opts["stop"] != null) { setScriptDone(usc, 1); } else if (opts["start"] != null) { setScriptDone(usc, 0); } else if (opts["restart"] != null) { System.Console.Write("Restarting script..."); usc.restartScript(); usc.setScriptDone(0); System.Console.WriteLine(""); } else if (opts["step"] != null) { setScriptDone(usc, 2); } else if (opts["servo"] != null) { string[] parts = opts["servo"].Split(','); if(parts.Length != 2) opts.error("Wrong number of commas in the argument to servo."); byte servo=0; ushort target=0; try { servo = byte.Parse(parts[0]); target = ushort.Parse(parts[1]); } catch(FormatException) { opts.error(); } Console.Write("Setting target of servo "+servo+" to "+target+"..."); usc.setTarget(servo, target); Console.WriteLine(""); } else if (opts["speed"] != null) { string[] parts = opts["speed"].Split(','); if(parts.Length != 2) opts.error("Wrong number of commas in the argument to speed."); byte servo=0; ushort speed=0; try { servo = byte.Parse(parts[0]); speed = ushort.Parse(parts[1]); } catch(FormatException) { opts.error(); } Console.Write("Setting speed of servo "+servo+" to "+speed+"..."); usc.setSpeed(servo, speed); Console.WriteLine(""); } else if (opts["accel"] != null) { string[] parts = opts["accel"].Split(','); if(parts.Length != 2) opts.error("Wrong number of commas in the argument to accel."); byte servo=0; byte acceleration=0; try { servo = byte.Parse(parts[0]); acceleration = byte.Parse(parts[1]); } catch(FormatException) { opts.error(); } Console.Write("Setting acceleration of servo "+servo+" to "+acceleration+"..."); usc.setAcceleration(servo, acceleration); Console.WriteLine(""); } else if (opts["sub"] != null) { string[] parts = opts["sub"].Split(new char[] {','}); if(parts.Length > 2) opts.error("Too many commas in the argument to sub."); byte address=0; short parameter=0; try { if(parts[0].StartsWith("0x")) address = byte.Parse(parts[0].Substring(2),System.Globalization.NumberStyles.AllowHexSpecifier); else address = byte.Parse(parts[0]); } catch(FormatException) { opts.error(); } if(parts.Length == 2) { try { if(parts[1].StartsWith("0x")) parameter = short.Parse(parts[1].Substring(2),System.Globalization.NumberStyles.AllowHexSpecifier); else parameter = short.Parse(parts[1]); } catch(FormatException) { opts.error(); } Console.Write("Restarting at subroutine "+address+" with parameter "+parameter+"..."); usc.restartScriptAtSubroutineWithParameter(address, parameter); usc.setScriptDone(0); } else { Console.Write("Restarting at subroutine "+address+"..."); usc.restartScriptAtSubroutine(address); usc.setScriptDone(0); } Console.WriteLine(""); } else opts.error(); }
static void program(Usc usc, string filename) { string text = (new StreamReader(filename)).ReadToEnd(); BytecodeProgram program = BytecodeReader.Read(text, usc.servoCount != 6); BytecodeReader.WriteListing(program,filename+".lst"); usc.setScriptDone(1); usc.eraseScript(); List<byte> byteList = program.getByteList(); if (byteList.Count > usc.maxScriptLength) { throw new Exception("Script too long for device (" + byteList.Count + " bytes)"); } if (byteList.Count < usc.maxScriptLength) { byteList.Add((byte)Opcode.QUIT); } System.Console.WriteLine("Setting up subroutines..."); usc.setSubroutines(program.subroutineAddresses, program.subroutineCommands); System.Console.WriteLine("Loading "+byteList.Count+" bytes..."); usc.writeScript(byteList); System.Console.WriteLine("Restarting..."); usc.reinitialize(); }
static void restoreDefaultConfiguration(Usc usc) { Console.Write("Restoring default settings..."); usc.restoreDefaultConfiguration(); Console.WriteLine(""); }
static void setScriptDone(Usc usc, byte value) { Console.Write("Setting script state to "+value+"..."); usc.setScriptDone(value); Console.WriteLine(""); }
private void refreshAvailablePololuMaestroList() { AvailablePololuMaestroList.Clear(); AvailablePololuMaestroList.AddRange(Usc.getConnectedDevices()); }