/// <summary> /// Attempts to disconnect /// </summary> public void TryToDisconnect() { if (motor == null) { //Log("Connecting stopped."); return; } try { //Log("Disconnecting..."); motor.Dispose(); // Disconnect } catch (Exception e) { //Log(e); //Log("Failed to disconnect cleanly."); } finally { // do this no matter what motor = null; //Log("Disconnected from #" + SerialNumberTextBox.Text + "."); } }
private static ActionOnDevice laterSetSettings() { // Read the entire file before connecting to the device. String filename = nextArgument(); List <String> warnings = new List <string>(); SmcSettings settings = SettingsFile.load(filename, warnings); return(delegate(Smc device) { Smc.fixSettings(settings, warnings, device.productId, device.getFirmwareVersion()); // Handle any warnings. if (warnings.Count != 0) { Console.WriteLine("There were problems with the settings file:"); foreach (String warning in warnings) { Console.WriteLine(" " + warning); } if (forceOption) { Console.WriteLine("The -f option is selected, so the settings will be applied anyway."); } else { throw new Exception("Aborted because of problems with settings file.\n" + "Use the -f option to override and apply settings anyway."); } } device.setSmcSettings(settings); }); }
/// <summary> /// Connects to a device using native USB. Throws an exception if it fails. /// </summary> void Connect() { if (device != null) { // We are already connected. return; } // Get a list of all connected devices of this type. List <DeviceListItem> connectedDevices = Smc.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 != "39FF-7406-3054-3036-4923-0743"){ continue; } this.device = new Smc(dli); // Connect to the device. StatusLabel.Text = "Connected"; StatusLabel.ForeColor = SystemColors.ControlText; return; } 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)."); }
public static void startBootloader(Smc device) { Console.WriteLine("Entering bootloader mode..."); string serialNumber = device.getSerialNumber(); device.startBootloader(); device.Dispose(); Console.WriteLine("Waiting for bootloader to connect..."); int msElapsed = 0; while (true) { foreach (DeviceListItem dli in Smc.getConnectedBootloaders()) { if (dli.serialNumber.Replace("-", "") == serialNumber.Replace("-", "")) { Console.WriteLine("Successfully entered bootloader mode."); return; } } System.Threading.Thread.Sleep(20); msElapsed += 20; if (msElapsed > 8000) { throw new Exception("Failed to enter bootloader mode: timeout elapsed."); } } }
public override void onCreate(Bundle savedInstanceState) { base.onCreate(savedInstanceState); ContentView = R.layout.main; mSourceDevicePicker = (DevicePicker)FragmentManager.findFragmentById(R.id.sourcePicker); mSourceDevicePicker.DeviceType = SmcDevice.TYPE_PROVIDER; mSourceDevicePicker.DeviceSelectedListener = mSourceDevicePickerListener; mPlayerDevicePicker = (DevicePicker)FragmentManager.findFragmentById(R.id.playerPicker); //mPlayerDevicePicker.setDeviceType(SmcDevice.TYPE_IMAGEVIEWER); mPlayerDevicePicker.DeviceSelectedListener = mPlayerDevicePickerListener; mListView = (ListView)findViewById(R.id.listView); mListView.OnItemClickListener = this; mItemAdapter = new ItemAdapter(this); mListView.Adapter = mItemAdapter; mListView.OnItemLongClickListener = this; mItemStack = new Stack <SmcItem>(); mSmcLib = new Smc(); try { mSmcLib.initialize(BaseContext); } catch (SsdkUnsupportedException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); //TODO Handle exceptions. } }
public override void onCreate(Bundle savedInstanceState) { base.onCreate(savedInstanceState); ContentView = R.layout.video_player_layout; setupViewElements(); mSmcLib = new Smc(); try { mSmcLib.initialize(BaseContext); } catch (SsdkUnsupportedException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); //TODO Handle exceptions. } Log.d("media control lib version", mSmcLib.VersionName); // Prepares assets used by sample. extractAssets(); // Restores saved state, after e.g. rotating. if (savedInstanceState != null) { mState = new VideoPlayerState(savedInstanceState); } else { mState = new VideoPlayerState(); // Initializes state with built-in content. File storageDir = new File(Environment.ExternalStorageDirectory, ASSETS_SUBDIR); File video = new File(storageDir, VIDEO_FILE); File subtitles = new File(storageDir, SUBTITLES_FILE); // Gets media information (title, artist, cover) MediaScannerConnection.scanFile(ApplicationContext, new string[] { video.AbsolutePath }, null, this); Uri mediaUri = Uri.fromFile(video); Uri subtitlesUri = Uri.fromFile(subtitles); mState.mMediaUri = mediaUri; mState.mSubtitlesUri = subtitlesUri; mState.mTitle = "Sample album"; string path = mediaUri.Path; if (path != null && path.LastIndexOf(".", StringComparison.Ordinal) != -1) { string ext = path.Substring(path.LastIndexOf(".", StringComparison.Ordinal) + 1); mState.mMimeType = MimeTypeMap.Singleton.getMimeTypeFromExtension(ext); } } }
/// <summary> /// Connects to the device if it is found in the device list. /// </summary> public void TryToReconnect() { foreach (DeviceListItem d in Smc.getConnectedDevices()) { if (d.serialNumber == serialNumber) { motor = new Smc(d); return; } } throw new Exception("Cannot connect to the SMC Make sure it is plugged in to USB " + "and check your Device Manager (Windows)"); }
public static void printStatus(Smc device) { SmcVariables vars = device.getSmcVariables(); Console.WriteLine("Model: " + Smc.productIdToLongModelString(device.productId)); Console.WriteLine("Serial Number: " + device.getSerialNumber()); Console.WriteLine("Firmware Version: " + device.getFirmwareVersionString()); Console.WriteLine("Last Reset: " + device.getResetCause()); Console.WriteLine(); printErrors(vars.errorStatus, "Errors currently stopping motor"); printErrors(vars.errorOccurred, "Errors that occurred since last check"); printSerialErrors(vars.serialErrorOccurred, "Serial errors that occurred since last check"); printLimitStatus(vars.limitStatus, "Active limits"); Console.WriteLine(channelStatusFormat, "Channel", "Unlimited", "Raw", "Scaled"); printChannelStatus(vars.rc1, "RC 1"); printChannelStatus(vars.rc2, "RC 2"); printChannelStatus(vars.analog1, "Analog 1"); printChannelStatus(vars.analog2, "Analog 2"); Console.WriteLine(); Console.WriteLine("Current Speed: " + vars.speed); Console.WriteLine("Target Speed: " + vars.targetSpeed); Console.WriteLine("Brake Amount: " + (vars.brakeAmount == 0xFF ? "N/A" : vars.brakeAmount.ToString())); Console.WriteLine("VIN: " + vars.vinMv.ToString() + " mV"); Console.WriteLine("Temperature: " + Smc.temperatureToString(vars.temperature)); Console.WriteLine("RC Period: " + Smc.rcPeriodToString(vars.rcPeriod)); Console.WriteLine("Baud rate: " + (vars.baudRateRegister == 0 ? "N/A" : (Smc.convertBaudRegisterToBps(vars.baudRateRegister).ToString() + " bps"))); uint seconds = vars.timeMs / 1000; uint minutes = seconds / 60; uint hours = minutes / 60; Console.WriteLine("Up time: {0}:{1:D2}:{2:D2}.{3:D3}", hours, minutes % 60, seconds % 60, vars.timeMs % 1000); Console.WriteLine(); const string motorLimitFormat = "{0, -18} {1,9} {2,8}"; Console.WriteLine(motorLimitFormat, "Limit", "Forward", "Reverse"); Console.WriteLine(motorLimitFormat, "Max. speed", vars.forwardLimits.maxSpeed, vars.reverseLimits.maxSpeed); Console.WriteLine(motorLimitFormat, "Starting speed", vars.forwardLimits.startingSpeed, vars.reverseLimits.startingSpeed); Console.WriteLine(motorLimitFormat, "Max. acceleration", Smc.accelDecelToString(vars.forwardLimits.maxAcceleration), Smc.accelDecelToString(vars.reverseLimits.maxAcceleration)); Console.WriteLine(motorLimitFormat, "Max. deceleration", Smc.accelDecelToString(vars.forwardLimits.maxDeceleration), Smc.accelDecelToString(vars.reverseLimits.maxDeceleration)); Console.WriteLine(motorLimitFormat, "Brake duration", vars.forwardLimits.brakeDuration, vars.reverseLimits.brakeDuration); }
/// <summary> /// This function runs when the user clicks the Reverse button. /// </summary> void reverseButton_Click(object sender, EventArgs e) { try { using (Smc device = connectToDevice()) // Find a device and temporarily connect. { device.resume(); // Clear as many errors as possible. device.setSpeed(-3200); // Set the speed to full reverse (-100%). } } catch (Exception exception) // Handle exceptions by displaying them to the user. { displayException(exception); } }
public void setSpeedRight(Smc device, short speed) { try { // Find a device and temporarily connect. { device.resume(); // Clear as many errors as possible. device.setSpeed(speed); // Set the speed to full forward (+100%). } } catch (Exception exception) // Handle exceptions by displaying them to the user. { Console.WriteLine(exception.Message); device.stop(); } }
public void stop(List <DeviceListItem> deviceList) { try { // Find a device and temporarily connect. foreach (var dev in deviceList) { Smc device = new Smc(dev); device.stop(); } } catch (Exception exception) // Handle exceptions by displaying them to the user. { Console.WriteLine(exception.Message); } }
/// <summary> /// Detects whether the device we are connected to is still plugged in /// to USB. If it is unplugged, we close the connection. /// </summary> void DetectDisconnect() { // Get a list of all connected devices of this type. List <DeviceListItem> connectedDevices = Smc.getConnectedDevices(); foreach (DeviceListItem dli in connectedDevices) { if (dli.serialNumber == device.getSerialNumber()) { // The device we are connected to is still plugged in. return; } } // The device we are connected to is not plugged in, so disconnect. Disconnect(); }
/// <summary> /// Connects to a Simple Motor Controller using native USB and returns the /// Smc 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> Smc connectToDevice() { // Get a list of all connected devices of this type. List<DeviceListItem> connectedDevices = Smc.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 != "39FF-7406-3054-3036-4923-0743"){ continue; } Smc device = new Smc(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> /// Connects to a Simple Motor Controller using native USB and returns the /// Smc 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> Smc connectToDevice() { // Get a list of all connected devices of this type. List <DeviceListItem> connectedDevices = Smc.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 != "39FF-7406-3054-3036-4923-0743"){ continue; } Smc device = new Smc(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)."); }
public static void listDevices() { List <DeviceListItem> list = Smc.getConnectedDevices(); if (list.Count == 1) { Console.WriteLine("1 " + Smc.name + " found:"); } else { Console.WriteLine(list.Count + " " + Smc.name + "s found:"); } foreach (DeviceListItem item in list) { Console.WriteLine(item.text); } }
/// <summary> /// This function runs when the user clicks the Stop button. /// </summary> void stopButton_Click(object sender, EventArgs e) { try { using (Smc device = connectToDevice()) // Find a device and temporarily connect. { device.stop(); // Activate the USB kill switch // Alternatively you can set the speed to 0 to stop the motor, // but that will only stop the motor if the input mode is Serial/USB: // device.setSpeed(0); } } catch (Exception exception) // Handle exceptions by displaying them to the user. { displayException(exception); } }
public void resume(List <DeviceListItem> deviceList) { try { // Find a device and temporarily connect. foreach (var dev in deviceList) { Smc device = new Smc(dev); device.setSpeed(50); device.resume(); } } catch (Exception error) // Handle exceptions by displaying them to the user. { Console.WriteLine(error.Message); } }
public List <DeviceListItem> getConnectedDevices() { try { try { devices = Smc.getConnectedDevices(); } catch (NotImplementedException) { // use vendor and product instead } } catch (Exception e) { throw new Exception("There was an error getting the list of connected devices.", e); } return(devices); }
private MeterDto CreateMeter(Meter meter, MeterDto meterDto, Smc smc) { meter.UpdateFields(meter, _meterModelService.GetExistingMeterModel(meterDto.MeterModel.Name), _rateTypeService.GetExistingRateType(meterDto.RateType.Name), smc, _meterKeyService.GetBySerial(smc.Serial)); CheckSmcPositions(meter); var status = _meterForwarderService.ForwardCreation(_mapper.Map <Meter, MeterDto>(meter)); if (!status.IsSuccessStatusCode) { throw new BadRequestException(JsonConvert .DeserializeObject <ErrorMessageDto>(status.Content.ReadAsStringAsync().Result).ErrorMessage); } var smcUnregisteredDto = _smcUnregisteredService.FindBySerial(smc.Serial); if (smcUnregisteredDto != null) { _smcUnregisteredService.Deactive(smc.Serial); } meter.AccountantStatus = AccountantStatus.NO_INFORMATION; return(_mapper.Map <Meter, MeterDto>(_meterRepository.Save(meter))); }
public List <DeviceListItem> connectDevice(List <DeviceListItem> devicelist) { foreach (DeviceListItem dli in devicelist) { // 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 != "39FF-7406-3054-3036-4923-0743"){ continue; } try { Smc connDevice = new Smc(dli); // Connect to the device. listOfconnectedDevice.Add(dli); } catch (Exception) { throw; } return(listOfconnectedDevice); // 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)."); }
public static void listDevices() { List <DeviceListItem> list = Smc.getConnectedDevices(); // Note: This format is kind of annoying but we use it for compatibility with old // SmcCmd format. For future products, we should use a CSV format similar to // the one used by jrk2cmd. if (list.Count == 1) { Console.WriteLine("1 " + Smc.name + " found:"); } else { Console.WriteLine(list.Count + " " + Smc.namePlural + " found:"); } foreach (DeviceListItem item in list) { Console.WriteLine(item.text); } }
private MeterDto CheckSmcMeterRegistered(Meter meter, MeterDto meterDto, Smc smc) { if (meter.Active) { throw new ExistentEntityException("O medidor de serial " + meter.Serial + " já existe"); } meter.UpdateFields(meter, _meterModelService.GetExistingMeterModel(meter.MeterModel.Name), _rateTypeService.GetExistingRateType(meterDto.RateType.Name), smc, _meterKeyService.GetBySerial(smc.Serial)); CheckSmcPositions(meter); meter.Active = true; var status = _meterForwarderService.ForwardEdition(_mapper.Map <Meter, MeterDto>(meter)); if (!status.IsSuccessStatusCode) { throw new BadRequestException(JsonConvert .DeserializeObject <ErrorMessageDto>(status.Content.ReadAsStringAsync().Result).ErrorMessage); } return(_mapper.Map <Meter, MeterDto>( _meterRepository.Update(meter))); }
/// <summary> /// Closes our connection to the device. Does not throw exceptions. /// </summary> void Disconnect() { if (device == null) { // We are already disconnected. return; } StatusLabel.Text = "Disconnected"; StatusLabel.ForeColor = Color.Red; try { device.Dispose(); // Disconnect } catch // Ignore exceptions. { } finally // Do this no matter what. { device = null; } }
private void GetsmcbtnClick(object sender, EventArgs e) { _sw = Stopwatch.StartNew(); var ofd = new OpenFileDialog(); if (ofd.ShowDialog() != DialogResult.OK) { return; } var bw = new BackgroundWorker(); bw.DoWork += (o, args) => { try { using (var reader = new NANDReader(ofd.FileName)) { AddOutput("Grabbing SMC from NAND: "); var data = _x360NAND.GetSmc(reader, true); var smc = new Smc(); var type = smc.GetType(ref data); AddOutput("\r\nSMC Version: {0} [{1}]", smc.GetVersion(ref data), smc.GetMotherBoardFromVersion(ref data)); AddOutput("\r\nSMC Type: {0}", type); if (type == Smc.SmcTypes.Jtag || type == Smc.SmcTypes.RJtag) { Smc.JtagsmcPatches.AnalyseSmc(ref data); } AddOutput("\r\nSMC Glitch Patched: {0}", smc.CheckGlitchPatch(ref data) ? "Yes" : "No"); } } catch (X360UtilsException ex) { AddOutput("FAILED!"); AddException(ex.ToString()); } AddOutput(Environment.NewLine); AddDone(); }; bw.RunWorkerCompleted += BwCompleted; bw.RunWorkerAsync(); }
private static ActionOnDevice laterConfigure() { // Read the entire file before connecting to the device. String filename = nextArgument(); List <String> warnings = new List <string>(); SmcSettings settings = SettingsFile.load(filename, warnings, 0); Smc.fixSettings(settings, warnings, 0); // Handle any warnings. if (warnings.Count != 0) { Console.WriteLine("There were problems with the settings file:"); foreach (String warning in warnings) { Console.WriteLine(" " + warning); } if (forceOption) { Console.WriteLine("The -f option is selected, so the settings will be applied anyway."); } else { throw new Exception("Aborted because of problems with settings file.\nUse the -f option to override and apply settings anyway."); } } // Return a delegate function that will get executed later after all // the command line arguments have been processed. return(delegate(Smc device) { // This is the line that actually applies the settings to the device. device.setSmcSettings(settings); }); }
public override void onCreate(Bundle savedInstanceState) { base.onCreate(savedInstanceState); ContentView = R.layout.video_player_layout; setupViewElements(); mSmcLib = new Smc(); try { mSmcLib.initialize(BaseContext); } catch (SsdkUnsupportedException e) { Console.WriteLine(e.ToString()); Console.Write(e.StackTrace); //TODO Handle exceptions. } Log.d("media control lib version", mSmcLib.VersionName); // Prepares assets used by sample. extractAssets(); // Restores saved state, after e.g. rotating. if (savedInstanceState != null) { mState = new VideoPlayerState(savedInstanceState); } else { mState = new VideoPlayerState(); // Initializes state with built-in content. File storageDir = new File(Environment.ExternalStorageDirectory, ASSETS_SUBDIR); File video = new File(storageDir, VIDEO_FILE); File subtitles = new File(storageDir, SUBTITLES_FILE); // Gets media information (title, artist, cover) MediaScannerConnection.scanFile(ApplicationContext, new string[] {video.AbsolutePath}, null, this); Uri mediaUri = Uri.fromFile(video); Uri subtitlesUri = Uri.fromFile(subtitles); mState.mMediaUri = mediaUri; mState.mSubtitlesUri = subtitlesUri; mState.mTitle = "Sample album"; string path = mediaUri.Path; if (path != null && path.LastIndexOf(".", StringComparison.Ordinal) != -1) { string ext = path.Substring(path.LastIndexOf(".", StringComparison.Ordinal) + 1); mState.mMimeType = MimeTypeMap.Singleton.getMimeTypeFromExtension(ext); } } }
public static void stop(Smc device) { device.stop(); }
public static void resume(Smc device) { device.resume(); }
public Smc Update(Smc smc) { _iogContext.Update(smc); _iogContext.SaveChanges(); return(smc); }
/// <summary> /// This funnction does all the real work. It will /// throw an exception if anything goes wrong. /// </summary> static void MainWithExceptions(string[] args) { // Parse all the command-line arguments, turning them in to a list of // actions to be taken. No actions on the device will occur until // all the arguments have been processed and validated. List<Action> actions = new List<Action>(); List<ActionOnDevice> actionsOnDevice = new List<ActionOnDevice>(); // If the user specifies a device serial number, it will be stored here. String specifiedSerialNumber = null; // Create a list object because it is easier to work with. List<String> argList = new List<String>(args); // Search for the -f option. This must be done ahead of time so that // it can be any place in the command line. forceOption = argList.Contains("-f"); argEnumerator = argList.GetEnumerator(); while(argEnumerator.MoveNext()) { // Read the next argument and decide what to do. switch (argEnumerator.Current) { case "-f": // Ignore, because we already searched for "-f". break; case "-l": case "--list": actions.Add(listDevices); break; case "-d": case "--device": if (specifiedSerialNumber != null) { throw new Exception("Only one -d/--device argument is alllowed."); } // Remove the leading # sign. It is not standard to put it there, // but if someone writes it, this program should still work. specifiedSerialNumber = nextArgument().TrimStart('#'); break; case "-s": case "--status": actionsOnDevice.Add(printStatus); break; case "--stop": actionsOnDevice.Add(stop); break; case "--resume": actionsOnDevice.Add(resume); break; case "--speed": actionsOnDevice.Add(laterSetSpeed()); break; case "--brake": actionsOnDevice.Add(laterSetBrake()); break; case "--restoredefaults": actionsOnDevice.Add(restoreDefaults); break; case "--configure": actionsOnDevice.Add(laterConfigure()); break; case "--getconf": actionsOnDevice.Add(laterGetConf()); break; case "--bootloader": actionsOnDevice.Add(startBootloader); break; case "--max-speed": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxSpeed)); break; case "--max-accel": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxAcceleration)); break; case "--max-decel": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxDeceleration)); break; case "--brake-dur": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.BrakeDuration)); break; case "--max-speed-forward": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxSpeed | SmcMotorLimit.ForwardOnly)); break; case "--max-accel-forward": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxAcceleration | SmcMotorLimit.ForwardOnly)); break; case "--max-decel-forward": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxDeceleration | SmcMotorLimit.ForwardOnly)); break; case "--brake-dur-forward": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.BrakeDuration | SmcMotorLimit.ForwardOnly)); break; case "--max-speed-reverse": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxSpeed | SmcMotorLimit.ReverseOnly)); break; case "--max-accel-reverse": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxAcceleration | SmcMotorLimit.ReverseOnly)); break; case "--max-decel-reverse": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxDeceleration | SmcMotorLimit.ReverseOnly)); break; case "--brake-dur-reverse": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.BrakeDuration | SmcMotorLimit.ReverseOnly)); break; default: throw new ArgumentException("Unrecognized argument \"" + argEnumerator.Current + "\"."); } } if (actions.Count == 0 && actionsOnDevice.Count == 0) { throw new ArgumentException("No actions specified."); } // Perform all actions that don't require being connected to a device. foreach (Action action in actions) { action(); } if (actionsOnDevice.Count == 0) { // There are no actions that require a device, so exit successfully. return; } // Find the right device to connect to. List<DeviceListItem> list = Smc.getConnectedDevices(); DeviceListItem item = null; if (specifiedSerialNumber == null) { // No serial number specified: connect to the first item in the list. if (list.Count > 0) { item = list[0]; } } else { // Find the device with the specified serial number. foreach (DeviceListItem checkItem in list) { if (checkItem.serialNumber == specifiedSerialNumber) { item = checkItem; break; } } } if (item == null && actionsOnDevice.Count == 1 && actionsOnDevice[0] == startBootloader) { // The correct device was not found, but all the user wanted to do was enter // bootloader mode so we should see if the device is connected in bootloader // mode and report success if that is true. List<DeviceListItem> bootloaders = Smc.getConnectedBootloaders(); if (specifiedSerialNumber == null) { if (bootloaders.Count > 0) { item = bootloaders[0]; } } else { // Find the device with the specified serial number. foreach (DeviceListItem checkItem in bootloaders) { if (checkItem.serialNumber.Replace("-", "") == specifiedSerialNumber.Replace("-", "")) { item = checkItem; break; } } } if (item == null) { if (specifiedSerialNumber == null) { throw new Exception("No " + Smc.namePlural + " (or bootloaders) found."); } else { throw new Exception("Could not find a device or bootloader with serial number " + specifiedSerialNumber + ".\n" + "To list devices, use the --list option."); } } Console.WriteLine("The device is already in bootloader mode."); return; } if (item == null) { if (specifiedSerialNumber == null) { throw new Exception("No " + Smc.namePlural + " found."); } else { throw new Exception("Could not find a device with serial number " + specifiedSerialNumber + ".\n" + "To list device, use the --list option."); } } // All the command-line arguments were good and a matching device was found, so // connect to it. Smc device = new Smc(item); // Perform all the previously computed actions on the device. foreach(ActionOnDevice action in actionsOnDevice) { action(device); } }
public static void restoreDefaults(Smc device) { Console.WriteLine("Restoring default settings..."); device.resetSettings(); }
public Smc Save(Smc smc) { _iogContext.Smcs.Add(smc); _iogContext.SaveChanges(); return(smc); }
public static void startBootloader(Smc device) { Console.WriteLine("Entering bootloader mode..."); string serialNumber = device.getSerialNumber(); device.startBootloader(); device.Dispose(); Console.WriteLine("Waiting for bootloader to connect..."); int msElapsed = 0; while(true) { foreach(DeviceListItem dli in Smc.getConnectedBootloaders()) { if (dli.serialNumber.Replace("-", "") == serialNumber.Replace("-", "")) { Console.WriteLine("Successfully entered bootloader mode."); return; } } System.Threading.Thread.Sleep(20); msElapsed += 20; if (msElapsed > 8000) { throw new Exception("Failed to enter bootloader mode: timeout elapsed."); } } }
/// <summary> /// This funnction does all the real work. It will /// throw an exception if anything goes wrong. /// </summary> static void MainWithExceptions(string[] args) { // Parse all the command-line arguments, turning them in to a list of // actions to be taken. No actions on the device will occur until // all the arguments have been processed and validated. List <Action> actions = new List <Action>(); List <ActionOnDevice> actionsOnDevice = new List <ActionOnDevice>(); // If the user specifies a device serial number, it will be stored here. String specifiedSerialNumber = null; // Create a list object because it is easier to work with. List <String> argList = new List <String>(args); // Search for the -f option. This must be done ahead of time so that // it can be any place in the command line. forceOption = argList.Contains("-f"); argEnumerator = argList.GetEnumerator(); while (argEnumerator.MoveNext()) { // Read the next argument and decide what to do. switch (argEnumerator.Current) { case "-f": // Ignore, because we already searched for "-f". break; case "-l": case "--list": actions.Add(listDevices); break; case "-d": case "--device": if (specifiedSerialNumber != null) { throw new Exception("Only one -d/--device argument is alllowed."); } // Remove the leading # sign. It is not standard to put it there, // but if someone writes it, this program should still work. specifiedSerialNumber = nextArgument().TrimStart('#'); break; case "-s": case "--status": actionsOnDevice.Add(printStatus); break; case "--stop": actionsOnDevice.Add(stop); break; case "--resume": actionsOnDevice.Add(resume); break; case "--speed": actionsOnDevice.Add(laterSetSpeed()); break; case "--brake": actionsOnDevice.Add(laterSetBrake()); break; case "--restoredefaults": actionsOnDevice.Add(restoreDefaults); break; case "--configure": actionsOnDevice.Add(laterConfigure()); break; case "--getconf": actionsOnDevice.Add(laterGetConf()); break; case "--bootloader": actionsOnDevice.Add(startBootloader); break; case "--max-speed": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxSpeed)); break; case "--max-accel": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxAcceleration)); break; case "--max-decel": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxDeceleration)); break; case "--brake-dur": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.BrakeDuration)); break; case "--max-speed-forward": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxSpeed | SmcMotorLimit.ForwardOnly)); break; case "--max-accel-forward": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxAcceleration | SmcMotorLimit.ForwardOnly)); break; case "--max-decel-forward": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxDeceleration | SmcMotorLimit.ForwardOnly)); break; case "--brake-dur-forward": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.BrakeDuration | SmcMotorLimit.ForwardOnly)); break; case "--max-speed-reverse": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxSpeed | SmcMotorLimit.ReverseOnly)); break; case "--max-accel-reverse": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxAcceleration | SmcMotorLimit.ReverseOnly)); break; case "--max-decel-reverse": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.MaxDeceleration | SmcMotorLimit.ReverseOnly)); break; case "--brake-dur-reverse": actionsOnDevice.Add(laterSetMotorLimit(SmcMotorLimit.BrakeDuration | SmcMotorLimit.ReverseOnly)); break; default: throw new ArgumentException("Unrecognized argument \"" + argEnumerator.Current + "\"."); } } if (actions.Count == 0 && actionsOnDevice.Count == 0) { throw new ArgumentException("No actions specified."); } // Perform all actions that don't require being connected to a device. foreach (Action action in actions) { action(); } if (actionsOnDevice.Count == 0) { // There are no actions that require a device, so exit successfully. return; } // Find the right device to connect to. List <DeviceListItem> list = Smc.getConnectedDevices(); DeviceListItem item = null; if (specifiedSerialNumber == null) { // No serial number specified: connect to the first item in the list. if (list.Count > 0) { item = list[0]; } } else { // Find the device with the specified serial number. foreach (DeviceListItem checkItem in list) { if (checkItem.serialNumber == specifiedSerialNumber) { item = checkItem; break; } } } if (item == null && actionsOnDevice.Count == 1 && actionsOnDevice[0] == startBootloader) { // The correct device was not found, but all the user wanted to do was enter // bootloader mode so we should see if the device is connected in bootloader // mode and report success if that is true. List <DeviceListItem> bootloaders = Smc.getConnectedBootloaders(); if (specifiedSerialNumber == null) { if (bootloaders.Count > 0) { item = bootloaders[0]; } } else { // Find the device with the specified serial number. foreach (DeviceListItem checkItem in bootloaders) { if (checkItem.serialNumber.Replace("-", "") == specifiedSerialNumber.Replace("-", "")) { item = checkItem; break; } } } if (item == null) { if (specifiedSerialNumber == null) { throw new Exception("No " + Smc.namePlural + " (or bootloaders) found."); } else { throw new Exception("Could not find a device or bootloader with serial number " + specifiedSerialNumber + ".\n" + "To list devices, use the --list option."); } } Console.WriteLine("The device is already in bootloader mode."); return; } if (item == null) { if (specifiedSerialNumber == null) { throw new Exception("No " + Smc.namePlural + " found."); } else { throw new Exception("Could not find a device with serial number " + specifiedSerialNumber + ".\n" + "To list device, use the --list option."); } } // All the command-line arguments were good and a matching device was found, so // connect to it. Smc device = new Smc(item); // Perform all the previously computed actions on the device. foreach (ActionOnDevice action in actionsOnDevice) { action(device); } }