Skip to content

Instantly share code, notes, and snippets.

@KeanW
Created January 8, 2016 15:13
Show Gist options
  • Save KeanW/c815cd941148fdc69238 to your computer and use it in GitHub Desktop.
Save KeanW/c815cd941148fdc69238 to your computer and use it in GitHub Desktop.
C# file to drive robots from within AutoCAD via our Node/Cylon.js web-service
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using System.Globalization;
using System.Net;
using System.Web.Script.Serialization;
namespace DriveRobots
{
public static class Extensions
{
public static string ToTitleCase(this string str)
{
return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}
}
public class Commands
{
private static string _lastBot = "";
const string host = "http://localhost:8080";
const string root = host + "/api/robots";
[CommandMethod("DR")]
public void DriveRobot()
{
var doc = Application.DocumentManager.MdiActiveDocument;
if (doc == null)
return;
var ed = doc.Editor;
var db = doc.Database;
using (var wc = new WebClient())
{
string[] names = null;
try
{
var json = wc.DownloadString(root);
names = new JavaScriptSerializer().Deserialize<string[]>(json);
}
catch (System.Exception ex)
{
ed.WriteMessage("\nCan't access robot web-service: {0}.", ex.Message);
return;
}
// Ask the user for the robot to control
var pko = new PromptKeywordOptions("\nRobot name");
foreach (var name in names)
{
pko.Keywords.Add(name.ToTitleCase());
}
// If a bot was selected previously, set it as the default
if (!string.IsNullOrEmpty(_lastBot))
{
pko.Keywords.Default = _lastBot;
}
var pkr = ed.GetKeywords(pko);
if (pkr.Status != PromptStatus.OK)
return;
_lastBot = pkr.StringResult;
var botUrl = root + "/" + _lastBot.ToLower();
// Start by getting the bot - this should wake it, if needed
try
{
wc.DownloadString(botUrl);
}
catch (System.Exception ex)
{
ed.WriteMessage("\nCan't connect to {0}: {1}.", _lastBot, ex.Message);
return;
}
// The direction can be one of the four main directions or a number
var pio = new PromptIntegerOptions("\nDirection");
pio.Keywords.Add("Left");
pio.Keywords.Add("Right");
pio.Keywords.Add("Forward");
pio.Keywords.Add("Backward");
pio.AppendKeywordsToMessage = true;
// Set the direction depending on which was chosen
var pir = ed.GetInteger(pio);
var direction = "";
if (pir.Status == PromptStatus.Keyword)
{
direction = pir.StringResult;
}
else if (pir.Status == PromptStatus.OK)
{
direction = pir.Value.ToString();
}
else return;
// Generate the URL to direct the robot
var dirUrl = botUrl + "/" + direction.ToLower();
// Our move command
try
{
wc.DownloadString(dirUrl);
}
catch (System.Exception ex)
{
ed.WriteMessage("\nCan't move {0}: {1}.", _lastBot, ex.Message);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment