├── clad_library └── CladCSharp.dll ├── .gitignore ├── csharp_interface ├── cozmoInterface │ ├── version.cs │ ├── callback.cs │ ├── action.cs │ ├── message.cs │ └── connection.cs ├── cozmoApp.cs └── cozmocsharp.csproj ├── README.md └── LICENSE.txt /clad_library/CladCSharp.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anki/cozmo-csharp-sdk/HEAD/clad_library/CladCSharp.dll -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | csharp_interface/obj/ 2 | csharp_interface/bin/ 3 | csharp_interface/cozmocsharp.sln 4 | csharp_interface/cozmocsharp.userprefs 5 | -------------------------------------------------------------------------------- /csharp_interface/cozmoInterface/version.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016-2017 Anki, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License in the file LICENSE.txt or at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Anki.Cozmo.ExternalInterface; 16 | 17 | namespace Anki 18 | { 19 | namespace Cozmo 20 | { 21 | public static class SDKVersion 22 | { 23 | public static readonly string _Data = "0.4.0"; 24 | } 25 | } // namespace Cozmo 26 | } // namespace Anki 27 | -------------------------------------------------------------------------------- /csharp_interface/cozmoInterface/callback.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016-2017 Anki, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License in the file LICENSE.txt or at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System; 16 | 17 | namespace Anki 18 | { 19 | namespace Cozmo 20 | { 21 | public interface iCallback 22 | { 23 | void Execute( object message ); 24 | } 25 | 26 | public class CallbackImpl : iCallback 27 | { 28 | Action _action; 29 | 30 | public CallbackImpl(Action action) 31 | { 32 | _action = action; 33 | } 34 | 35 | public void Execute(object message) 36 | { 37 | if (!(message is T)) { 38 | throw new System.Exception("CallbackImpl<" + typeof(T).FullName + ">.Execute - can't execute with param of type " + message.GetType().FullName); 39 | } 40 | if (_action != null) { 41 | _action((T)message); 42 | } 43 | } 44 | } 45 | } // namespace Cozmo 46 | } // namespace Anki 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # cozmo-csharp-sdk 2 | Anki Cozmo C# SDK Interface 3 | 4 | **Please note that updates to this C# SDK interface are indefinitely on hold. Current users can continue to use it, though must remain on version 3.0 of the Cozmo mobile app.** 5 | 6 | Unlike the Cozmo Python SDK - https://github.com/anki/cozmo-python-sdk - the C# SDK is not actively maintained by Anki, and is instead meant as a starting point for anyone who wishes to build their own C# SDK for interacting with Cozmo. 7 | 8 | The Cozmo Python SDK GitHub repo: https://github.com/anki/cozmo-python-sdk 9 | 10 | Learn more about Cozmo: https://anki.com/cozmo 11 | 12 | Learn more about the SDK: https://developer.anki.com/ 13 | 14 | SDK documentation: http://cozmosdk.anki.com/docs/ 15 | 16 | Forums: https://forums.anki.com/ 17 | 18 | 19 | 20 | The included project can be built on macOS via Xamarin Studio, or on Windows via Visual Studio. This project is a very small sample application which demonstrates how to send an action to Cozmo, and how to register for specific callbacks to receive incoming messages. Other messages can be found by browsing the CladCSharp.dll assembly, and can be sent and received using a similar approach. 21 | 22 | To connect to the Cozmo app running on your mobile device, you will need to plug in the device via a USB cable, and also set up port forwarding for TCP port 5106 to go over the USB cable. 23 | 24 | For Android devices use adb: 25 | 26 | adb forward tcp:5106 tcp:5106 27 | 28 | For iOS devices you will need to use the usbmux protocol (usually installed as part of iTunes) along with something like libimobiledevice. 29 | -------------------------------------------------------------------------------- /csharp_interface/cozmoInterface/action.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016-2017 Anki, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License in the file LICENSE.txt or at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Threading; 16 | 17 | namespace Anki 18 | { 19 | namespace Cozmo 20 | { 21 | public class Action 22 | { 23 | private SdkConnection _connection = null; 24 | private ExternalInterface.QueueSingleAction _message = null; 25 | private uint _id = 0; 26 | private bool _completed = false; 27 | 28 | private static uint _nextActionId = (uint)ActionConstants.FIRST_SDK_TAG; 29 | 30 | public uint ID { get { return _id; } } 31 | public ExternalInterface.QueueSingleAction Message { get { return _message; } } 32 | 33 | public Action(SdkConnection connection) 34 | { 35 | _connection = connection; 36 | 37 | _id = _nextActionId; 38 | _nextActionId++; 39 | if (_nextActionId >= (uint)ActionConstants.LAST_SDK_TAG) 40 | { 41 | _nextActionId = (uint)ActionConstants.FIRST_SDK_TAG; 42 | } 43 | } 44 | 45 | public void Abort() 46 | { 47 | _connection.SendMessage(new ExternalInterface.CancelActionByIdTag(_id)); 48 | } 49 | 50 | public void MarkAsComplete() 51 | { 52 | _completed = true; 53 | } 54 | 55 | public void WaitForCompleted() 56 | { 57 | while (!_completed) 58 | { 59 | Thread.Sleep(5); 60 | } 61 | } 62 | 63 | public void Initialize(T state, int numRetries, bool inParallel) 64 | { 65 | Cozmo.QueueActionPosition position = inParallel ? Cozmo.QueueActionPosition.IN_PARALLEL : Cozmo.QueueActionPosition.NOW; 66 | ExternalInterface.RobotActionUnion action = new ExternalInterface.RobotActionUnion(); 67 | action.Initialize(state); 68 | _message = new ExternalInterface.QueueSingleAction(idTag: _id, numRetries: (byte)numRetries, position: position, action: action); 69 | } 70 | } 71 | } // namespace Cozmo 72 | } // namespace Anki 73 | -------------------------------------------------------------------------------- /csharp_interface/cozmoInterface/message.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016-2017 Anki, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License in the file LICENSE.txt or at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using Anki.Cozmo.ExternalInterface; 16 | 17 | namespace Anki 18 | { 19 | namespace Cozmo 20 | { 21 | 22 | public class SDKMessageOut 23 | { 24 | public readonly MessageGameToEngine Message = new MessageGameToEngine(); 25 | 26 | #region IMessageWrapper implementation 27 | 28 | public void Unpack(System.IO.Stream stream) 29 | { 30 | Message.Unpack(stream); 31 | } 32 | 33 | public void Unpack(System.IO.BinaryReader reader) 34 | { 35 | Message.Unpack(reader); 36 | } 37 | 38 | public void Pack(System.IO.Stream stream) 39 | { 40 | Message.Pack(stream); 41 | } 42 | 43 | public void Pack(System.IO.BinaryWriter writer) 44 | { 45 | Message.Pack(writer); 46 | } 47 | 48 | public string GetTag() 49 | { 50 | return Message.GetTag().ToString(); 51 | } 52 | 53 | public int Size 54 | { 55 | get 56 | { 57 | return Message.Size; 58 | } 59 | } 60 | 61 | public bool IsValid 62 | { 63 | get 64 | { 65 | return Message.GetTag() != MessageGameToEngine.Tag.INVALID; 66 | } 67 | } 68 | 69 | #endregion 70 | } 71 | 72 | public class SDKMessageIn 73 | { 74 | public readonly MessageEngineToGame Message = new MessageEngineToGame(); 75 | 76 | #region IMessageWrapper implementation 77 | 78 | public void Unpack(System.IO.Stream stream) 79 | { 80 | Message.Unpack(stream); 81 | } 82 | 83 | public void Unpack(System.IO.BinaryReader reader) 84 | { 85 | Message.Unpack(reader); 86 | } 87 | 88 | public void Pack(System.IO.Stream stream) 89 | { 90 | Message.Pack(stream); 91 | } 92 | 93 | public void Pack(System.IO.BinaryWriter writer) 94 | { 95 | Message.Pack(writer); 96 | } 97 | 98 | public string GetTag() 99 | { 100 | return Message.GetTag().ToString(); 101 | } 102 | 103 | public int Size 104 | { 105 | get 106 | { 107 | return Message.Size; 108 | } 109 | } 110 | 111 | public bool IsValid 112 | { 113 | get 114 | { 115 | return Message.GetTag() != MessageEngineToGame.Tag.INVALID; 116 | } 117 | } 118 | 119 | #endregion 120 | } 121 | 122 | } // namespace Cozmo 123 | } // namespace Anki 124 | -------------------------------------------------------------------------------- /csharp_interface/cozmoApp.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016-2017 Anki, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License in the file LICENSE.txt or at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | // This program is a non-exhasutive example of how to leverage clad through csharp. 16 | // 17 | // The following message interaction paradigms are demonstrated: 18 | // - sending the "SetLiftHeight" message inside a cancellable action wrapper 19 | // - sending the "RequestAvailableAnimations" message, and registering for its associated callbacks 20 | // 21 | // Some messages are meant to be wrapped in actions, others are single calls meant to set robot state, 22 | // and some are designed to be used with callbacks. Please refer to the python sdk for further specific examples. 23 | // 24 | 25 | using System.Collections.Generic; 26 | using System.Threading; 27 | 28 | public class SampleApp 29 | { 30 | public const string kTargetIP = "127.0.0.1"; 31 | public const int kTargetPort = 5106; 32 | 33 | private Anki.Cozmo.SdkConnection _connection; 34 | private List _supportedAnimations = new List(); 35 | 36 | private void OnAnimationAvailable(Anki.Cozmo.ExternalInterface.AnimationAvailable message) 37 | { 38 | _supportedAnimations.Add(message.animName); 39 | } 40 | 41 | private void RequestSupportedAnimations() 42 | { 43 | // clear list and register for messages 44 | _supportedAnimations.Clear(); 45 | bool finished = false; 46 | _connection.AddCallback(this, OnAnimationAvailable); 47 | _connection.AddCallback(this, msg => finished = true); 48 | 49 | Anki.Cozmo.ExternalInterface.RequestAvailableAnimations message = new Anki.Cozmo.ExternalInterface.RequestAvailableAnimations(); 50 | _connection.SendMessage(message); 51 | 52 | while (!finished) 53 | { 54 | Thread.Sleep(5); 55 | } 56 | 57 | // unregister for messages 58 | _connection.RemoveCallback(this); 59 | _connection.RemoveCallback(this); 60 | } 61 | 62 | private Anki.Cozmo.Action SetLiftHeight(float percent) 63 | { 64 | // lift: (32 mm is the minimum height, 92 mm is the maximum height) 65 | float height_mm = 32.0f + percent * 60.0f; 66 | 67 | Anki.Cozmo.ExternalInterface.SetLiftHeight message = new Anki.Cozmo.ExternalInterface.SetLiftHeight(height_mm: height_mm, max_speed_rad_per_sec: 10.0f, accel_rad_per_sec2: 10.0f, duration_sec: 2.0f); 68 | 69 | return _connection.SendAction(message); 70 | } 71 | 72 | public void Execute() 73 | { 74 | _connection = new Anki.Cozmo.SdkConnection(kTargetIP, kTargetPort); 75 | 76 | RequestSupportedAnimations(); 77 | System.Console.WriteLine("Cozmo can perform " + _supportedAnimations.Count.ToString() + " animations"); 78 | 79 | SetLiftHeight(1.0f).WaitForCompleted(); 80 | SetLiftHeight(0.0f).WaitForCompleted(); 81 | 82 | _connection.Close(); 83 | } 84 | 85 | static void Main(string[] args) 86 | { 87 | SampleApp app = new SampleApp(); 88 | app.Execute(); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /csharp_interface/cozmocsharp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Debug 5 | x86 6 | {7CFA29E4-65E9-49B5-82AE-39CD0E36796C} 7 | Exe 8 | cozmoCSharp 9 | cozmoCSharp 10 | v4.5 11 | 12 | 13 | true 14 | full 15 | false 16 | bin\Debug 17 | DEBUG; 18 | prompt 19 | 4 20 | x86 21 | 22 | 23 | true 24 | bin\Release 25 | prompt 26 | 4 27 | x86 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | ..\clad_library\CladCSharp.dll 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Unless otherwise stated in that file, or the folder containing that file, all 2 | files in the Cozmo SDK are Copyright (c) 2016-2017 Anki Inc. and licensed under 3 | the Apache 2.0 License: 4 | 5 | Apache License 6 | Version 2.0, January 2004 7 | http://www.apache.org/licenses/ 8 | 9 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 10 | 11 | 1. Definitions. 12 | 13 | "License" shall mean the terms and conditions for use, reproduction, 14 | and distribution as defined by Sections 1 through 9 of this document. 15 | 16 | "Licensor" shall mean the copyright owner or entity authorized by 17 | the copyright owner that is granting the License. 18 | 19 | "Legal Entity" shall mean the union of the acting entity and all 20 | other entities that control, are controlled by, or are under common 21 | control with that entity. For the purposes of this definition, 22 | "control" means (i) the power, direct or indirect, to cause the 23 | direction or management of such entity, whether by contract or 24 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 25 | outstanding shares, or (iii) beneficial ownership of such entity. 26 | 27 | "You" (or "Your") shall mean an individual or Legal Entity 28 | exercising permissions granted by this License. 29 | 30 | "Source" form shall mean the preferred form for making modifications, 31 | including but not limited to software source code, documentation 32 | source, and configuration files. 33 | 34 | "Object" form shall mean any form resulting from mechanical 35 | transformation or translation of a Source form, including but 36 | not limited to compiled object code, generated documentation, 37 | and conversions to other media types. 38 | 39 | "Work" shall mean the work of authorship, whether in Source or 40 | Object form, made available under the License, as indicated by a 41 | copyright notice that is included in or attached to the work 42 | (an example is provided in the Appendix below). 43 | 44 | "Derivative Works" shall mean any work, whether in Source or Object 45 | form, that is based on (or derived from) the Work and for which the 46 | editorial revisions, annotations, elaborations, or other modifications 47 | represent, as a whole, an original work of authorship. For the purposes 48 | of this License, Derivative Works shall not include works that remain 49 | separable from, or merely link (or bind by name) to the interfaces of, 50 | the Work and Derivative Works thereof. 51 | 52 | "Contribution" shall mean any work of authorship, including 53 | the original version of the Work and any modifications or additions 54 | to that Work or Derivative Works thereof, that is intentionally 55 | submitted to Licensor for inclusion in the Work by the copyright owner 56 | or by an individual or Legal Entity authorized to submit on behalf of 57 | the copyright owner. For the purposes of this definition, "submitted" 58 | means any form of electronic, verbal, or written communication sent 59 | to the Licensor or its representatives, including but not limited to 60 | communication on electronic mailing lists, source code control systems, 61 | and issue tracking systems that are managed by, or on behalf of, the 62 | Licensor for the purpose of discussing and improving the Work, but 63 | excluding communication that is conspicuously marked or otherwise 64 | designated in writing by the copyright owner as "Not a Contribution." 65 | 66 | "Contributor" shall mean Licensor and any individual or Legal Entity 67 | on behalf of whom a Contribution has been received by Licensor and 68 | subsequently incorporated within the Work. 69 | 70 | 2. Grant of Copyright License. Subject to the terms and conditions of 71 | this License, each Contributor hereby grants to You a perpetual, 72 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 73 | copyright license to reproduce, prepare Derivative Works of, 74 | publicly display, publicly perform, sublicense, and distribute the 75 | Work and such Derivative Works in Source or Object form. 76 | 77 | 3. Grant of Patent License. Subject to the terms and conditions of 78 | this License, each Contributor hereby grants to You a perpetual, 79 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 80 | (except as stated in this section) patent license to make, have made, 81 | use, offer to sell, sell, import, and otherwise transfer the Work, 82 | where such license applies only to those patent claims licensable 83 | by such Contributor that are necessarily infringed by their 84 | Contribution(s) alone or by combination of their Contribution(s) 85 | with the Work to which such Contribution(s) was submitted. If You 86 | institute patent litigation against any entity (including a 87 | cross-claim or counterclaim in a lawsuit) alleging that the Work 88 | or a Contribution incorporated within the Work constitutes direct 89 | or contributory patent infringement, then any patent licenses 90 | granted to You under this License for that Work shall terminate 91 | as of the date such litigation is filed. 92 | 93 | 4. Redistribution. You may reproduce and distribute copies of the 94 | Work or Derivative Works thereof in any medium, with or without 95 | modifications, and in Source or Object form, provided that You 96 | meet the following conditions: 97 | 98 | (a) You must give any other recipients of the Work or 99 | Derivative Works a copy of this License; and 100 | 101 | (b) You must cause any modified files to carry prominent notices 102 | stating that You changed the files; and 103 | 104 | (c) You must retain, in the Source form of any Derivative Works 105 | that You distribute, all copyright, patent, trademark, and 106 | attribution notices from the Source form of the Work, 107 | excluding those notices that do not pertain to any part of 108 | the Derivative Works; and 109 | 110 | (d) If the Work includes a "NOTICE" text file as part of its 111 | distribution, then any Derivative Works that You distribute must 112 | include a readable copy of the attribution notices contained 113 | within such NOTICE file, excluding those notices that do not 114 | pertain to any part of the Derivative Works, in at least one 115 | of the following places: within a NOTICE text file distributed 116 | as part of the Derivative Works; within the Source form or 117 | documentation, if provided along with the Derivative Works; or, 118 | within a display generated by the Derivative Works, if and 119 | wherever such third-party notices normally appear. The contents 120 | of the NOTICE file are for informational purposes only and 121 | do not modify the License. You may add Your own attribution 122 | notices within Derivative Works that You distribute, alongside 123 | or as an addendum to the NOTICE text from the Work, provided 124 | that such additional attribution notices cannot be construed 125 | as modifying the License. 126 | 127 | You may add Your own copyright statement to Your modifications and 128 | may provide additional or different license terms and conditions 129 | for use, reproduction, or distribution of Your modifications, or 130 | for any such Derivative Works as a whole, provided Your use, 131 | reproduction, and distribution of the Work otherwise complies with 132 | the conditions stated in this License. 133 | 134 | 5. Submission of Contributions. Unless You explicitly state otherwise, 135 | any Contribution intentionally submitted for inclusion in the Work 136 | by You to the Licensor shall be under the terms and conditions of 137 | this License, without any additional terms or conditions. 138 | Notwithstanding the above, nothing herein shall supersede or modify 139 | the terms of any separate license agreement you may have executed 140 | with Licensor regarding such Contributions. 141 | 142 | 6. Trademarks. This License does not grant permission to use the trade 143 | names, trademarks, service marks, or product names of the Licensor, 144 | except as required for reasonable and customary use in describing the 145 | origin of the Work and reproducing the content of the NOTICE file. 146 | 147 | 7. Disclaimer of Warranty. Unless required by applicable law or 148 | agreed to in writing, Licensor provides the Work (and each 149 | Contributor provides its Contributions) on an "AS IS" BASIS, 150 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 151 | implied, including, without limitation, any warranties or conditions 152 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 153 | PARTICULAR PURPOSE. You are solely responsible for determining the 154 | appropriateness of using or redistributing the Work and assume any 155 | risks associated with Your exercise of permissions under this License. 156 | 157 | 8. Limitation of Liability. In no event and under no legal theory, 158 | whether in tort (including negligence), contract, or otherwise, 159 | unless required by applicable law (such as deliberate and grossly 160 | negligent acts) or agreed to in writing, shall any Contributor be 161 | liable to You for damages, including any direct, indirect, special, 162 | incidental, or consequential damages of any character arising as a 163 | result of this License or out of the use or inability to use the 164 | Work (including but not limited to damages for loss of goodwill, 165 | work stoppage, computer failure or malfunction, or any and all 166 | other commercial damages or losses), even if such Contributor 167 | has been advised of the possibility of such damages. 168 | 169 | 9. Accepting Warranty or Additional Liability. While redistributing 170 | the Work or Derivative Works thereof, You may choose to offer, 171 | and charge a fee for, acceptance of support, warranty, indemnity, 172 | or other liability obligations and/or rights consistent with this 173 | License. However, in accepting such obligations, You may act only 174 | on Your own behalf and on Your sole responsibility, not on behalf 175 | of any other Contributor, and only if You agree to indemnify, 176 | defend, and hold each Contributor harmless for any liability 177 | incurred by, or claims asserted against, such Contributor by reason 178 | of your accepting any such warranty or additional liability. 179 | 180 | END OF TERMS AND CONDITIONS 181 | -------------------------------------------------------------------------------- /csharp_interface/cozmoInterface/connection.cs: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2016-2017 Anki, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License in the file LICENSE.txt or at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | using System.Collections.Generic; 16 | using System.Linq; 17 | using System.Threading; 18 | using System.IO; 19 | 20 | using System.Net; 21 | using System.Net.Sockets; 22 | 23 | namespace Anki 24 | { 25 | namespace Cozmo 26 | { 27 | public class SdkConnection 28 | { 29 | public UiConnectionType SDKConnectionType = UiConnectionType.SdkOverTcp; 30 | 31 | private const int _MaxBufferSize = 8192; 32 | 33 | private IPEndPoint _endPoint = null; 34 | private Socket _socket = null; 35 | private bool _verboseLogging = false; 36 | private Thread _listenThread = null; 37 | private bool _shutdownSignal = false; 38 | private Dictionary> _callbacks = new Dictionary>(); 39 | private List _inFlightActions = new List(); 40 | private bool _open = false; 41 | private bool _robotIsConnected = false; 42 | 43 | public SdkConnection(string ip, int socket, bool verboseLogging = false) 44 | { 45 | _verboseLogging = verboseLogging; 46 | 47 | AddCallback(this, HandlePing); 48 | AddCallback(this, HandleUiDeviceConnected); 49 | AddCallback(this, HandleActionCompleted); 50 | 51 | System.Console.WriteLine("Connecting to engine"); 52 | 53 | _endPoint = new IPEndPoint(IPAddress.Parse(ip), socket); 54 | _socket = new Socket(_endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 55 | _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); 56 | _socket.Connect(_endPoint); 57 | 58 | _listenThread = new Thread(PollSocket); 59 | _listenThread.Start(); 60 | _open = true; 61 | 62 | // wait for robot 63 | while (!_robotIsConnected) 64 | { 65 | Thread.Sleep(5); 66 | } 67 | } 68 | 69 | public void Close() 70 | { 71 | if (_open) 72 | { 73 | _open = false; 74 | _shutdownSignal = true; 75 | _listenThread.Join(); 76 | 77 | System.Console.WriteLine("Disconnecting from engine"); 78 | 79 | _socket.Disconnect(true); 80 | _socket.Close(); 81 | } 82 | } 83 | 84 | public Action SendAction(T state, int numRetries = 0, bool inParallel = false) 85 | { 86 | Action result = new Action(this); 87 | result.Initialize(state, numRetries, inParallel); 88 | 89 | _inFlightActions.Add(result); 90 | 91 | SendMessage(result.Message); 92 | 93 | return result; 94 | } 95 | 96 | public void SendMessage(T state) 97 | { 98 | SDKMessageOut messageWrapper = new SDKMessageOut(); 99 | messageWrapper.Message.Initialize(state); 100 | SendMessageInternal(messageWrapper); 101 | } 102 | 103 | private void SendMessageInternal(SDKMessageOut messageOut) 104 | { 105 | if (!_open) 106 | { 107 | System.Console.WriteLine("Attempt to send message while not connected - " + messageOut.GetTag()); 108 | return; 109 | } 110 | try 111 | { 112 | MemoryStream stream = new MemoryStream(_MaxBufferSize); 113 | BinaryWriter writer = new BinaryWriter(stream); 114 | 115 | writer.Write((short)messageOut.Size); 116 | messageOut.Pack(stream); 117 | 118 | int packetSize = 2 + messageOut.Size; 119 | 120 | int bytesSent = _socket.Send(stream.GetBuffer(), 0, packetSize, SocketFlags.None); 121 | 122 | if (bytesSent != packetSize) 123 | { 124 | System.Console.WriteLine("Wrong number of bytes sent: " + bytesSent.ToString() + ", expected: " + packetSize.ToString()); 125 | } 126 | } 127 | catch (System.Exception e) 128 | { 129 | System.Console.WriteLine(e.Message); 130 | Close(); 131 | } 132 | } 133 | 134 | private void ReceiveMessage(SDKMessageIn messageIn) 135 | { 136 | var message = messageIn.Message; 137 | if (_verboseLogging) { System.Console.WriteLine("Recieved Message - " + message.GetTag()); } 138 | 139 | // since the property to access individual message data in a CLAD message shares its name 140 | // with the message's tag, we can use that name to get the property that retrieves message 141 | // data for this type, and execute it on this message 142 | object messageData = typeof(Anki.Cozmo.ExternalInterface.MessageEngineToGame).GetProperty(message.GetTag().ToString()).GetValue(message, null); 143 | 144 | Dictionary callbacks; 145 | if (_callbacks.TryGetValue(messageData.GetType(), out callbacks)) 146 | { 147 | iCallback[] callbacksToExectute = callbacks.Values.ToArray(); 148 | foreach (iCallback callback in callbacksToExectute) 149 | { 150 | callback.Execute(messageData); 151 | } 152 | } 153 | 154 | if (!_robotIsConnected && message.GetTag() == Anki.Cozmo.ExternalInterface.MessageEngineToGame.Tag.RobotState) 155 | { 156 | _robotIsConnected = true; 157 | System.Console.WriteLine("Robot connected!"); 158 | } 159 | } 160 | 161 | private bool ParseBuffer(List buffer) 162 | { 163 | if (buffer.Count < 2) 164 | { 165 | return false; 166 | } 167 | 168 | System.Byte[] byteArray = buffer.ToArray(); 169 | MemoryStream stream = new MemoryStream(byteArray); 170 | BinaryReader br = new BinaryReader(stream); 171 | 172 | int messageSize = (int)br.ReadInt16(); 173 | int packetSize = 2 + messageSize; 174 | 175 | if (stream.Length >= packetSize) 176 | { 177 | SDKMessageIn message = null; 178 | try 179 | { 180 | message = new SDKMessageIn(); 181 | try 182 | { 183 | message.Unpack(stream); 184 | } 185 | catch (System.Exception e) 186 | { 187 | if (message.Size != messageSize) 188 | { 189 | throw new System.Exception("Could not parse message " + message.GetTag() + ": " + 190 | "message size " + message.Size.ToString() + 191 | " not equal to buffer size " + messageSize.ToString(), 192 | e); 193 | } 194 | throw; 195 | } 196 | 197 | if (message.Size != messageSize) 198 | { 199 | throw new System.Exception("Could not parse message " + message.GetTag() + ": " + 200 | "message size " + message.Size.ToString() + 201 | " not equal to buffer size " + messageSize.ToString()); 202 | } 203 | } 204 | catch (System.Exception e) 205 | { 206 | System.Console.WriteLine(e.Message); 207 | Close(); 208 | return false; 209 | } 210 | 211 | ReceiveMessage(message); 212 | 213 | buffer.RemoveRange(0, packetSize); 214 | return true; 215 | } 216 | else 217 | { 218 | return false; 219 | } 220 | } 221 | 222 | private void PollSocket() 223 | { 224 | System.Byte[] socketBuffer = new System.Byte[_MaxBufferSize]; 225 | List recievedBuffer = new List(); 226 | 227 | while (!_shutdownSignal) 228 | { 229 | int bytesRead = _socket.Receive(socketBuffer, 0, _MaxBufferSize, SocketFlags.None); 230 | if (bytesRead > 0) 231 | { 232 | if (_verboseLogging) { System.Console.WriteLine("Read " + bytesRead.ToString() + " bytes"); } 233 | for (int i = 0; i < bytesRead; ++i) { recievedBuffer.Add(socketBuffer[i]); } 234 | 235 | while (ParseBuffer(recievedBuffer)) { } 236 | } 237 | 238 | // 10 ms sleep 239 | Thread.Sleep(10); 240 | } 241 | } 242 | 243 | public void AddCallback(object obj, System.Action action) 244 | { 245 | if (!_callbacks.ContainsKey(typeof(T))) 246 | { 247 | _callbacks[typeof(T)] = new Dictionary(); 248 | } 249 | 250 | if (_callbacks[typeof(T)].ContainsKey(obj)) 251 | { 252 | throw new System.Exception("Cannot register the same object multiple times for the same action"); 253 | } 254 | 255 | _callbacks[typeof(T)][obj] = new CallbackImpl(action); 256 | } 257 | 258 | public void RemoveCallback(object obj) 259 | { 260 | if (!_callbacks.ContainsKey(typeof(T))) 261 | { 262 | throw new System.Exception("Cannot remove callback, because no callbacks of type " + typeof(T).FullName + " are registered"); 263 | } 264 | Dictionary callbackEntries = _callbacks[typeof(T)]; 265 | 266 | if (!callbackEntries.ContainsKey(obj)) 267 | { 268 | throw new System.Exception("Cannot remove callback, because no callbacks of type " + typeof(T).FullName + " are registered to the object with address " + obj); 269 | } 270 | 271 | callbackEntries.Remove(obj); 272 | } 273 | 274 | private void HandlePing(Anki.Cozmo.ExternalInterface.Ping message) 275 | { 276 | SendMessage(new Anki.Cozmo.ExternalInterface.Ping(message.counter, message.timeSent_ms, true)); 277 | } 278 | 279 | private void HandleUiDeviceConnected(Anki.Cozmo.ExternalInterface.UiDeviceConnected message) 280 | { 281 | // @TODO: Send message "wrong version" - check python SDK 282 | if (!message.toGameCLADHash.SequenceEqual(MessageEngineToGameHash._Data)) 283 | { 284 | SendMessage(new ExternalInterface.UiDeviceConnectionWrongVersion(reserved: 0, connectionType: message.connectionType, deviceID: message.deviceID, buildVersion: Anki.Cozmo.CladVersion._Data)); 285 | throw new System.Exception("CladMismatchEngineToGame - Engine's hash (" + 286 | System.BitConverter.ToString(message.toGameCLADHash) + ") != UI's (" + 287 | System.BitConverter.ToString(MessageEngineToGameHash._Data) + ")"); 288 | } 289 | 290 | if (!message.toEngineCLADHash.SequenceEqual(MessageGameToEngineHash._Data)) 291 | { 292 | SendMessage(new ExternalInterface.UiDeviceConnectionWrongVersion(reserved: 0, connectionType: message.connectionType, deviceID: message.deviceID, buildVersion: Anki.Cozmo.CladVersion._Data)); 293 | throw new System.Exception("CladMismatchGameToEngine - Engine's hash (" + 294 | System.BitConverter.ToString(message.toEngineCLADHash) + ") != UI's (" + 295 | System.BitConverter.ToString(MessageGameToEngineHash._Data) + ")"); 296 | } 297 | 298 | SendMessage(new ExternalInterface.UiDeviceConnectionSuccess(connectionType: message.connectionType, 299 | deviceID: message.deviceID, 300 | buildVersion: Anki.Cozmo.CladVersion._Data, 301 | sdkModuleVersion: Anki.Cozmo.SDKVersion._Data, 302 | pythonVersion: "CSharp", 303 | pythonImplementation: "CSharp", 304 | osVersion: "?", 305 | cpuVersion: "?")); 306 | 307 | System.Console.WriteLine("Connected to Cozmo App"); 308 | } 309 | 310 | private void HandleActionCompleted(ExternalInterface.RobotCompletedAction message) 311 | { 312 | IEnumerable matches = _inFlightActions.FindAll(action => action.ID == message.idTag); 313 | 314 | foreach (Action action in matches) 315 | { 316 | action.MarkAsComplete(); 317 | _inFlightActions.Remove(action); 318 | } 319 | if (_verboseLogging) { System.Console.WriteLine("Action completed " + message.actionType.ToString()); } 320 | } 321 | } 322 | } // namespace Cozmo 323 | } // namespace Anki 324 | --------------------------------------------------------------------------------