Example #1
0
        public static void Run()
        {
            RemoteContorl remote             = new RemoteContorl();
            Light         light              = new Light();
            var           lightToggleCommand = new LightToggleCommand(light);

            CeilingFan fan = new CeilingFan();
            var        ceilingFanSpeedUpCommand   = new CeilingFanSpeedUpCommand(fan);
            var        ceilingFanSpeedDownCommand = new CeilingFanSpeedDownCommand(fan);

            remote.AddCommand(0, lightToggleCommand);
            remote.AddCommand(1, ceilingFanSpeedUpCommand);
            remote.AddCommand(2, ceilingFanSpeedDownCommand);

            MasterCommand master = new MasterCommand();

            master.AddCommand(lightToggleCommand);
            master.AddCommand(ceilingFanSpeedUpCommand);
            master.AddCommand(ceilingFanSpeedDownCommand);

            remote.AddCommand(3, master);
            remote.AddCommand(4, new NoOpCommand());


            remote.OnButtonPress(1);
            remote.OnButtonPress(1);
            remote.OnButtonPress(1);
            remote.OnButtonPress(1);

            remote.OnButtonPress(0);
            remote.OnButtonPress(0);

            remote.OnButtonPress(3);
        }
Example #2
0
        /// <summary>
        /// Used to retrive a command from the DB to see its details.
        /// </summary>
        /// <param name="MS"></param>
        static void MasterCommandRequest(MasterCommand MS)
        {
            if (MS.commandId.Length > 0 || MS.commandName.Length > 0)
            {
                int commandId;
                if (MS.commandId == "")
                {
                    commandId = db.commands.Where(c => c.Value.commandName.ToLower() == MS.commandName).Select(c => c.Key).FirstOrDefault();
                }
                else
                {
                    int.TryParse(MS.commandId, out commandId);
                }
                if (db.commands.Where(c => c.Key == commandId).Count() > 0)// COMMAND EXISTS IN DB!!!
                {
                    command cmd = db.commands[(int)commandId];

                    Console.WriteLine("\n\nPRINTING ARGUMENTS OF COMMAND ABOUT TO BE RETURNED TO JOSH THROUGH LOCALHOST\n");
                    utilities.PrintCommandArguments(cmd);

                    if (!MS.deleteRequestedCommand)//NOT A DELETE REQUEST
                    {
                        commandFormattedForJSON cmdToJSONFormat = new commandFormattedForJSON()
                        {
                            argumentLengths = cmd.argumentLengths,
                            argumentTypes   = cmd.argumentTypes.Select(x => (int)x).ToArray(),
                            commandName     = cmd.commandName,
                            description     = cmd.description
                        };

                        cmdToJSONFormat.setArgumentTypes(cmd.argumentTypes);
                        cmdToJSONFormat.setArguments(cmd.arguments);

                        string objToJSON = Jil.JSON.Serialize(cmdToJSONFormat);
                        Console.WriteLine("\n\nJSON string representing command:\n{0}", objToJSON);

                        sendResponse(MS, true, objToJSON);

                        Console.WriteLine("\n\nCommand, serialized as JSON string, was successfully returned to Josh.\n\n");
                    }
                    else
                    {
                        db.commands.Remove(commandId);
                        Console.WriteLine("\n\nCommand of id {0} has been removed from DB successfully.\n", commandId);
                        sendResponse(MS, true, "Command of id " + commandId + " has successfully been removed from DB.");
                    }
                }
                else
                {
                    //failed
                    Console.WriteLine("Could not find command in DB since the id/name are not present.\n\n");
                    sendResponse(MS, false, "Command could not be found in the DB, make sure the command ID or command Name exist first.");
                }
            }
            else
            {
                Console.WriteLine("Could not run REQUEST command since no command ID or Name have been provided.\n\n");
                sendResponse(MS, false, "Request of command could not be achieved since some of the required Master Command object properties are not set: command ID or Name mus tbe set.");
            }
        }
Example #3
0
        /// <summary>
        /// Sends a command to destination MAC. Either send a command in its default state as its in DB of commands or with custom arguments if they are passed
        /// </summary>
        /// <param name="MS"></param>
        static void MasterCommandSend(MasterCommand MS)
        {
            if ((MS.commandId.Length > 0 || MS.commandName.Length > 0) && MS.destinationMAC.Length > 0)
            {
                int commandId;
                if (MS.commandId == "")
                {
                    commandId = db.commands.Where(c => c.Value.commandName.ToLower() == MS.commandName).Select(c => c.Key).FirstOrDefault();
                }
                else
                {
                    int.TryParse(MS.commandId, out commandId);
                }
                if (db.commands.Where(c => c.Key == commandId).Count() > 0)// COMMAND EXISTS IN DB!!!
                {
                    command cmd = db.commands[(int)commandId];
                    //If custom arguments are passed, set them. REMEMBER TO KEEP SAME ORDER OF BITS AND LENGTH AS argumentLengths and argumentTypes on specific command in DB
                    //this updates db every time we send new arguments, a feature we wanted! This way next time default args are sent it will be the last ones sent
                    if (MS.arguments.Count > 0)
                    {
                        cmd.arguments = MS.getArgumentsAsBitArray();
                    }

                    Console.WriteLine("\n\nPRINTING ARGUMENTS OF COMMAND ABOUT TO BE SENT\n");

                    utilities.PrintCommandArguments(cmd);

                    Console.WriteLine("Command packet generated and about to be sent.\n COMMAND ID: {0} \n COMMAND NAME: {1}\n", commandId, cmd.commandName);

                    //Send packet to destination mac address via ethernet layer

                    Regex validMAC = new Regex("^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$");
                    if (validMAC.IsMatch(MS.destinationMAC))
                    {
                        PacketSender(cmd, MS.destinationMAC);
                        Console.WriteLine("Command packet WAS SENT SUCCESSFULLY.\n COMMAND ID: {0} \n COMMAND NAME: {1}\n\n", commandId, cmd.commandName);
                        sendResponse(MS, true, "Command of id " + commandId + " has been sent to destination MAC successfully.");
                    }
                    else
                    {
                        Console.WriteLine("Command of id " + commandId + " could not be sent to destination MAC since the MAC given is incorrect in format\n\n");
                        sendResponse(MS, false, "Command of id " + commandId + " could not be sent to destination MAC since the MAC given is incorrect in format:  " + MS.destinationMAC);
                    }
                }
                else
                {
                    //failed
                    Console.WriteLine("Could not find command in DB since the id/name are not present.\n\n");
                    sendResponse(MS, false, "Command could not be found in the DB, make sure the command ID or command Name exist first.");
                }
            }
            else
            {
                Console.WriteLine("Could not run SEND command since some of the mandatory fields in Master Command are not valid.\n\n");
                sendResponse(MS, false, "Command could not be sent since some of the required Master Command object properties are not set.");
            }
        }
Example #4
0
 /// <summary>
 /// Used to modify DB of commands. Either Update or Create.
 /// </summary>
 /// <param name="MS"></param>
 static void MasterCommandModify(MasterCommand MS)
 {
     //check if all values required for operation are set properly
     if (MS.commandId.Length > 0 && MS.argumentLengths.Length > 0 && MS.argumentTypes.Length > 0 && MS.commandName.Length > 0 && MS.description.Length > 0)
     {
         int cmdId;
         int.TryParse(MS.commandId, out cmdId);
         command cmd = new command()
         {
             argumentLengths = MS.argumentLengths,
             argumentTypes   = MS.getArgumentTypesAsByteArray(),
             commandName     = MS.commandName,
             arguments       = MS.getArgumentsAsBitArray(),
             description     = MS.description
         };
         Console.WriteLine("\n\nPRINTING PASSED ARGUMENTS OF COMMAND PASSED BY JOSH THROUGH LOCALHOST: \n");
         utilities.PrintCommandArguments(cmd);
         if (MS.createNewCommand)
         {
             if (db.commands.Where(c => c.Key == cmdId).Count() != 0)
             {
                 //fails, command with that ID already exists!!!
                 Console.WriteLine("\nFailed to insert command to DB. Command of id {0} already exists.\n\n", cmdId);
                 sendResponse(MS, false, "The command with id " + cmdId + " could not be added to DB since a command with same ID already exists. Why don't you try updating it instead fam?.");
             }
             else
             {
                 db.commands.Add(cmdId, cmd);
                 //Success
                 Console.WriteLine("SUCCESSFULLY ADDED CMD WITH {0}\n\n", cmdId);
                 sendResponse(MS, true, "Command of id " + cmdId + " has been added to the DB successfully.");
             }
         }
         else
         {
             if (db.commands.Where(c => c.Key == cmdId).Count() == 0)
             {
                 //fails, command with that ID does not exist, so cannot update
                 Console.WriteLine("Failed to update command of id {0} since no such command exists in DB.", cmdId);
                 sendResponse(MS, false, "The command you are trying to update does not exist. Check that the command with ID " + cmdId + " exists first.");
             }
             else
             {
                 db.commands[cmdId] = cmd;
                 //Success
                 Console.WriteLine("SUCCESSFULLY UPDATED CMD OF ID {0}\n\n", cmdId);
                 sendResponse(MS, true, "Command of id " + cmdId + " has been updated successfully.");
             }
         }
     }
     else
     {
         //fail instantly
         Console.WriteLine("Could not run MODIFY command since some of the mandatory fields in Master Command are not valid.\n\n");
         sendResponse(MS, false, "Issue adding command, some of the mandatory fields are empty! Check what values you are passing pls.");
     }
 }
Example #5
0
        static void sendResponse(MasterCommand cmdRespondingTo, bool success, string information = "")
        {
            ResponseLocalhost response = new ResponseLocalhost()
            {
                success     = success,
                commandType = cmdRespondingTo.commandType,
                information = information
            };
            string     jsonString = Jil.JSON.Serialize(response);
            Socket     s          = new Socket(System.Net.Sockets.AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint endPoint   = new IPEndPoint(IPAddress.Parse(netinfo.localhost), netinfo.hostport);

            Console.WriteLine("Sent to 127.0.0.1:" + endPoint.Port + "\n" + jsonString);
            s.SendTo(ASCIIEncoding.ASCII.GetBytes(jsonString), endPoint);
        }
Example #6
0
 /// <summary>
 ///  主站遥控命令 双命令
 /// </summary>
 /// <param name="cot">传输原因</param>
 /// <param name="dco">单命令</param>
 /// <param name="objectAddr">信息对象地址</param>
 private void SendMasterCommand(CauseOfTransmissionList cot, DoubleCommand dco, UInt32 objectAddr)
 {
     try
     {
         var id = TypeIdentification.C_DC_NA_1;//遥控命令
         eventTypeIDManager.AddEventProcess(new EventProperty(id));
         var frame = new MasterCommand(appMessageManager.TransmitSequenceNumber, appMessageManager.RealReceiveSequenceNumber,
                                       id, cot, appMessageManager.ASDUADdress, objectAddr, dco.DCO);
         var array = frame.GetAPDUDataArray();
         MainTypeIProcess(array, array.Length, appMessageManager.WaitTime, id);
         appMessageManager.UpdateTransmitSequenceNumber();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "SendMasterCommand主站遥控命令");
     }
 }
Example #7
0
 /// <summary>
 ///  电能召唤命令
 /// </summary>
 /// <param name="cot">传输原因</param>
 /// <param name="qcc">计量召唤限定词QCC</param>
 /// <param name="objectAddr">公共地址</param>
 private void SendMasterCommand(CauseOfTransmissionList cot, QualifyCalculateCommad qcc)
 {
     try
     {
         var id = TypeIdentification.C_CI_NA_1;//电能召唤
         eventTypeIDManager.AddEventProcess(new EventProperty(id));
         var frame = new MasterCommand(appMessageManager.TransmitSequenceNumber, appMessageManager.RealReceiveSequenceNumber,
                                       id, cot, appMessageManager.ASDUADdress, 0, qcc.QCC);
         var array = frame.GetAPDUDataArray();
         MainTypeIProcess(array, array.Length, appMessageManager.WaitTime, id);
         appMessageManager.UpdateTransmitSequenceNumber();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "SendMasterCommand电能召唤命令");
     }
 }
Example #8
0
        /// <summary>
        /// This function fires based on MasterCommand received from localhost. The MasterCommand will control this function's actions
        /// </summary>
        static void executeMasterCommand(MasterCommand MS)
        {
            //Example of command packet creation, includes argument check, creation and endianness set. True if bigEndian, flase if littleEndian.
            //CommandPacketSendReceiveExample(true);

            /*
             * On "Manufacturer device" run packet listener to detect these commands being sent
             * PacketListener();
             */
            switch (MS.commandType)
            {
            case "SEND":
                MasterCommandSend(MS);
                break;

            case "MODIFY":
                MasterCommandModify(MS);
                break;

            case "REQUEST":
                MasterCommandRequest(MS);
                break;
            }
        }