Ejemplo n.º 1
0
        //--------
        //-------- Constructors
        //--------

        /// <summary>
        /// Constructs a new u packet builder.
        /// </summary>
        /// <param name="startUState">   the object that contains the U brick state
        ///                        which is reference when creating packets </param>
        public UPacketBuilder(UAdapterState startUState)
        {
            // get a reference to the U state
            uState = startUState;

            // create the buffer for the data
            packet = new RawSendPacket();

            // create the vector
            packetsVector = new List <RawSendPacket>();

            // restart the packet to initialize
            restart();

            // no bit banging supported
            bitsOnly = false;

            // check for a bits only property
            string bits = OneWireAccessProvider.getProperty("onewire.serial.forcebitsonly");

            if (!string.ReferenceEquals(bits, null))
            {
                if (bits.IndexOf("true", StringComparison.Ordinal) != -1)
                {
                    bitsOnly = true;
                }
                else if (bits.IndexOf("false", StringComparison.Ordinal) != -1)
                {
                    bitsOnly = false;
                }
            }
        }
Ejemplo n.º 2
0
        private void SetupServer()
        {
            DSPortAdapter adapter;

            if (string.ReferenceEquals(m_adapterName, null) || string.ReferenceEquals(m_adapterPort, null))
            {
                adapter = OneWireAccessProvider.DefaultAdapter;
            }
            else
            {
                adapter = OneWireAccessProvider.getAdapter(m_adapterName, m_adapterPort);
            }

            OneWireEventSource.Log.Info(
                "  Adapter Name: " + adapter.AdapterName + "\r\n" +
                "  Adapter Name: " + adapter.PortName + "\r\n" +
                "  Host Listen Port: " + m_listenPort + "\r\n" +
                "  Multithreaded Host: " + (m_multithread ? "Enabled" : "Disabled") + "\r\n" +
                "  Shared Secret: '" + m_secret + "'\r\n" +
                "  Multicast: " + (m_multicast ? "Enabled" : "Disabled") + "\r\n" +
                "  Multicast Port: " + m_mcPort + "\r\n" +
                "  Multicast Group: " + m_mcGroup + "\r\n");

            // Create the NetAdapterHost
            m_host = new NetAdapterHost(adapter, m_listenPort, m_multithread);

            // set the shared secret
            m_host.Secret = m_secret;

            if (m_multicast)
            {
                OneWireEventSource.Log.Info("Starting Multicast Listener");
                m_host.createMulticastListener(m_mcPort, m_mcGroup);
            }
        }
Ejemplo n.º 3
0
        private static DSPortAdapter FindAdapter()
        {
            try
            {
                if (ConfigFile.DocumentElement == null)
                {
                    throw new Exception();
                }
                var adapterNode = ConfigFile.DocumentElement.SelectSingleNode("adapter");
                if (adapterNode == null)
                {
                    throw new Exception();
                }
                if (adapterNode.Attributes == null)
                {
                    throw new Exception();
                }
                var adapterNameAttribute = adapterNode.Attributes["name"];
                if (adapterNameAttribute == null)
                {
                    throw new Exception();
                }
                var portAttribute = adapterNode.Attributes["port"];

                return(OneWireAccessProvider.getAdapter(adapterNameAttribute.Value, (portAttribute == null) ? null : portAttribute.Value));
            }
            catch (Exception exception)
            {
                // Configuration not found, or configured adapter not found, try to autodetect adapter
                Logger.Logger.Log("Configuration not found, or configured adapter not found ({0}), try to autodetect adapter...", exception.Message);
                return(OneWireAccessProvider.getDefaultAdapter());
            }
        }
Ejemplo n.º 4
0
        public void RunInterface(string pluginName)
        {
            osae.AddToLog("Loading (0.2.4)...", true);
            osae.AddToLog("Current Environment Version: " + Environment.Version.Major.ToString(), true);
            if (Environment.Version.Major >= 4)
            {
                string folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), @"Microsoft.NET\Framework64\v2.0.50727");
                if (!Directory.Exists(folder))
                {
                    folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), @"Microsoft.NET\Framework\v2.0.50727");
                }
                osae.AddToLog("vjsnativ.dll path: " + folder, false);
                folder = Path.GetFullPath(folder);
                LoadLibrary(Path.Combine(folder, "vjsnativ.dll"));
            }
            pName = pluginName;
            string adapterProp = osae.GetObjectPropertyValue(pName, "Adapter").Value;
            string port        = osae.GetObjectPropertyValue(pName, "Port").Value;

            uom = osae.GetObjectPropertyValue(pName, "Unit of Measure").Value;
            osae.AddToLog("adapterProp: " + adapterProp, false);
            osae.AddToLog("port: " + port, false);
            osae.AddToLog("uom: " + uom, false);
            try
            {
                adapter = OneWireAccessProvider.getAdapter(adapterProp, "COM" + port);
            }
            catch (Exception ex)
            {
                osae.AddToLog("Failed to GetAdapter - " + ex.Message + " - " + ex.InnerException.Message, true);
            }


            if (adapter.adapterDetected())
            {
                osae.AddToLog("Adapter Detected", true);
                adapter.setSearchAllDevices();

                Clock = new System.Threading.Timer(poll, null, 0, 10000);

                if (restarting)
                {
                    restarting = false;
                }
            }



            else
            {
                osae.AddToLog("Adapter(" + adapterProp + ") not found on port " + port, true);
            }
        }
Ejemplo n.º 5
0
        private void GetProperties()
        {
            string test = OneWireAccessProvider.getProperty("onewire.adapter.default");

            if (!string.ReferenceEquals(test, null))
            {
                m_adapterName = test;
            }

            test = OneWireAccessProvider.getProperty("onewire.port.default");
            if (!string.ReferenceEquals(test, null))
            {
                m_adapterPort = test;
            }

            test = OneWireAccessProvider.getProperty("NetAdapter.ListenPort");
            if (!string.ReferenceEquals(test, null))
            {
                m_listenPort = test;
            }

            test = OneWireAccessProvider.getProperty("NetAdapter.Multithread");
            if (!string.ReferenceEquals(test, null))
            {
                m_multithread = Convert.ToBoolean(test);
            }

            test = OneWireAccessProvider.getProperty("NetAdapter.Secret");
            if (!string.ReferenceEquals(test, null))
            {
                m_secret = test;
            }

            test = OneWireAccessProvider.getProperty("NetAdapter.Multicast");
            if (!string.ReferenceEquals(test, null))
            {
                m_multicast = Convert.ToBoolean(test);
            }

            test = OneWireAccessProvider.getProperty("NetAdapter.MulticastPort");
            if (!string.ReferenceEquals(test, null))
            {
                m_mcPort = int.Parse(test);
            }

            test = OneWireAccessProvider.getProperty("NetAdapter.MulticastGroup");
            if (!string.ReferenceEquals(test, null))
            {
                m_mcGroup = test;
            }
        }
Ejemplo n.º 6
0
        public override void RunInterface(string pluginName)
        {
            pName = pluginName;
            Log   = new General.OSAELog(pName);
            Log.Info("Current Environment Version: " + Environment.Version.Major.ToString());
            if (Environment.Version.Major >= 4)
            {
                string folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), @"Microsoft.NET\Framework64\v2.0.50727");
                if (!Directory.Exists(folder))
                {
                    folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), @"Microsoft.NET\Framework\v2.0.50727");
                }

                Log.Debug("vjsnativ.dll path: " + folder);
                folder = Path.GetFullPath(folder);
                LoadLibrary(Path.Combine(folder, "vjsnativ.dll"));
            }

            string adapterProp = OSAEObjectPropertyManager.GetObjectPropertyValue(pName, "Adapter").Value;
            string port        = OSAEObjectPropertyManager.GetObjectPropertyValue(pName, "Port").Value;

            uom = OSAEObjectPropertyManager.GetObjectPropertyValue(pName, "Unit of Measure").Value;
            Log.Debug("adapterProp: " + adapterProp + ", port: " + port + ", uom: " + uom);
            try
            {
                adapter = OneWireAccessProvider.getAdapter(adapterProp, "COM" + port);
            }
            catch (Exception ex)
            { Log.Error("Failed to GetAdapter ", ex); }


            if (adapter.adapterDetected())
            {
                Log.Info("Adapter Detected");
                adapter.setSearchAllDevices();

                Clock = new System.Threading.Timer(poll, null, 0, 10000);

                if (restarting)
                {
                    restarting = false;
                }
            }
            else
            {
                Log.Info("Adapter(" + adapterProp + ") not found on port " + port);
            }
        }
Ejemplo n.º 7
0
        private static void GetSupportedAdapters()
        {
            var adapters = OneWireAccessProvider.enumerateAllAdapters();

            if (!adapters.hasMoreElements())
            {
                throw new Exception("No adapter is supported. Maybe the 1-wire driver is not correctly installed (see http://www.maximintegrated.com/products/ibutton/software/tmex/download_drivers.cfm)");
            }

            var supportedAdapterString = "Supported adapters are : ";

            while (adapters.hasMoreElements())
            {
                supportedAdapterString += ((DSPortAdapter)adapters.nextElement()).getAdapterName() + " ";
            }
            Logger.Logger.Log(supportedAdapterString);
        }
Ejemplo n.º 8
0
        private void SetupLogging()
        {
            string enable = OneWireAccessProvider.getProperty("onewire.debug");

            if (!string.ReferenceEquals(enable, null) && enable.ToLower().Equals("true"))
            {
                DEBUG = true;
            }
            else
            {
                DEBUG = false;
            }

            string logFile = OneWireAccessProvider.getProperty("onewire.debug.logfile");

            if (!string.ReferenceEquals(logFile, null))
            {
                if (DEBUG)
                {
                    // ignore any absolute path provided, only use filename
                    string[]      strtok      = logFile.Split(new char[] { '\\' });
                    StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                    string        logFilePath = localFolder.Path + "\\" + strtok[strtok.Length - 1].Trim();

                    Debug.WriteLine("Log location: " + ApplicationData.Current.LocalFolder.Path);
                    EventListener listener = new StorageFileEventListener(logFile);
                    listener.EnableEvents(OneWireEventSource.Log, EventLevel.Verbose);
                }
                else
                {
                    Debug.WriteLine("Log location: " + ApplicationData.Current.LocalFolder.Path);
                    EventListener listener = new StorageFileEventListener("log");
                    listener.EnableEvents(OneWireEventSource.Log, EventLevel.Informational);
                }
            }
            else
            {
                Debug.WriteLine("Log location: " + ApplicationData.Current.LocalFolder.Path);
                EventListener listener = new StorageFileEventListener("log");
                listener.EnableEvents(OneWireEventSource.Log, EventLevel.Informational);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Static constructor.  Checks system properties to see if debugging
        /// is enabled by default.  Also, will redirect debug output to a log
        /// file if specified.
        /// </summary>
        static Debug()
        {
            string enable = OneWireAccessProvider.getProperty("onewire.debug");

            if (!string.ReferenceEquals(enable, null) && enable.ToLower().Equals("true"))
            {
                DEBUG = true;
            }
            else
            {
                DEBUG = false;
            }

            if (DEBUG)
            {
                string logFile = OneWireAccessProvider.getProperty("onewire.debug.logfile");
                if (!string.ReferenceEquals(logFile, null))
                {
                    // ignore any absolute path provided, only use filename
                    string[]      strtok      = logFile.Split(new char[] { '\\' });
                    StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                    string        logFilePath = localFolder.Path + "\\" + strtok[strtok.Length - 1].Trim();

                    System.Diagnostics.Debug.WriteLine(logFilePath);

                    try
                    {
                        @out           = new StreamWriter(new FileStream(logFilePath, FileMode.Create, FileAccess.Write));
                        @out.AutoFlush = true;
                    }
                    catch (System.Exception e)
                    {
                        @out  = null;
                        DEBUG = false;
                        debug("Error opening log file in Debug Static Constructor", e);
                    }
                }
            }
        }
Ejemplo n.º 10
0
    /// <summary>
    /// Method main
    ///
    /// </summary>
    /// <param name="args">
    /// </param>
    /// <exception cref="OneWireException"> </exception>
    /// <exception cref="OneWireIOException">
    ///  </exception>
    public static void Main1(string[] args)
    {
        bool          usedefault   = false;
        DSPortAdapter access       = null;
        string        adapter_name = null;
        string        port_name    = null;

        if ((args == null) || (args.Length < 1))
        {
            try
            {
                access = OneWireAccessProvider.DefaultAdapter;

                if (access == null)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                Debug.WriteLine("Couldn't get default adapter!");
                printUsageString();

                return;
            }

            usedefault = true;
        }

        if (!usedefault)
        {
            string[] st = args[0].Split(new char[] { '_' });

            if (st.Length != 2)
            {
                printUsageString();

                return;
            }

            adapter_name = st[0];
            port_name    = st[1];

            Debug.WriteLine("Adapter Name: " + adapter_name);
            Debug.WriteLine("Port Name: " + port_name);
        }

        if (access == null)
        {
            try
            {
                access = OneWireAccessProvider.getAdapter(adapter_name, port_name);
            }
            catch (Exception)
            {
                Debug.WriteLine("That is not a valid adapter/port combination.");

                System.Collections.IEnumerator en = OneWireAccessProvider.enumerateAllAdapters();

                while (en.MoveNext())
                {
                    DSPortAdapter temp = (DSPortAdapter)en.Current;

                    Debug.WriteLine("Adapter: " + temp.AdapterName);

                    System.Collections.IEnumerator f = temp.PortNames;

                    while (f.MoveNext())
                    {
                        Debug.WriteLine("   Port name : " + ((string)f.Current));
                    }
                }

                return;
            }
        }

        access.adapterDetected();
        access.targetAllFamilies();
        access.beginExclusive(true);
        access.reset();
        access.setSearchAllDevices();

        bool next = access.findFirstDevice();

        if (!next)
        {
            Debug.WriteLine("Could not find any iButtons!");

            return;
        }

        while (next)
        {
            OneWireContainer owc = access.DeviceContainer;

            Debug.WriteLine("====================================================");
            Debug.WriteLine("= Found One Wire Device: " + owc.AddressAsString + "          =");
            Debug.WriteLine("====================================================");
            Debug.WriteLine("=");

            bool isPotContainer       = false;
            PotentiometerContainer pc = null;

            try
            {
                pc             = (PotentiometerContainer)owc;
                isPotContainer = true;
            }
            catch (InvalidCastException)
            {
                pc             = null;
                isPotContainer = false;         //just to reiterate
            }

            if (isPotContainer)
            {
                Debug.WriteLine("= This device is a " + owc.Name);
                Debug.WriteLine("= Also known as a " + owc.AlternateNames);
                Debug.WriteLine("=");
                Debug.WriteLine("= It is a Potentiometer Container");

                byte[] state       = pc.readDevice();
                bool   charge      = pc.isChargePumpOn(state);
                int    wiper       = pc.getCurrentWiperNumber(state);
                int    position    = pc.WiperPosition;
                bool   linear      = pc.isLinear(state);
                int    numPots     = pc.numberOfPotentiometers(state);
                int    numSettings = pc.numberOfWiperSettings(state);
                int    resistance  = pc.potentiometerResistance(state);

                Debug.WriteLine("=");
                Debug.WriteLine("= Charge pump is " + (charge ? "ON" : "OFF"));
                Debug.WriteLine("= This device has " + numPots + " potentiometer" + ((numPots > 1) ? "s" : ""));
                Debug.WriteLine("= This device has a " + (linear ? "linear" : "logarithmic") + " potentiometer");
                Debug.WriteLine("= It uses " + numSettings + " potentiometer wiper settings");
                Debug.WriteLine("= The potentiometer resistance is " + resistance + " kOhms");
                Debug.WriteLine("= CURRENT WIPER NUMBER  : " + wiper);
                Debug.WriteLine("= CURRENT WIPER POSITION: " + position);
                Debug.WriteLine("= Trying to toggle the charge pump...");
                pc.setChargePump(!charge, state);
                pc.writeDevice(state);

                state = pc.readDevice();

                if (charge == pc.isChargePumpOn(state))
                {
                    Debug.WriteLine("= Could not toggle charge pump.  Must have external power supplied.");
                }
                else
                {
                    Debug.WriteLine("= Toggled charge pump successfully");
                }

                //int newwiper = (int)((DateTime.Now.Ticks & 0x0ff00) >> 8);
                //pc.WiperPosition = newwiper;
                //Debug.WriteLine("= Setting wiper position to " + (newwiper));
                Debug.WriteLine("= CURRENT WIPER POSITION: " + pc.WiperPosition);
            }
            else
            {
                Debug.WriteLine("= This device is not a potentiometer device.");
                Debug.WriteLine("=");
                Debug.WriteLine("=");
            }

            next = access.findNextDevice();
        }
    }
Ejemplo n.º 11
0
    /// <summary>
    /// Method main
    ///
    /// </summary>
    /// <param name="args">
    /// </param>
    /// <exception cref="OneWireException"> </exception>
    /// <exception cref="OneWireIOException">
    ///  </exception>
    public static void Main1(string[] args)
    {
        bool          usedefault   = false;
        DSPortAdapter access       = null;
        string        adapter_name = null;
        string        port_name    = null;

        if ((args == null) || (args.Length < 1))
        {
            try
            {
                access = OneWireAccessProvider.DefaultAdapter;

                if (access == null)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                Debug.WriteLine("Couldn't get default adapter!");
                printUsageString();

                return;
            }

            usedefault = true;
        }

        if (!usedefault)
        {
            string[] st = args[0].Split(new char[] { '_' });


            if (st.Length != 2)
            {
                printUsageString();

                return;
            }

            adapter_name = st[0];
            port_name    = st[1];

            Debug.WriteLine("Adapter Name: " + adapter_name);
            Debug.WriteLine("Port Name: " + port_name);
        }

        if (access == null)
        {
            try
            {
                access = OneWireAccessProvider.getAdapter(adapter_name, port_name);
            }
            catch (Exception)
            {
                Debug.WriteLine("That is not a valid adapter/port combination.");

                System.Collections.IEnumerator en = OneWireAccessProvider.enumerateAllAdapters();

                while (en.MoveNext())
                {
                    DSPortAdapter temp = (DSPortAdapter)en.Current;

                    Debug.WriteLine("Adapter: " + temp.AdapterName);

                    System.Collections.IEnumerator f = temp.PortNames;

                    while (f.MoveNext())
                    {
                        Debug.WriteLine("   Port name : " + ((string)f.Current));
                    }
                }

                return;
            }
        }

        access.adapterDetected();
        access.targetAllFamilies();
        access.beginExclusive(true);
        access.reset();
        access.setSearchAllDevices();

        bool next = access.findFirstDevice();

        if (!next)
        {
            Debug.WriteLine("Could not find any iButtons!");

            return;
        }

        while (next)
        {
            OneWireContainer owc = access.DeviceContainer;

            Debug.WriteLine("====================================================");
            Debug.WriteLine("= Found One Wire Device: " + owc.AddressAsString + "          =");
            Debug.WriteLine("====================================================");
            Debug.WriteLine("=");

            bool            isSwitchContainer = false;
            SwitchContainer sc = null;

            try
            {
                sc = (SwitchContainer)owc;
                isSwitchContainer = true;
            }
            catch (InvalidCastException)
            {
                sc = null;
                isSwitchContainer = false;         //just to reiterate
            }

            if (isSwitchContainer)
            {
                Debug.WriteLine("= This device is a " + owc.Name);
                Debug.WriteLine("= Also known as a " + owc.AlternateNames);
                Debug.WriteLine("=");
                Debug.WriteLine("= It is a Switch Container");
                if (sc.hasActivitySensing())
                {
                    sc.clearActivity();
                }

                byte[] state    = sc.readDevice();
                int    channels = sc.getNumberChannels(state);
                bool   activity = sc.hasActivitySensing();
                bool   level    = sc.hasLevelSensing();
                bool   smart    = sc.hasSmartOn();

                Debug.WriteLine("= This device has " + channels + " channel" + (channels > 1 ? "s" : ""));
                Debug.WriteLine("= It " + (activity ? "has" : "does not have") + " activity sensing abilities");
                Debug.WriteLine("= It " + (level ? "has" : "does not have") + " level sensing abilities");
                Debug.WriteLine("= It " + (smart ? "is" : "is not") + " smart-on capable");

                for (int ch = 0; ch < channels; ch++)
                {
                    Debug.WriteLine("======================");
                    Debug.WriteLine("=   Channel " + ch + "        =");
                    Debug.WriteLine("=--------------------=");

                    bool latchstate = sc.getLatchState(ch, state);

                    Debug.WriteLine("= State " + (latchstate ? "ON " : "OFF") + "          =");

                    if (level)
                    {
                        bool sensedLevel = sc.getLevel(ch, state);

                        Debug.WriteLine("= Level " + (sensedLevel ? "HIGH" : "LOW ") + "         =");
                    }

                    if (activity)
                    {
                        bool sensedActivity = sc.getSensedActivity(ch, state);

                        Debug.WriteLine("= Activity " + (sensedActivity ? "YES" : "NO ") + "       =");
                    }

                    Debug.WriteLine("= Toggling switch... =");

                    try
                    {
                        Thread.Sleep(500);
                    }
                    catch (Exception)
                    {
                        /*drain it*/
                    }

                    sc.setLatchState(ch, !latchstate, smart, state);
                    sc.writeDevice(state);

                    state = sc.readDevice();

                    if (latchstate == sc.getLatchState(ch, state))
                    {
                        Debug.WriteLine("= Toggle Failed      =");
                    }
                    else
                    {
                        try
                        {
                            Thread.Sleep(500);
                        }
                        catch (Exception)
                        {
                            /*drain it*/
                        }

                        Debug.WriteLine("= Toggling back...   =");
                        sc.setLatchState(ch, latchstate, smart, state);
                        sc.writeDevice(state);
                    }
                }
            }
            else
            {
                Debug.WriteLine("= This device is not a Switch device.");
                Debug.WriteLine("=");
                Debug.WriteLine("=");
            }

            next = access.findNextDevice();
        }
    }
Ejemplo n.º 12
0
    /// <summary>
    /// Method main
    ///
    /// </summary>
    /// <param name="args">
    /// </param>
    /// <exception cref="IOException"> </exception>
    /// <exception cref="OneWireException"> </exception>
    /// <exception cref="OneWireIOException">
    ///  </exception>
    public static void Main1(string[] args)
    {
        bool          usedefault   = false;
        DSPortAdapter access       = null;
        string        adapter_name = null;
        string        port_name    = null;

        if ((args == null) || (args.Length < 1))
        {
            try
            {
                access = OneWireAccessProvider.DefaultAdapter;

                if (access == null)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                Debug.WriteLine("Couldn't get default adapter!");
                printUsageString();

                return;
            }

            usedefault = true;
        }

        if (!usedefault)
        {
            string[] st = args[0].Split(new char[] { '_' });

            if (st.Length != 2)
            {
                printUsageString();

                return;
            }

            adapter_name = st[0];
            port_name    = st[1];

            Debug.WriteLine("Adapter Name: " + adapter_name);
            Debug.WriteLine("Port Name: " + port_name);
        }

        if (access == null)
        {
            try
            {
                access = OneWireAccessProvider.getAdapter(adapter_name, port_name);
            }
            catch (Exception)
            {
                Debug.WriteLine("That is not a valid adapter/port combination.");

                System.Collections.IEnumerator en = OneWireAccessProvider.enumerateAllAdapters();

                while (en.MoveNext())
                {
                    DSPortAdapter temp = (DSPortAdapter)en.Current;

                    Debug.WriteLine("Adapter: " + temp.AdapterName);

                    System.Collections.IEnumerator f = temp.PortNames;

                    while (f.MoveNext())
                    {
                        Debug.WriteLine("   Port name : " + ((string)f.Current));
                    }
                }

                return;
            }
        }

        access.adapterDetected();
        access.targetFamily(0x21);
        access.beginExclusive(true);
        access.reset();
        access.setSearchAllDevices();

        bool next = access.findFirstDevice();

        if (!next)
        {
            Debug.WriteLine("Could not find any DS1921 Thermochrons!");

            return;
        }

        OneWireContainer21 owc = new OneWireContainer21();

        owc.setupContainer(access, access.AddressAsLong);

        Stream stream = loadResourceFile("Thermochron.input.txt");

        System.IO.StreamReader din = new StreamReader(stream);

        //the following section of code jus gets all these options from the command line
        //to see how to actually talk to the iButton, scroll down until you find
        //the code "disableMission()
        Debug.WriteLine("Dallas Semiconductor DS1921 Thermochron Demo");
        Debug.WriteLine("--------------------------------------------");
        Debug.WriteLine("Initializing mission on iButton " + owc.AddressAsString + "\r\n");

        string tstr;
        bool   rollover = false;

        Debug.Write("Enable rollover (y or n)? ");

        tstr = din.ReadLine();

        if (tstr.Equals("y", StringComparison.CurrentCultureIgnoreCase) || tstr.Equals("yes", StringComparison.CurrentCultureIgnoreCase))
        {
            rollover = true;
        }

        Debug.Write("Enter low temperature alarm in celsius (23) : ");

        int low = parseInt(din, 23);

        Debug.Write("Enter high temperature alarm in celsius (28) : ");

        int  high       = parseInt(din, 28);
        bool clockalarm = false;

        Debug.Write("Enable clock alarm (y or n)? ");

        tstr = din.ReadLine();

        if (tstr.Equals("y", StringComparison.CurrentCultureIgnoreCase) || tstr.Equals("yes", StringComparison.CurrentCultureIgnoreCase))
        {
            clockalarm = true;
        }

        int second    = 0;
        int minute    = 0;
        int hour      = 0;
        int day       = 0;
        int frequency = -1;

        if (clockalarm)
        {
            Debug.WriteLine("Clock alarm enabled.  Enter alarm frequency: ");
            Debug.WriteLine("   0  Once per second");
            Debug.WriteLine("   1  Once per minute");   //need second
            Debug.WriteLine("   2  Once per hour");     //need second, minute
            Debug.WriteLine("   3  Once per day");      //need hour, minute, second
            Debug.WriteLine("   4  Once per week");     //need hour, minute, second, day
            Debug.Write("   ? ");

            int x = parseInt(din, -1);

            if ((x < 0) || (x > 4))
            {
                Debug.WriteLine("That is not a valid clock alarm frequency.");

                return;
            }

            switch (x)      //noteice no breaks!
            {
            case 4:
                if (frequency == -1)
                {
                    frequency = OneWireContainer21.ONCE_PER_WEEK;
                }

                Debug.Write("Day of week to alarm (1==Sunday) : ");

                day = parseInt(din, 1);
                goto case 3;

            case 3:
                if (frequency == -1)
                {
                    frequency = OneWireContainer21.ONCE_PER_DAY;
                }

                Debug.Write("Hour of day to alarm (0 - 23) : ");

                hour = parseInt(din, 0);
                goto case 2;

            case 2:
                if (frequency == -1)
                {
                    frequency = OneWireContainer21.ONCE_PER_HOUR;
                }

                Debug.Write("Minute of hour to alarm (0 - 59) : ");

                minute = parseInt(din, 0);
                goto case 1;

            case 1:
                if (frequency == -1)
                {
                    frequency = OneWireContainer21.ONCE_PER_MINUTE;
                }

                Debug.Write("Second of minute to alarm (0 - 59) : ");

                second = parseInt(din, 0);
                goto case 0;

            case 0:
                if (frequency == -1)
                {
                    frequency = OneWireContainer21.ONCE_PER_SECOND;
                }
                break;
            }
        }

        bool synchronize = false;

        Debug.Write("Set thermochron clock to system clock (y or n)? ");

        tstr = din.ReadLine();

        if (tstr.Equals("y", StringComparison.CurrentCultureIgnoreCase) || tstr.Equals("yes", StringComparison.CurrentCultureIgnoreCase))
        {
            synchronize = true;
        }

        Debug.Write("Start the mission in how many minutes? ");

        int delay = 0;

        delay = parseInt(din, 0);

        Debug.Write("Sampling Interval in minutes (1 to 255)? ");

        int rate = 1;

        rate = parseInt(din, 1);

        //now do some bounds checking
        if (rate < 1)
        {
            rate = 1;
        }

        if (rate > 255)
        {
            rate = 255;
        }

        delay = delay & 0x0ffff;

        int physicalLow  = (int)owc.PhysicalRangeLowTemperature;
        int physicalHigh = (int)owc.PhysicalRangeHighTemperature;

        if (low < physicalLow)
        {
            low = physicalLow;
        }

        if (low > physicalHigh)
        {
            low = physicalHigh;
        }

        if (high < physicalLow)
        {
            high = physicalLow;
        }

        if (high > physicalHigh)
        {
            high = physicalHigh;
        }

        if (day < 1)
        {
            day = 1;
        }

        if (day > 7)
        {
            day = 7;
        }

        second = second % 60;
        minute = minute % 60;
        hour   = hour % 24;

        //some regurgitation first....
        Debug.WriteLine("\r\n\r\nSummary---------------------");
        Debug.WriteLine("Rollover enabled              : " + rollover);
        Debug.WriteLine("Low temperature alarm trigger : " + low);
        Debug.WriteLine("High temperature alarm trigger: " + high);
        Debug.WriteLine("Clock alarm enabled           : " + clockalarm);

        if (clockalarm)
        {
            Debug.Write("Alarm frequency               : ");

            switch (frequency)
            {
            case OneWireContainer21.ONCE_PER_SECOND:
                Debug.WriteLine("Once per second");
                break;

            case OneWireContainer21.ONCE_PER_MINUTE:
                Debug.WriteLine("Once per minute");
                break;

            case OneWireContainer21.ONCE_PER_HOUR:
                Debug.WriteLine("Once per hour");
                break;

            case OneWireContainer21.ONCE_PER_DAY:
                Debug.WriteLine("Once per day");
                break;

            case OneWireContainer21.ONCE_PER_WEEK:
                Debug.WriteLine("Once per week");
                break;

            default:
                Debug.WriteLine("Unknown alarm frequency!!! Bailing!!!");

                return;
            }

            Debug.Write("Alarm setting                 : " + hour + ":" + minute + ":" + second + " ");

            switch (day)
            {
            case 1:
                Debug.WriteLine("Sunday");
                break;

            case 2:
                Debug.WriteLine("Monday");
                break;

            case 3:
                Debug.WriteLine("Tuesday");
                break;

            case 4:
                Debug.WriteLine("Wednesday");
                break;

            case 5:
                Debug.WriteLine("Thursday");
                break;

            case 6:
                Debug.WriteLine("Friday");
                break;

            case 7:
                Debug.WriteLine("Saturday");
                break;

            default:
                Debug.WriteLine("Unknown day of week! Bailing!");

                return;
            }
        }

        Debug.WriteLine("Synchonizing with host clock  : " + synchronize);
        Debug.WriteLine("Mission starts in (minutes)   : " + delay);
        Debug.WriteLine("Sampling rate (minutes)       : " + rate);
        Debug.WriteLine("-------------------------------\r\n");

        //now let's start talking to the thermochron
        //first lets put it into overdrive
        Debug.WriteLine("Putting the part into overdrive...");
        owc.setSpeed(DSPortAdapter.SPEED_OVERDRIVE, true);
        Debug.WriteLine("Disabling current mission...");
        owc.disableMission();
        Debug.WriteLine("Clearing memory...");
        owc.clearMemory();
        Debug.WriteLine("Reading device state...");

        byte[] state = owc.readDevice();

        Debug.WriteLine("Setting rollover flag in state...");
        owc.setFlag(OneWireContainer21.CONTROL_REGISTER, OneWireContainer21.ROLLOVER_ENABLE_FLAG, rollover, state);
        Debug.WriteLine("Setting high alarm in state...");
        owc.setTemperatureAlarm(TemperatureContainer_Fields.ALARM_HIGH, (double)high, state);
        Debug.WriteLine("Setting low alarm in state...");
        owc.setTemperatureAlarm(TemperatureContainer_Fields.ALARM_LOW, (double)low, state);

        if (clockalarm)
        {
            Debug.WriteLine("Setting clock alarm in state...");
            owc.setClockAlarm(hour, minute, second, day, frequency, state);
            Debug.WriteLine("Enabling clock alarm in state...");
            owc.setClockAlarmEnable(true, state);
        }

        if (synchronize)
        {
            Debug.WriteLine("Synchonizing with host clock in state...");
            owc.setClock(DateTime.Now.Ticks * TimeSpan.TicksPerMillisecond, state);
        }

        Debug.WriteLine("Setting mission delay in state...");
        owc.setMissionStartDelay(delay, state);
        Debug.WriteLine("Enabling the clock oscillator in state...");
        owc.setClockRunEnable(true, state);
        Debug.WriteLine("Writing state back to Thermochron...");
        owc.writeDevice(state);
        Debug.WriteLine("Enabling mission...");
        owc.enableMission(rate);
        Debug.WriteLine("Initialization Complete.");

        //       state = owc.readDevice();
        //       for (int i=0;i<state.length;i++)
        //           System.out.println("State["+(i < 0x10 ? "0" : "")+Integer.toHexString(i)+"] == "+Integer.toHexString(0x0ff & state[i]));
    }
Ejemplo n.º 13
0
    /// <summary>
    /// Method main
    ///
    /// </summary>
    /// <param name="args">
    /// </param>
    /// <exception cref="OneWireException"> </exception>
    /// <exception cref="OneWireIOException">
    ///  </exception>
    public static void Main1(string[] args)
    {
        bool          usedefault   = false;
        DSPortAdapter access       = null;
        string        adapter_name = null;
        string        port_name    = null;

        if ((args == null) || (args.Length < 1))
        {
            try
            {
                access = OneWireAccessProvider.DefaultAdapter;

                if (access == null)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                Debug.WriteLine("Couldn't get default adapter!");
                printUsageString();

                return;
            }

            usedefault = true;
        }

        if (!usedefault)
        {
            string[] st = args[0].Split(new char[] { '_' });

            if (st.Length != 2)
            {
                printUsageString();

                return;
            }

            adapter_name = st[0];
            port_name    = st[1];

            Debug.WriteLine("Adapter Name: " + adapter_name);
            Debug.WriteLine("Port Name: " + port_name);
        }

        if (access == null)
        {
            try
            {
                access = OneWireAccessProvider.getAdapter(adapter_name, port_name);
            }
            catch (Exception)
            {
                Debug.WriteLine("That is not a valid adapter/port combination.");

                System.Collections.IEnumerator en = OneWireAccessProvider.enumerateAllAdapters();

                while (en.MoveNext())
                {
                    DSPortAdapter temp = (DSPortAdapter)en.Current;

                    Debug.WriteLine("Adapter: " + temp.AdapterName);

                    System.Collections.IEnumerator f = temp.PortNames;

                    while (f.MoveNext())
                    {
                        Debug.WriteLine("   Port name : " + ((string)f.Current));
                    }
                }

                return;
            }
        }

        access.adapterDetected();
        access.targetAllFamilies();
        access.beginExclusive(true);
        access.reset();
        access.setSearchAllDevices();

        bool next = access.findFirstDevice();

        if (!next)
        {
            Debug.WriteLine("Could not find any iButtons!");

            return;
        }

        while (next)
        {
            OneWireContainer owc = access.DeviceContainer;

            Debug.WriteLine("====================================================");
            Debug.WriteLine("= Found One Wire Device: " + owc.AddressAsString + "          =");
            Debug.WriteLine("====================================================");
            Debug.WriteLine("=");

            bool           isClockContainer = false;
            ClockContainer cc = null;

            try
            {
                cc = (ClockContainer)owc;
                isClockContainer = true;
            }
            catch (Exception)
            {
                cc = null;
                isClockContainer = false;         //just to reiterate
            }

            if (isClockContainer)
            {
                Debug.WriteLine("= This device is a " + owc.Name);
                Debug.WriteLine("= Also known as a " + owc.AlternateNames);
                Debug.WriteLine("=");
                Debug.WriteLine("= It is a Clock Container");

                byte[] state      = cc.readDevice();
                long   resolution = cc.ClockResolution;

                Debug.WriteLine("= The clock resolution is " + resolution + " milliseconds");

                bool alarm = cc.hasClockAlarm();

                Debug.WriteLine("= This clock " + (alarm ? "does" : "does not") + " have a clock alarm");

                long rtc = cc.getClock(state);

                Debug.WriteLine("= Clock raw time: " + rtc);
                Debug.WriteLine("= Readable clock time: " + new DateTime(rtc));

                bool alarmenabled = false;

                if (alarm)
                {
                    long aclock = cc.getClockAlarm(state);

                    alarmenabled = cc.isClockAlarmEnabled(state);

                    bool alarming = cc.isClockAlarming(state);

                    Debug.WriteLine("= Raw clock alarm: " + aclock);
                    Debug.WriteLine("= Readable clock alarm: " + new DateTime(aclock));
                    Debug.WriteLine("= The alarm is" + (alarmenabled ? "" : " not") + " enabled");
                    Debug.WriteLine("= The alarm is" + (alarming ? "" : " not") + " alarming");
                }

                bool running    = cc.isClockRunning(state);
                bool candisable = cc.canDisableClock();

                Debug.WriteLine("= The clock is" + (running ? "" : " not") + " running");
                Debug.WriteLine("= The clock can" + (candisable ? "" : " not") + " be disabled");

                TimeSpan t = new TimeSpan(DateTime.Now.Ticks);
                cc.setClock((long)t.TotalMilliseconds, state);

                if (alarm)
                {
                    try
                    {
                        cc.setClockAlarm((long)t.TotalMilliseconds + 1000 * 60, state);
                        Debug.WriteLine("= Set the clock alarm");
                    }
                    catch (Exception)
                    {
                        Debug.WriteLine("= Could not set the clock alarm");
                    }

                    cc.setClockAlarmEnable(!alarmenabled, state);
                    Debug.WriteLine("= " + (alarmenabled ? "Disabled" : "Enabled") + " the clock alarm");
                }

                if (candisable)
                {
                    cc.setClockRunEnable(!running, state);
                    Debug.WriteLine("= " + (running ? "Disabled" : "Enabled") + " the clock oscillator");
                }

                Debug.WriteLine("= Writing device state...");

                try
                {
                    cc.writeDevice(state);
                    Debug.WriteLine("= Successfully wrote device state");
                }
                catch (Exception e)
                {
                    Debug.WriteLine("= Failed to write device state: " + e.ToString());
                }
            }
            else
            {
                Debug.WriteLine("= This device is not a Clock device.");
                Debug.WriteLine("=");
                Debug.WriteLine("=");
            }

            next = access.findNextDevice();
        }
    }
Ejemplo n.º 14
0
        /// <summary>
        /// Method main
        ///
        /// </summary>
        /// <param name="args">
        /// </param>
        /// <exception cref="OneWireException"> </exception>
        /// <exception cref="OneWireIOException">
        ///  </exception>

        public static void Main1([ReadOnlyArray()] string[] args)
        {
            bool          usedefault   = false;
            DSPortAdapter access       = null;
            string        adapter_name = null;
            string        port_name    = null;

            if ((args == null) || (args.Length < 1))
            {
                try
                {
                    access = OneWireAccessProvider.DefaultAdapter;

                    if (access == null)
                    {
                        throw new Exception();
                    }
                }
                catch (Exception)
                {
                    Debug.WriteLine("Couldn't get default adapter!");
                    printUsageString();

                    return;
                }

                usedefault = true;
            }

            if (!usedefault)
            {
                //parse device instance

                //string[] st = args[0].Split(new char[] { '_' });

                if (args.Length != 2)
                {
                    printUsageString();

                    return;
                }

                adapter_name = args[0];
                port_name    = args[1];

                Debug.WriteLine("Adapter Name: " + adapter_name);
                Debug.WriteLine("Port Name: " + port_name);
            }

            if (access == null)
            {
                try
                {
                    access = OneWireAccessProvider.getAdapter(adapter_name, port_name);
                }
                catch (Exception)
                {
                    Debug.WriteLine("That is not a valid adapter/port combination.");

                    System.Collections.IEnumerator en = OneWireAccessProvider.enumerateAllAdapters();

                    while (en.MoveNext())
                    {
                        DSPortAdapter temp = (DSPortAdapter)en.Current;

                        Debug.WriteLine("Adapter: " + temp.AdapterName);

                        System.Collections.IEnumerator f = temp.PortNames;

                        while (f.MoveNext())
                        {
                            Debug.WriteLine("   Port name : " + ((DeviceInformation)f.Current).Id);
                        }
                    }

                    return;
                }
            }

            access.adapterDetected();
            access.targetAllFamilies();
            access.beginExclusive(true);
            access.reset();
            access.setSearchAllDevices();

            bool next = access.findFirstDevice();

            if (!next)
            {
                Debug.WriteLine("Could not find any iButtons!");

                return;
            }

            while (next)
            {
                OneWireContainer owc = access.DeviceContainer;

                Debug.WriteLine("====================================================");
                Debug.WriteLine("= Found One Wire Device: " + owc.AddressAsString + "          =");
                Debug.WriteLine("====================================================");
                Debug.WriteLine("=");

                bool isTempContainer    = false;
                TemperatureContainer tc = null;

                try
                {
                    tc = (TemperatureContainer)owc;
                    isTempContainer = true;
                }
                catch (System.InvalidCastException)
                {
                    tc = null;
                    isTempContainer = false; //just to reiterate
                }

                if (isTempContainer)
                {
                    Debug.WriteLine("= This device is a " + owc.Name);
                    Debug.WriteLine("= Also known as a " + owc.AlternateNames);
                    Debug.WriteLine("=");
                    Debug.WriteLine("= It is a Temperature Container");

                    double max       = tc.MaxTemperature;
                    double min       = tc.MinTemperature;
                    bool   hasAlarms = tc.hasTemperatureAlarms();

                    Debug.WriteLine("= This device " + (hasAlarms ? "has" : "does not have") + " alarms");
                    Debug.WriteLine("= Maximum temperature: " + max);
                    Debug.WriteLine("= Minimum temperature: " + min);

                    double high  = 0.0;
                    double low   = 0.0;
                    byte[] state = tc.readDevice();

                    if (hasAlarms)
                    {
                        high = tc.getTemperatureAlarm(TemperatureContainer_Fields.ALARM_HIGH, state);
                        low  = tc.getTemperatureAlarm(TemperatureContainer_Fields.ALARM_LOW, state);

                        Debug.WriteLine("= High temperature alarm set to : " + high);
                        Debug.WriteLine("= Low temperature alarm set to  : " + low);
                    }

                    double resol      = 0.0;
                    bool   selectable = tc.hasSelectableTemperatureResolution();

                    if (hasAlarms)
                    {
                        resol = tc.TemperatureAlarmResolution;

                        Debug.WriteLine("= Temperature alarm resolution  : " + resol);
                    }

                    double   tempres    = tc.getTemperatureResolution(state);
                    double[] resolution = null;

                    Debug.WriteLine("= Temperature resolution        : " + tempres);
                    Debug.WriteLine("= Resolution is selectable      : " + selectable);

                    if (selectable)
                    {
                        try
                        {
                            resolution = tc.TemperatureResolutions;

                            for (int i = 0; i < resolution.Length; i++)
                            {
                                Debug.WriteLine("= Available resolution " + i + "        : " + resolution[i]);
                            }
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine("= Could not get available resolutions : " + e.ToString());
                        }
                    }

                    if (hasAlarms)
                    {
                        Debug.WriteLine("= Setting high temperature alarm to 28.0 C...");
                        tc.setTemperatureAlarm(TemperatureContainer_Fields.ALARM_HIGH, 28.0, state);
                        Debug.WriteLine("= Setting low temperature alarm to 23.0 C...");
                        tc.setTemperatureAlarm(TemperatureContainer_Fields.ALARM_LOW, 23.0, state);
                    }

                    if (selectable)
                    {
                        try
                        {
                            Debug.WriteLine("= Setting temperature resolution to " + resolution[0] + "...");
                            tc.setTemperatureResolution(resolution[0], state);
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine("= Could not set resolution: " + e.ToString());
                        }
                    }

                    try
                    {
                        tc.writeDevice(state);
                        Debug.WriteLine("= Device state written.");
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("= Could not write device state, all changes lost.");
                        Debug.WriteLine("= Exception occurred: " + e.ToString());
                    }

                    Debug.WriteLine("= Doing temperature conversion...");

                    try
                    {
                        tc.doTemperatureConvert(state);
                    }
                    catch (Exception)
                    {
                        Debug.WriteLine("= Could not complete temperature conversion...");
                    }

                    state = tc.readDevice();

                    if (hasAlarms)
                    {
                        high = tc.getTemperatureAlarm(TemperatureContainer_Fields.ALARM_HIGH, state);
                        low  = tc.getTemperatureAlarm(TemperatureContainer_Fields.ALARM_LOW, state);

                        Debug.WriteLine("= High temperature alarm set to : " + high);
                        Debug.WriteLine("= Low temperature alarm set to  : " + low);
                    }

                    double temp = tc.getTemperature(state);

                    Debug.WriteLine("= Reported temperature: " + temp);
                }
                else
                {
                    Debug.WriteLine("= This device is not a temperature device.");
                    Debug.WriteLine("=");
                    Debug.WriteLine("=");
                }

                next = access.findNextDevice();
            }
        }
Ejemplo n.º 15
0
    /// <summary>
    /// Method main
    ///
    /// </summary>
    /// <param name="args">
    /// </param>
    /// <exception cref="OneWireException"> </exception>
    /// <exception cref="OneWireIOException">
    ///  </exception>
    public static void Main1(string[] args)
    {
        bool          show_history   = false;
        bool          show_log       = false;
        bool          show_histogram = false;
        bool          pre_kill       = false;
        bool          post_kill      = false;
        bool          usedefault     = false;
        DSPortAdapter access         = null;
        string        adapter_name   = null;
        string        port_name      = null;
        Stopwatch     stopWatch      = new Stopwatch();

        if ((args == null) || (args.Length < 1) || (args [0].IndexOf("_", StringComparison.Ordinal) == -1))
        {
            try
            {
                access = OneWireAccessProvider.DefaultAdapter;

                if (access == null)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                Debug.WriteLine("Couldn't get default adapter!");
                printUsageString();

                return;
            }

            usedefault = true;
        }

        if ((args != null) && (args.Length > 0) && (usedefault))
        {
            string arg = args [0];

            if (arg.IndexOf("a", StringComparison.Ordinal) != -1)
            {
                show_history = true;
            }

            if (arg.IndexOf("l", StringComparison.Ordinal) != -1)
            {
                show_log = true;
            }

            if (arg.IndexOf("h", StringComparison.Ordinal) != -1)
            {
                show_histogram = true;
            }

            if (arg.IndexOf("k", StringComparison.Ordinal) != -1)
            {
                pre_kill = true;
            }

            if (arg.IndexOf("s", StringComparison.Ordinal) != -1)
            {
                post_kill = true;
            }
        }

        if (!usedefault)
        {
            string[] st = args[0].Split(new char[] { '_' });

            if (st.Length != 2)
            {
                printUsageString();

                return;
            }

            if (args.Length > 1)
            {
                string arg = args [1];

                if (arg.IndexOf("a", StringComparison.Ordinal) != -1)
                {
                    show_history = true;
                }

                if (arg.IndexOf("l", StringComparison.Ordinal) != -1)
                {
                    show_log = true;
                }

                if (arg.IndexOf("h", StringComparison.Ordinal) != -1)
                {
                    show_histogram = true;
                }

                if (arg.IndexOf("k", StringComparison.Ordinal) != -1)
                {
                    pre_kill = true;
                }

                if (arg.IndexOf("s", StringComparison.Ordinal) != -1)
                {
                    post_kill = true;
                }
            }

            adapter_name = st[0];
            port_name    = st[1];

            Debug.WriteLine("Adapter Name: " + adapter_name);
            Debug.WriteLine("Port Name: " + port_name);
        }

        if (access == null)
        {
            try
            {
                access = OneWireAccessProvider.getAdapter(adapter_name, port_name);
            }
            catch (Exception)
            {
                Debug.WriteLine("That is not a valid adapter/port combination.");

                System.Collections.IEnumerator en = OneWireAccessProvider.enumerateAllAdapters();

                while (en.MoveNext())
                {
                    DSPortAdapter temp = (DSPortAdapter)en.Current;

                    Debug.WriteLine("Adapter: " + temp.AdapterName);

                    System.Collections.IEnumerator f = temp.PortNames;

                    while (f.MoveNext())
                    {
                        Debug.WriteLine("   Port name : " + ((string)f.Current));
                    }
                }

                return;
            }
        }

        access.adapterDetected();
        access.targetFamily(0x21);
        access.beginExclusive(true);
        access.reset();
        access.setSearchAllDevices();

        bool next = access.findFirstDevice();

        if (!next)
        {
            Debug.WriteLine("Could not find any DS1921 Thermocrons!");

            return;
        }

        OneWireContainer21 owc = new OneWireContainer21();

        owc.setupContainer(access, access.AddressAsLong);

        //put the part into overdrive...make it sizzle!
        owc.setSpeed(DSPortAdapter.SPEED_OVERDRIVE, true);

        //let's gather our information here...
        stopWatch.Start();

        if (pre_kill)
        {
            try
            {
                owc.disableMission();
            }
            catch (Exception e)
            {
                Debug.WriteLine("Couldn't end mission before reading: " + e.ToString());
            }
        }

        bool mission_in_progress = owc.getFlag(OneWireContainer21.STATUS_REGISTER, OneWireContainer21.MISSION_IN_PROGRESS_FLAG);

        byte[] state;

        DateTime cal = new DateTime();

        // first, check to make sure that the thermochron isn't
        // sampling, or at least that a sample isn't about to occur.
        bool isSampling = false;

        do
        {
            state = owc.readDevice();

            cal = new DateTime(owc.getClock(state) * TimeSpan.TicksPerMillisecond);

            isSampling = mission_in_progress && (owc.getFlag(OneWireContainer21.STATUS_REGISTER, OneWireContainer21.SAMPLE_IN_PROGRESS_FLAG, state) || (cal.Second > 55));

            if (isSampling)
            {
                // wait for current sample to finish
                Thread.Sleep(1000);
            }
        } while (isSampling);

        int      mission_count = owc.getMissionSamplesCounter(state);
        int      device_count  = owc.getDeviceSamplesCounter(state);
        long     rtc           = owc.getClock(state);
        long     next_alarm    = owc.getClockAlarm(state);
        DateTime time_stamp    = owc.getMissionTimeStamp(state);
        int      sample_rate   = owc.getSampleRate(state);
        double   high_alarm    = owc.getTemperatureAlarm(TemperatureContainer_Fields.ALARM_HIGH, state);
        double   low_alarm     = owc.getTemperatureAlarm(TemperatureContainer_Fields.ALARM_LOW, state);

        int[]  histogram    = owc.TemperatureHistogram;
        byte[] log          = owc.getTemperatureLog(state);
        byte[] high_history = owc.getAlarmHistory(OneWireContainer21.TEMPERATURE_HIGH_ALARM);
        byte[] low_history  = owc.getAlarmHistory(OneWireContainer21.TEMPERATURE_LOW_ALARM);
        stopWatch.Stop();
        bool   clock_enabled = owc.isClockRunning(state);
        bool   alarm_enabled = owc.isClockAlarmEnabled(state);
        bool   clock_alarm   = owc.isClockAlarming(state);
        bool   rollover      = owc.getFlag(OneWireContainer21.CONTROL_REGISTER, OneWireContainer21.ROLLOVER_ENABLE_FLAG, state);
        double current_temp  = 0;
        string mission_in_progress_string;

        if (!mission_in_progress)
        {
            owc.doTemperatureConvert(state);

            current_temp = owc.getTemperature(state);
            mission_in_progress_string = "- NO MISSION IN PROGRESS AT THIS TIME";
        }
        else
        {
            mission_in_progress_string = "- MISSION IS CURRENTLY RUNNING";
        }

        //spew all this data

        Debug.WriteLine("Dallas Semiconductor DS1921 Thermocron Mission Summary Demo");
        Debug.WriteLine("-----------------------------------------------------------");
        Debug.WriteLine("- Device ID : " + owc.AddressAsString);
        Debug.WriteLine(mission_in_progress_string);

        if (!mission_in_progress)
        {
            Debug.WriteLine("- Current Temperature : " + current_temp);
        }
        else
        {
            Debug.WriteLine("- Cannot read current temperature with mission in progress");
        }

        Debug.WriteLine("-----------------------------------------------------------");
        Debug.WriteLine("- Number of mission samples: " + mission_count);
        Debug.WriteLine("- Total number of samples  : " + device_count);
        Debug.WriteLine("- Real Time Clock          : " + (clock_enabled ? "ENABLED" : "DISABLED"));
        Debug.WriteLine("- Real Time Clock Value    : " + (new DateTime(rtc * TimeSpan.TicksPerMillisecond)).ToString("r"));
        Debug.WriteLine("- Clock Alarm              : " + (alarm_enabled ? "ENABLED" : "DISABLED"));

        if (alarm_enabled)
        {
            Debug.WriteLine("- Clock Alarm Status       : " + (clock_alarm ? "ALARMING" : "NOT ALARMING"));
            Debug.WriteLine("- Next alarm occurs at     : " + (new DateTime(next_alarm * TimeSpan.TicksPerMillisecond)).ToString("r"));
        }

        Debug.WriteLine("- Last mission started     : " + time_stamp);
        Debug.WriteLine("- Sample rate              : Every " + sample_rate + " minutes");
        Debug.WriteLine("- High temperature alarm   : " + high_alarm);
        Debug.WriteLine("- Low temperature alarm    : " + low_alarm);
        Debug.WriteLine("- Rollover enabled         : " + (rollover ? "YES" : "NO"));
        Debug.WriteLine("- Time to read Thermocron  : " + (stopWatch.ElapsedMilliseconds) + " milliseconds");
        Debug.WriteLine("-----------------------------------------------------------");

        if (show_history)
        {
            int start_offset, violation_count;

            Debug.WriteLine("-");
            Debug.WriteLine("-                   ALARM HISTORY");

            if (low_history.Length == 0)
            {
                Debug.WriteLine("- No violations against the low temperature alarm.");
                Debug.WriteLine("-");
            }

            for (int i = 0; i < low_history.Length / 4; i++)
            {
                start_offset    = (low_history [i * 4] & 0x0ff) | ((low_history [i * 4 + 1] << 8) & 0x0ff00) | ((low_history [i * 4 + 2] << 16) & 0x0ff0000);
                violation_count = 0x0ff & low_history [i * 4 + 3];

                Debug.WriteLine("- Low alarm started at     : " + (start_offset * sample_rate));
                Debug.WriteLine("-                          : Lasted " + (violation_count * sample_rate) + " minutes");
            }

            if (high_history.Length == 0)
            {
                Debug.WriteLine("- No violations against the high temperature alarm.");
                Debug.WriteLine("-");
            }

            for (int i = 0; i < high_history.Length / 4; i++)
            {
                start_offset    = (high_history [i * 4] & 0x0ff) | ((high_history [i * 4 + 1] << 8) & 0x0ff00) | ((high_history [i * 4 + 2] << 16) & 0x0ff0000);
                violation_count = 0x0ff & high_history [i * 4 + 3];

                Debug.WriteLine("- High alarm started at    : " + (start_offset * sample_rate));
                Debug.WriteLine("-                          : Lasted " + (violation_count * sample_rate) + " minutes");
            }

            Debug.WriteLine("-----------------------------------------------------------");
        }

        if (show_log)
        {
            long time = (time_stamp.Ticks / TimeSpan.TicksPerMillisecond) + owc.getFirstLogOffset(state);

            Debug.WriteLine("-");
            Debug.WriteLine("-                   TEMPERATURE LOG");


            for (int i = 0; i < log.Length; i++)
            {
                DateTime gc = new DateTime(time * TimeSpan.TicksPerMillisecond);
                Debug.WriteLine("- Temperature recorded at  : " + gc.ToString("r"));
                Debug.WriteLine("-                     was  : " + owc.decodeTemperature(log [i]) + " C");

                time += sample_rate * 60 * 1000;
            }

            Debug.WriteLine("-----------------------------------------------------------");
        }

        if (show_histogram)
        {
            double resolution   = owc.TemperatureResolution;
            double histBinWidth = owc.HistogramBinWidth;
            double start        = owc.HistogramLowTemperature;

            Debug.WriteLine("-");
            Debug.WriteLine("-                   TEMPERATURE HISTOGRAM");

            for (int i = 0; i < histogram.Length; i++)
            {
                Debug.WriteLine("- Histogram entry          : " + histogram [i] + " at temperature " + start + " to " + (start + (histBinWidth - resolution)) + " C");

                start += histBinWidth;
            }
        }

        if (post_kill)
        {
            try
            {
                owc.disableMission();
            }
            catch (Exception e)
            {
                Debug.WriteLine("Couldn't end mission after reading: " + e.ToString());
            }
        }

        access.endExclusive();
        access.freePort();
        access = null;
        Debug.WriteLine("Finished.");
    }
Ejemplo n.º 16
0
    public static void Main0(string[] args)
    {
        //coprocessor
        long coprID   = 0;
        long lookupID = 0;
        bool next;

        // ------------------------------------------------------------
        // Check for valid path to sha.properties file on the cmd line.
        // ------------------------------------------------------------
        for (int i = 0; i < args.Length; i++)
        {
            string arg = args[i].ToUpper();
            if (arg.IndexOf("-P", StringComparison.Ordinal) == 0)
            {
                string sha_props_path;
                if (arg.Length == 2)
                {
                    sha_props_path = args[++i];
                }
                else
                {
                    sha_props_path = arg.Substring(2);
                }

                // attempt to open the sha.properties file
                sha_properties = new Properties();
                if (!sha_properties.loadLocalFile("sha.properties"))
                {
                    Debug.WriteLine("loading default sha.properties!");
                    Assembly asm = typeof(SHADebitDemo.MainPage).GetTypeInfo().Assembly;
                    sha_properties.loadResourceFile(asm, "SHADebitDemo.sha.properties");
                }
            }
            else
            {
                printUsageString();
                return;
            }
        }


        // ------------------------------------------------------------
        // Instantiate coprocessor containers
        // ------------------------------------------------------------
        SHAiButtonCopr     copr   = null;
        OneWireContainer18 copr18 = new OneWireContainer18();

        copr18.setSpeed(DSPortAdapter.SPEED_OVERDRIVE, false);
        copr18.SpeedCheck = false;

        // ------------------------------------------------------------
        // Setup the adapter for the coprocessor
        // ------------------------------------------------------------
        DSPortAdapter coprAdapter = null;
        string        coprAdapterName = null, coprPort = null;

        try
        {
            coprAdapterName = sha_properties.getProperty("copr.adapter");
            coprPort        = sha_properties.getProperty("copr.port");

            if (string.ReferenceEquals(coprPort, null) || string.ReferenceEquals(coprAdapterName, null))
            {
                coprAdapter = OneWireAccessProvider.DefaultAdapter;
            }
            else
            {
                coprAdapter = OneWireAccessProvider.getAdapter(coprAdapterName, coprPort);
            }

            IOHelper.writeLine("Coprocessor adapter loaded, adapter: " + coprAdapter.AdapterName + " port: " + coprAdapter.PortName);

            coprAdapter.adapterDetected();
            coprAdapter.targetFamily(0x18);
            coprAdapter.beginExclusive(true);
            coprAdapter.reset();
            coprAdapter.setSearchAllDevices();
            coprAdapter.reset();
            coprAdapter.putByte(0x3c);
            coprAdapter.Speed = DSPortAdapter.SPEED_OVERDRIVE;
        }
        catch (Exception e)
        {
            IOHelper.writeLine("Error initializing coprocessor adapter");
            Debug.WriteLine(e.ToString());
            Debug.Write(e.StackTrace);
            return;
        }

        // ------------------------------------------------------------
        // Find the coprocessor
        // ------------------------------------------------------------
        if (sha_properties.getPropertyBoolean("copr.simulated.isSimulated", false))
        {
            string coprVMfilename = sha_properties.getProperty("copr.simulated.filename");
            // ---------------------------------------------------------
            // Load emulated coprocessor
            // ---------------------------------------------------------
            try
            {
                copr = new SHAiButtonCoprVM(coprVMfilename);
            }
            catch (Exception e)
            {
                IOHelper.writeLine("Invalid Coprocessor Data File");
                Debug.WriteLine(e.ToString());
                Debug.Write(e.StackTrace);
                return;
            }
        }
        else
        {
            // ---------------------------------------------------------
            // Get the name of the coprocessor service file
            // ---------------------------------------------------------
            string filename = sha_properties.getProperty("copr.filename", "COPR.0");

            // ---------------------------------------------------------
            // Check for hardcoded coprocessor address
            // ---------------------------------------------------------
            byte[] coprAddress = sha_properties.getPropertyBytes("copr.address", null);
            lookupID = 0;
            if (coprAddress != null)
            {
                lookupID = Address.toLong(coprAddress);

                IOHelper.write("Looking for coprocessor: ");
                IOHelper.writeLineHex(lookupID);
            }

            // ---------------------------------------------------------
            // Find hardware coprocessor
            // ---------------------------------------------------------
            try
            {
                next = coprAdapter.findFirstDevice();
                while (copr == null && next)
                {
                    try
                    {
                        long tmpCoprID = coprAdapter.AddressAsLong;
                        if (coprAddress == null || tmpCoprID == lookupID)
                        {
                            IOHelper.write("Loading coprocessor file: " + filename + " from device: ");
                            IOHelper.writeLineHex(tmpCoprID);

                            copr18.setupContainer(coprAdapter, tmpCoprID);
                            copr = new SHAiButtonCopr(copr18, filename);

                            //save coprocessor ID
                            coprID = tmpCoprID;
                        }
                    }
                    catch (Exception e)
                    {
                        IOHelper.writeLine(e);
                    }

                    next = coprAdapter.findNextDevice();
                }
            }
            catch (Exception)
            {
                ;
            }
        }

        if (copr == null)
        {
            IOHelper.writeLine("No Coprocessor found!");
            return;
        }

        IOHelper.writeLine(copr);
        IOHelper.writeLine();


        // ------------------------------------------------------------
        // Create the SHADebit transaction types
        // ------------------------------------------------------------
        //stores DS1963S transaction type
        SHATransaction debit18 = null;

        string transType18 = sha_properties.getProperty("transaction.type", "signed");

        transType18 = transType18.ToLower();
        if (transType18.Equals("signed"))
        {
            debit18 = new SHADebit(copr, 10000, 50);
        }
        else
        {
            debit18 = new SHADebitUnsigned(copr, 10000, 50);
        }

        //stores DS1961S transaction type
        SHATransaction debit33 = null;

        string transType33 = sha_properties.getProperty("ds1961s.transaction.type", "unsigned");

        transType33 = transType33.ToLower();
        if (transType33.Equals(transType18))
        {
            debit33 = debit18;
        }
        else if (transType33.IndexOf("unsigned", StringComparison.Ordinal) >= 0)
        {
            //everything is seemless if you use the authentication secret
            //as the button's secret.
            debit33 = new SHADebitUnsigned(copr, 10000, 50);
        }
        else
        {
            //if the 1961S uses the authentication secret,
            //you'll need another button for generating the
            //write authorization MAC, but you can share the
            //1963S debit code for signed data.
            debit33 = new SHADebit(copr, 10000, 50);
        }

        //Transaction super class, swap variable
        SHATransaction trans = null;

        // ------------------------------------------------------------
        // Get the write-authorization coprocessor for ds1961S
        // ------------------------------------------------------------
        //first get the write authorization adapter
        DSPortAdapter authAdapter = null;
        string        authAdapterName = null, authPort = null;

        try
        {
            authAdapterName = sha_properties.getProperty("ds1961s.copr.adapter");
            authPort        = sha_properties.getProperty("ds1961s.copr.port");

            if (string.ReferenceEquals(authAdapterName, null) || string.ReferenceEquals(authAdapterName, null))
            {
                if (!string.ReferenceEquals(coprAdapterName, null) && !string.ReferenceEquals(coprPort, null))
                {
                    authAdapter = OneWireAccessProvider.DefaultAdapter;
                }
                else
                {
                    authAdapter = coprAdapter;
                }
            }
            else if (coprAdapterName.Equals(authAdapterName) && coprPort.Equals(authPort))
            {
                authAdapter = coprAdapter;
            }
            else
            {
                authAdapter = OneWireAccessProvider.getAdapter(authAdapterName, authPort);
            }

            IOHelper.writeLine("Write-Authorization adapter loaded, adapter: " + authAdapter.AdapterName + " port: " + authAdapter.PortName);

            byte[] families = new byte[] { 0x18 };

            authAdapter.adapterDetected();
            authAdapter.targetFamily(families);
            authAdapter.beginExclusive(false);
            authAdapter.reset();
            authAdapter.setSearchAllDevices();
            authAdapter.reset();
            authAdapter.putByte(0x3c);
            authAdapter.Speed = DSPortAdapter.SPEED_OVERDRIVE;
        }
        catch (Exception e)
        {
            IOHelper.writeLine("Error initializing write-authorization adapter.");
            Debug.WriteLine(e.ToString());
            Debug.Write(e.StackTrace);
            return;
        }

        //now find the coprocessor
        SHAiButtonCopr authCopr = null;

        // -----------------------------------------------------------
        // Check for hardcoded write-authorizaton coprocessor address
        // -----------------------------------------------------------
        byte[] authCoprAddress = sha_properties.getPropertyBytes("ds1961s.copr.address", null);
        lookupID = 0;
        if (authCoprAddress != null)
        {
            lookupID = Address.toLong(authCoprAddress);

            IOHelper.write("Looking for coprocessor: ");
            IOHelper.writeLineHex(lookupID);
        }
        if (lookupID == coprID)
        {
            //it's the same as the standard coprocessor.
            //valid only if we're not signing the data
            authCopr = copr;
        }
        else
        {
            // ---------------------------------------------------------
            // Find write-authorization coprocessor
            // ---------------------------------------------------------
            try
            {
                string             filename = sha_properties.getProperty("ds1961s.copr.filename", "COPR.1");
                OneWireContainer18 auth18   = new OneWireContainer18();
                auth18.setSpeed(DSPortAdapter.SPEED_OVERDRIVE, false);
                auth18.SpeedCheck = false;

                next = authAdapter.findFirstDevice();
                while (authCopr == null && next)
                {
                    try
                    {
                        long tmpAuthID = authAdapter.AddressAsLong;
                        if (authCoprAddress == null || tmpAuthID == lookupID)
                        {
                            IOHelper.write("Loading coprocessor file: " + filename + " from device: ");
                            IOHelper.writeLineHex(tmpAuthID);

                            auth18.setupContainer(authAdapter, tmpAuthID);
                            authCopr = new SHAiButtonCopr(auth18, filename);
                        }
                    }
                    catch (Exception e)
                    {
                        IOHelper.writeLine(e);
                    }

                    next = authAdapter.findNextDevice();
                }
            }
            catch (Exception e)
            {
                IOHelper.writeLine(e);
            }
            if (authCopr == null)
            {
                IOHelper.writeLine("no write-authorization coprocessor found");
                if (copr is SHAiButtonCoprVM)
                {
                    authCopr = copr;
                    IOHelper.writeLine("Re-using SHAiButtonCoprVM");
                }
            }
        }

        IOHelper.writeLine(authCopr);
        IOHelper.writeLine();

        // ------------------------------------------------------------
        // Create the User Buttons objects
        // ------------------------------------------------------------
        //holds DS1963S user buttons
        SHAiButtonUser18   user18 = new SHAiButtonUser18(copr);
        OneWireContainer18 owc18  = new OneWireContainer18();

        owc18.setSpeed(DSPortAdapter.SPEED_OVERDRIVE, false);
        owc18.SpeedCheck = false;

        //holds DS1961S user buttons
        SHAiButtonUser33   user33 = new SHAiButtonUser33(copr, authCopr);
        OneWireContainer33 owc33  = new OneWireContainer33();

        owc33.setSpeed(DSPortAdapter.SPEED_OVERDRIVE, false);
        //owc33.setSpeedCheck(false);

        //Holds generic user type, swap variable
        SHAiButtonUser user = null;

        // ------------------------------------------------------------
        // Get the adapter for the user
        // ------------------------------------------------------------
        DSPortAdapter adapter = null;
        string        userAdapterName = null, userPort = null;

        try
        {
            userAdapterName = sha_properties.getProperty("user.adapter");
            userPort        = sha_properties.getProperty("user.port");

            if (string.ReferenceEquals(userPort, null) || string.ReferenceEquals(userAdapterName, null))
            {
                if (!string.ReferenceEquals(coprAdapterName, null) && !string.ReferenceEquals(coprPort, null))
                {
                    if (!string.ReferenceEquals(authAdapterName, null) && !string.ReferenceEquals(authPort, null))
                    {
                        adapter = OneWireAccessProvider.DefaultAdapter;
                    }
                    else
                    {
                        adapter = authAdapter;
                    }
                }
                else
                {
                    adapter = coprAdapter;
                }
            }
            else if (userAdapterName.Equals(authAdapterName) && userPort.Equals(authPort))
            {
                adapter = authAdapter;
            }
            else if (userAdapterName.Equals(coprAdapterName) && userPort.Equals(coprPort))
            {
                adapter = coprAdapter;
            }
            else
            {
                adapter = OneWireAccessProvider.getAdapter(userAdapterName, userPort);
            }

            IOHelper.writeLine("User adapter loaded, adapter: " + adapter.AdapterName + " port: " + adapter.PortName);

            byte[] families = new byte[] { 0x18, 0x33 };
            families = sha_properties.getPropertyBytes("transaction.familyCodes", families);
            IOHelper.write("Supporting the following family codes: ");
            IOHelper.writeBytesHex(" ", families, 0, families.Length);

            adapter.adapterDetected();
            adapter.targetFamily(families);
            adapter.beginExclusive(true);
            adapter.reset();
            adapter.setSearchAllDevices();
            adapter.reset();
            adapter.putByte(0x3c);
            adapter.Speed = DSPortAdapter.SPEED_OVERDRIVE;
        }
        catch (Exception e)
        {
            IOHelper.writeLine("Error initializing user adapter.");
            Debug.WriteLine(e.ToString());
            Debug.Write(e.StackTrace);
            return;
        }

        //timing variables
        long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0;

        //address of current device
        byte[] address = new byte[8];

        //result of findNextDevice/findFirstDevice
        next = false;

        //holds list of known buttons
        long[] buttons = new long[16];
        //count of how many buttons are in buttons array
        int index = 0;

        //temporary id representing current button
        long tmpID = -1;

        //array of buttons looked at during this search
        long[] temp = new long[16];
        //count of how many buttons in temp array
        int cIndex = 0;

        //flag indiciating whether or not temp array represents
        //the complete list of buttons on the network.
        bool wholeList = false;

        Debug.WriteLine("");
        Debug.WriteLine("");
        Debug.WriteLine("**********************************************************");
        Debug.WriteLine("   Beginning The Main Application Loop (Search & Debit)");
        Debug.WriteLine("           Press Enter to Exit Application");
        Debug.WriteLine("**********************************************************");
        Debug.WriteLine("");

        //application infinite loop
        for (bool applicationFinished = false; !applicationFinished;)
        {
            try
            {
                if (coprAdapter != adapter)
                {
                    //in case coprocessor communication got hosed, make sure
                    //the coprocessor adapter is in overdrive
                    coprAdapter.Speed = DSPortAdapter.SPEED_REGULAR;
                    coprAdapter.reset();
                    coprAdapter.putByte(0x3c);        //overdrive skip rom
                    coprAdapter.Speed = DSPortAdapter.SPEED_OVERDRIVE;
                }
                if (authAdapter != coprAdapter && authAdapter != adapter)
                {
                    //in case coprocessor communication with the write-
                    //authorization coprocessor got hosed, make sure
                    //the coprocessor adapter is in overdrive
                    authAdapter.Speed = DSPortAdapter.SPEED_REGULAR;
                    authAdapter.reset();
                    authAdapter.putByte(0x3c);        //overdrive skip rom
                    authAdapter.Speed = DSPortAdapter.SPEED_OVERDRIVE;
                }
            }
            catch (Exception)
            {
                ;
            }

            // ---------------------------------------------------------
            // Search for new buttons
            // ---------------------------------------------------------
            bool buttonSearch = true;

            //Button search loop, waits forever until new button appears.
            while (buttonSearch && !applicationFinished)
            {
                wholeList = false;
                t0        = Stopwatch.GetTimestamp() * TimeSpan.TicksPerMillisecond;
                try
                {
                    //Go into overdrive
                    adapter.Speed = DSPortAdapter.SPEED_REGULAR;
                    adapter.reset();
                    adapter.putByte(0x3c);        //overdrive skip rom
                    adapter.Speed = DSPortAdapter.SPEED_OVERDRIVE;

                    // Begin search for new buttons
                    if (!next)
                    {
                        wholeList = true;
                        next      = adapter.findFirstDevice();
                    }

                    for (tmpID = -1, cIndex = 0; next && (tmpID == -1); next = adapter.findNextDevice())
                    {
                        tmpID = adapter.AddressAsLong;
                        if (tmpID != coprID)
                        {
                            temp[cIndex++] = tmpID;
                            for (int i = 0; i < index; i++)
                            {
                                if (buttons[i] == tmpID)
                                {                 //been here all along
                                    tmpID = -1;
                                    i     = index;
                                }
                            }

                            if (tmpID != -1)
                            {
                                //populate address array
                                adapter.getAddress(address);
                            }
                        }
                        else
                        {
                            tmpID = -1;
                        }
                    }

                    //if we found a new button
                    if (tmpID != -1)
                    {
                        //add it to the main list
                        buttons[index++] = tmpID;

                        //quite searching, we got one!
                        buttonSearch = false;
                    }
                    else if (wholeList)
                    {
                        //went through whole list with nothing new
                        //update the main list of buttons
                        buttons = temp;
                        index   = cIndex;

                        //if user presses the enter key, we'll quit and clean up nicely
//TODO				  applicationFinished = (System.in.available() > 0);
                    }
                }
                catch (Exception e)
                {
                    if (DEBUG)
                    {
                        IOHelper.writeLine("adapter hiccup while searching");
                        Debug.WriteLine(e.ToString());
                        Debug.Write(e.StackTrace);
                    }
                }
            }

            if (applicationFinished)
            {
                continue;
            }

            // ---------------------------------------------------------
            // Perform the transaction
            // ---------------------------------------------------------
            try
            {
                t1 = Stopwatch.GetTimestamp() * TimeSpan.TicksPerMillisecond;

                //de-ref the user
                user = null;

                //check for button family code
                if ((tmpID & 0x18) == (byte)0x18)
                {
                    //get transactions for ds1963s
                    trans = debit18;
                    owc18.setupContainer(adapter, address);
                    if (user18.setiButton18(owc18))
                    {
                        user = user18;
                    }
                }
                else if ((tmpID & 0x33) == (byte)0x33)
                {
                    //get transactions for 1961S
                    trans = debit33;
                    owc33.setupContainer(adapter, address);
                    if (user33.setiButton33(owc33))
                    {
                        user = user33;
                    }
                }

                if (user != null)
                {
                    Debug.WriteLine("");
                    Debug.WriteLine(user.ToString());
                    t2 = Stopwatch.GetTimestamp() * TimeSpan.TicksPerMillisecond;
                    if (trans.verifyUser(user))
                    {
                        t3 = Stopwatch.GetTimestamp() * TimeSpan.TicksPerMillisecond;
                        if (trans.verifyTransactionData(user))
                        {
                            t4 = Stopwatch.GetTimestamp() * TimeSpan.TicksPerMillisecond;
                            if (!trans.executeTransaction(user, true))
                            {
                                Debug.WriteLine("Execute Transaction Failed");
                            }
                            t5 = Stopwatch.GetTimestamp() * TimeSpan.TicksPerMillisecond;

                            Debug.WriteLine("  Debit Amount: $00.50");
                            Debug.Write("User's balance: $");
                            int balance = trans.getParameter(SHADebit.USER_BALANCE);
                            Debug.WriteLine(com.dalsemi.onewire.utils.Convert.ToString(balance / 100d, 2));
                        }
                        else
                        {
                            Debug.WriteLine("Verify Transaction Data Failed");
                        }
                    }
                    else
                    {
                        Debug.WriteLine("Verify User Authentication Failed");
                    }
                }
                else
                {
                    Debug.WriteLine("Not a SHA user of this service");
                }

                Debug.Write("Total time: ");
                Debug.WriteLine(t5 - t0);
                Debug.Write("Executing transaction took: ");
                Debug.WriteLine(t5 - t4);
                Debug.Write("Verifying data took: ");
                Debug.WriteLine(t4 - t3);
                Debug.Write("Verifying user took: ");
                Debug.WriteLine(t3 - t2);
                Debug.Write("Loading user data took: ");
                Debug.WriteLine(t2 - t1);
                Debug.Write("Finding user took: ");
                Debug.WriteLine(t1 - t0);

                //report all errors
                if (trans.LastError != 0)
                {
                    IOHelper.writeLine("Last Error Code: ");
                    IOHelper.writeLine(trans.LastError);
                    if (trans.LastError == SHATransaction.COPROCESSOR_FAILURE)
                    {
                        IOHelper.writeLine("COPR Error Code: ");
                        IOHelper.writeLine(copr.LastError);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Transaction failed!");
                Debug.WriteLine(e.ToString());
                Debug.Write(e.StackTrace);
            }
        }

        // --------------------------------------------------------------
        // Some Friendly Cleanup
        // --------------------------------------------------------------
        adapter.endExclusive();
        coprAdapter.endExclusive();
        authAdapter.endExclusive();
    }
Ejemplo n.º 17
0
    /// <summary>
    /// Method main
    ///
    /// </summary>
    /// <param name="args">
    /// </param>
    /// <exception cref="OneWireException"> </exception>
    /// <exception cref="OneWireIOException">
    ///  </exception>
    public static void Main1(string[] args)
    {
        byte[] sign_secret = null;
        byte[] auth_secret = null;

        // attempt to open the sha.properties file
        sha_properties = new Properties();
        if (!sha_properties.loadLocalFile("sha.properties"))
        {
            Debug.WriteLine("loading default sha.properties!");
            Assembly asm = typeof(SHADebitDemo.MainPage).GetTypeInfo().Assembly;
            sha_properties.loadResourceFile(asm, "SHADebitDemo.sha.properties");
        }

        // ------------------------------------------------------------
        // Instantiate coprocessor containers
        // ------------------------------------------------------------
        SHAiButtonCopr     copr   = null;
        OneWireContainer18 copr18 = new OneWireContainer18();

        //TODO copr18.setSpeed(DSPortAdapter.SPEED_OVERDRIVE, false);
        copr18.SpeedCheck = false;

        // ------------------------------------------------------------
        // Setup the adapter for the coprocessor
        // ------------------------------------------------------------
        DSPortAdapter coprAdapter = null;
        string        coprAdapterName = null, coprPort = null;

        try
        {
            coprAdapterName = sha_properties.getProperty("copr.adapter");
            coprPort        = sha_properties.getProperty("copr.port");

            if (string.ReferenceEquals(coprPort, null) || string.ReferenceEquals(coprAdapterName, null))
            {
                coprAdapter = OneWireAccessProvider.DefaultAdapter;
            }
            else
            {
                coprAdapter = OneWireAccessProvider.getAdapter(coprAdapterName, coprPort);
            }

            Debug.WriteLine("Coprocessor adapter loaded, adapter: " + coprAdapter.AdapterName + " port: " + coprAdapter.PortName);

            coprAdapter.adapterDetected();
            coprAdapter.targetFamily(0x18);
            coprAdapter.beginExclusive(true);
            coprAdapter.reset();
            coprAdapter.setSearchAllDevices();
            coprAdapter.reset();
            coprAdapter.putByte(0x3c);
            //TODO coprAdapter.Speed = DSPortAdapter.SPEED_OVERDRIVE;
        }
        catch (Exception e)
        {
            Debug.WriteLine("Error initializing coprocessor adapter");
            Debug.WriteLine(e.ToString());
            Debug.Write(e.StackTrace);
            return;
        }

        // ---------------------------------------------------------
        // Get the name of the coprocessor service file
        // ---------------------------------------------------------
        string filename = sha_properties.getProperty("copr.filename", "COPR.0");

        bool   next = false;
        bool   vmSaveSecrets  = true;
        string coprVMfilename = null;

        // ------------------------------------------------------------
        // Find the coprocessor
        // ------------------------------------------------------------
        if (sha_properties.getPropertyBoolean("copr.simulated.isSimulated", false))
        {
            coprVMfilename = sha_properties.getProperty("copr.simulated.filename");
            vmSaveSecrets  = sha_properties.getPropertyBoolean("copr.simulated.saveSecrets", true);

            // ---------------------------------------------------------
            // Load emulated coprocessor
            // ---------------------------------------------------------
            Debug.WriteLine("Setting up simulated Copressor.");
            Debug.WriteLine("Would you like to emulate another coprocessor? (y)");
            //if (IOHelper.readLine().ToUpper()[0] == 'Y')
            //{
            //    //    OneWireContainer18 ibc = new OneWireContainer18();
            //    ibc.SpeedCheck = false;
            //    try
            //    {
            //        next = coprAdapter.findFirstDevice();
            //        while (next && copr == null)
            //        {
            //            try
            //            {
            //                Debug.WriteLine(coprAdapter.AddressAsLong);
            //                ibc.setupContainer(coprAdapter, coprAdapter.AddressAsLong);
            //                copr = new SHAiButtonCopr(ibc, filename);
            //            }
            //            catch (Exception e)
            //            {
            //                Debug.WriteLine(e.ToString());
            //                Debug.Write(e.StackTrace);
            //            }
            //            next = coprAdapter.findNextDevice();
            //        }
            //    }
            //    catch (Exception)
            //    {
            //        ;
            //    }
            //    if (copr == null)
            //    {
            //        Debug.WriteLine("No coprocessor found to emulate");
            //        return;
            //    }

            //    Debug.WriteLine("");
            //    Debug.WriteLine("Emulating Coprocessor: " + ibc.AddressAsString);
            //    Debug.WriteLine("");

            //    //now that we got all that, we need a signing secret and an authentication secret
            //    Debug.WriteLine("How would you like to enter the signing secret (unlimited bytes)? ");
            //    sign_secret = new byte[] { 0, 0, 0, 0 }; //TODO
            //    IOHelper.writeBytes(sign_secret);

            //    Debug.WriteLine("");
            //    Debug.WriteLine("How would you like to enter the authentication secret (unlimited bytes)? ");
            //    auth_secret = new byte[] { 0, 0, 0, 0 }; //TODO
            //    IOHelper.writeBytes(auth_secret);

            //    Debug.WriteLine("");
            //    if (copr.DS1961Scompatible)
            //    {
            //        //reformat the auth_secret
            //        auth_secret = SHAiButtonCopr.reformatFor1961S(auth_secret);
            //        IOHelper.writeBytes(auth_secret);
            //    }
            //    Debug.WriteLine("");
            //    copr = new SHAiButtonCoprVM(ibc, filename, sign_secret, auth_secret);

            //    ((SHAiButtonCoprVM)copr).save(coprVMfilename, true);

            //    Debug.WriteLine(copr);
            //    return;
            //}
        }
        //else
        {
            // ---------------------------------------------------------
            // Check for hardcoded coprocessor address
            // ---------------------------------------------------------
            byte[] coprAddress = sha_properties.getPropertyBytes("copr.address", null);
            long   lookupID = 0, coprID = -1;
            if (coprAddress != null)
            {
                lookupID = com.dalsemi.onewire.utils.Address.toLong(coprAddress);

                Debug.Write("Looking for coprocessor: " + lookupID.ToString("x"));
            }

            // ---------------------------------------------------------
            // Find hardware coprocessor
            // ---------------------------------------------------------
            try
            {
                next = coprAdapter.findFirstDevice();
                while (copr == null && next)
                {
                    try
                    {
                        long tmpCoprID = coprAdapter.AddressAsLong;
                        if (coprAddress == null || tmpCoprID == lookupID)
                        {
                            Debug.WriteLine("Loading coprocessor file: " + filename + " from device: " + tmpCoprID.ToString("x"));

                            copr18.setupContainer(coprAdapter, tmpCoprID);

                            //save coprocessor ID
                            coprID = tmpCoprID;
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e);
                    }

                    next = coprAdapter.findNextDevice();
                }
            }
            catch (Exception)
            {
                ;
            }

            if (coprID == -1)
            {
                Debug.WriteLine("No Coprocessor found!");
                return;
            }

            Debug.WriteLine("Setting up DS1963S as Coprocessor: " + com.dalsemi.onewire.utils.Address.ToString(copr18.Address));
        }

        // Now that we've got a suitable button for creating a coprocessor,
        // let's ask the user for all the necessary paramters.

        Debug.Write("Enter the name of the coprocessor file (usually 'COPR') : ");
        byte[] coprname = { (byte)'C', (byte)'O', (byte)'P', (byte)'R' }; //com.dalsemi.onewire.utils.IOHelper.readBytesAsc(4, ' ');

        Debug.Write("Enter the file extension of the coprocessor file (0) : ");
        int coprext = 0; // com.dalsemi.onewire.utils.IOHelper.readInt(0);

        Debug.Write("Enter the name of the service file (4 characters) : ");
        byte[] name = { (byte)'S', (byte)'V', (byte)'C', (byte)'F' }; // com.dalsemi.onewire.utils.IOHelper.readBytesAsc(4, ' ');

        Debug.Write("Enter the file extension of the service file (102 for Money) : ");
        byte ext = 102; // (byte)com.dalsemi.onewire.utils.IOHelper.readInt(102);

        Debug.Write("Enter authentication page number (7) : ");
        int auth_page = 7; // com.dalsemi.onewire.utils.IOHelper.readInt(7);

        if (auth_page < 7)
        {
            Debug.WriteLine("Authentication page too low, default to 7");
            auth_page = 7;
        }
        if (auth_page == 8)
        {
            Debug.WriteLine("Page already taken, default to 7");
            auth_page = 7;
        }

        Debug.Write("Enter workspace page number (9) : ");
        int work_page = 9; //TODO com.dalsemi.onewire.utils.IOHelper.readInt(9);

        if (work_page < 7)
        {
            Debug.WriteLine("Workspace page too low, default to 9");
            work_page = 9;
        }
        if ((work_page == 8) || (work_page == auth_page))
        {
            Debug.WriteLine("Page already taken, default to 9");
            work_page = 9;
        }

        Debug.Write("Enter version number (1) : ");
        int version = 1; //TODO com.dalsemi.onewire.utils.IOHelper.readInt(1);

        Debug.WriteLine("How would you like to enter the binding data (32 bytes)? ");
        byte[] bind_data = getBytes(32);

        Debug.WriteLine("How would you like to enter the binding code (7 bytes)? ");
        byte[] bind_code = getBytes(7);

        // This could be done on the button
        //java.util.Random random = new java.util.Random();
        //random.nextBytes(chlg);
        //  Need to know what the challenge is so that I can reproduce it!
        byte[] chlg = new byte[] { 0x00, 0x00, 0x00 };

        Debug.WriteLine("Enter a human-readable provider name: ");
        string provider_name = com.dalsemi.onewire.utils.IOHelper.readLine();

        Debug.WriteLine("Enter an initial signature in HEX (all 0' default): ");
        byte[] sig_ini = com.dalsemi.onewire.utils.IOHelper.readBytesHex(20, 0);

        Debug.WriteLine("Enter any additional text you would like store on the coprocessor: ");
        string aux_data = com.dalsemi.onewire.utils.IOHelper.readLine();

        Debug.WriteLine("Enter an encryption code (0): ");
        int enc_code = com.dalsemi.onewire.utils.IOHelper.readInt(0);

        //now that we got all that, we need a signing secret and an authentication secret
        Debug.WriteLine("How would you like to enter the signing secret (unlimited bytes)? ");
        sign_secret = new byte[] { 0, 0, 0, 0 }; //TODO
        com.dalsemi.onewire.utils.IOHelper.writeBytes(sign_secret);

        Debug.WriteLine("");
        Debug.WriteLine("How would you like to enter the authentication secret (unlimited bytes)? ");
        auth_secret = new byte[] { 0, 0, 0, 0 }; //TODO
        com.dalsemi.onewire.utils.IOHelper.writeBytes(auth_secret);

        Debug.WriteLine("");
        Debug.WriteLine("Would you like to reformat the authentication secret for the 1961S? (y or n)");
        string s = com.dalsemi.onewire.utils.IOHelper.readLine();

        if (s.ToUpper()[0] == 'Y')
        {
            //reformat the auth_secret
            auth_secret = SHAiButtonCopr.reformatFor1961S(auth_secret);
            com.dalsemi.onewire.utils.IOHelper.writeLine("authentication secret");
            com.dalsemi.onewire.utils.IOHelper.writeBytes(auth_secret);
            com.dalsemi.onewire.utils.IOHelper.writeLine();
        }

        // signing page must be 8, using secret 0
        int sign_page = 8;

        if (!string.ReferenceEquals(coprVMfilename, null))
        {
            byte[] RomID = new byte[] { 0x18, 0x20, 0xAF, 0x02, 0x00, 0x00, 0x00, 0xE7 };
            RomID = sha_properties.getPropertyBytes("copr.simulated.address", RomID);

            copr = new SHAiButtonCoprVM(RomID, sign_page, auth_page, work_page, version, enc_code, ext, name, Encoding.UTF8.GetBytes(provider_name), bind_data, bind_code, Encoding.UTF8.GetBytes(aux_data), sig_ini, chlg, sign_secret, auth_secret);
            ((SHAiButtonCoprVM)copr).save(coprVMfilename, vmSaveSecrets);
        }
        else
        {
            string coprFilename = coprname.ToString() + "." + coprext;
            // initialize this OneWireContainer18 as a valid coprocessor
            copr = new SHAiButtonCopr(copr18, coprFilename, true, sign_page, auth_page, work_page, version, enc_code, ext, name, Encoding.UTF8.GetBytes(provider_name), bind_data, bind_code, Encoding.UTF8.GetBytes(aux_data), sig_ini, chlg, sign_secret, auth_secret);
        }
        Debug.WriteLine("Initialized Coprocessor");
        Debug.WriteLine(copr.ToString());

        Debug.WriteLine("done");
    }
Ejemplo n.º 18
0
    /// <summary>
    /// Method main
    ///
    /// </summary>
    /// <param name="args">
    /// </param>
    /// <exception cref="OneWireException"> </exception>
    /// <exception cref="OneWireIOException">
    ///  </exception>
    public static void Main3(string[] args)
    {
        //coprocessor
        long coprID = 0;

        // attempt to open the sha.properties file
        sha_properties = new Properties();
        if (!sha_properties.loadLocalFile("sha.properties"))
        {
            Debug.WriteLine("loading default sha.properties!");
            Assembly asm = typeof(SHADebitDemo.MainPage).GetTypeInfo().Assembly;
            sha_properties.loadResourceFile(asm, "SHADebitDemo.sha.properties");
        }

        // ------------------------------------------------------------
        // Instantiate coprocessor containers
        // ------------------------------------------------------------
        SHAiButtonCopr     copr   = null;
        OneWireContainer18 copr18 = new OneWireContainer18();

        copr18.setSpeed(DSPortAdapter.SPEED_REGULAR, false);
        copr18.SpeedCheck = false;

        // ------------------------------------------------------------
        // Setup the adapter for the coprocessor
        // ------------------------------------------------------------
        DSPortAdapter coprAdapter = null;
        string        coprAdapterName = null, coprPort = null;

        try
        {
            coprAdapterName = sha_properties.getProperty("copr.adapter", "{DS9097U}");
            coprPort        = sha_properties.getProperty("copr.port", "COM1");

            if (string.ReferenceEquals(coprPort, null) || string.ReferenceEquals(coprAdapterName, null))
            {
                coprAdapter = OneWireAccessProvider.DefaultAdapter;
            }
            else
            {
                coprAdapter = OneWireAccessProvider.getAdapter(coprAdapterName, coprPort);
            }

            IOHelper.writeLine("Coprocessor adapter loaded, adapter: " + coprAdapter.AdapterName + " port: " + coprAdapter.PortName);

            coprAdapter.adapterDetected();
            coprAdapter.targetFamily(0x18);
            coprAdapter.beginExclusive(true);
            coprAdapter.setSearchAllDevices();
            coprAdapter.reset();
        }
        catch (Exception e)
        {
            IOHelper.writeLine("Error initializing coprocessor adapter");
            Debug.WriteLine(e.ToString());
            Debug.Write(e.StackTrace);
            return;
        }

        // ------------------------------------------------------------
        // Find the coprocessor
        // ------------------------------------------------------------
        if (sha_properties.getPropertyBoolean("copr.simulated.isSimulated", false))
        {
            string coprVMfilename = sha_properties.getProperty("copr.simulated.filename");
            // ---------------------------------------------------------
            // Load emulated coprocessor
            // ---------------------------------------------------------
            try
            {
                copr = new SHAiButtonCoprVM(coprVMfilename);
            }
            catch (Exception e)
            {
                IOHelper.writeLine("Invalid Coprocessor Data File");
                Debug.WriteLine(e.ToString());
                Debug.Write(e.StackTrace);
                return;
            }
        }
        else
        {
            // ---------------------------------------------------------
            // Get the name of the coprocessor service file
            // ---------------------------------------------------------
            string filename = sha_properties.getProperty("copr.filename", "COPR.0");

            // ---------------------------------------------------------
            // Check for hardcoded coprocessor address
            // ---------------------------------------------------------
            byte[] coprAddress = sha_properties.getPropertyBytes("copr.address", null);
            long   lookupID    = 0;
            if (coprAddress != null)
            {
                lookupID = Address.toLong(coprAddress);

                IOHelper.write("Looking for coprocessor: ");
                IOHelper.writeLineHex(lookupID);
            }

            // ---------------------------------------------------------
            // Find hardware coprocessor
            // ---------------------------------------------------------
            try
            {
                bool next = coprAdapter.findFirstDevice();
                while (copr == null && next)
                {
                    try
                    {
                        long tmpCoprID = coprAdapter.AddressAsLong;
                        if (coprAddress == null || tmpCoprID == lookupID)
                        {
                            IOHelper.write("Loading coprocessor file: " + filename + " from device: ");
                            IOHelper.writeLineHex(tmpCoprID);

                            copr18.setupContainer(coprAdapter, tmpCoprID);
                            copr = new SHAiButtonCopr(copr18, filename);

                            //save coprocessor ID
                            coprID = tmpCoprID;
                        }
                    }
                    catch (Exception e)
                    {
                        IOHelper.writeLine(e);
                    }

                    next = coprAdapter.findNextDevice();
                }
            }
            catch (Exception)
            {
                ;
            }
        }

        if (copr == null)
        {
            IOHelper.writeLine("No Coprocessor found!");
            return;
        }

        IOHelper.writeLine(copr);
        IOHelper.writeLine();


        // ------------------------------------------------------------
        // Create the SHADebit transaction types
        // ------------------------------------------------------------
        //stores DS1963S transaction data
        SHATransaction trans     = null;
        string         transType = sha_properties.getProperty("ds1961s.transaction.type", "Signed");

        if (transType.ToLower().IndexOf("unsigned", StringComparison.Ordinal) >= 0)
        {
            trans = new SHADebitUnsigned(copr, 10000, 50);
        }
        else
        {
            trans = new SHADebit(copr, 10000, 50);
        }

        // ------------------------------------------------------------
        // Create the User Buttons objects
        // ------------------------------------------------------------
        //holds DS1963S user buttons
        OneWireContainer33 owc33 = new OneWireContainer33();

        owc33.setSpeed(DSPortAdapter.SPEED_REGULAR, false);
        //owc33.setSpeedCheck(false);

        // ------------------------------------------------------------
        // Get the adapter for the user
        // ------------------------------------------------------------
        DSPortAdapter adapter = null;
        string        userAdapterName = null, userPort = null;

        try
        {
            userAdapterName = sha_properties.getProperty("user.adapter", "{DS9097U}");
            userPort        = sha_properties.getProperty("user.port", "COM9");

            if (string.ReferenceEquals(userPort, null) || string.ReferenceEquals(userAdapterName, null))
            {
                if (!string.ReferenceEquals(coprAdapterName, null) && !string.ReferenceEquals(coprPort, null))
                {
                    adapter = OneWireAccessProvider.DefaultAdapter;
                }
                else
                {
                    adapter = coprAdapter;
                }
            }
            else if (userAdapterName.Equals(coprAdapterName) && userPort.Equals(coprPort))
            {
                adapter = coprAdapter;
            }
            else
            {
                adapter = OneWireAccessProvider.getAdapter(userAdapterName, userPort);
            }

            IOHelper.writeLine("User adapter loaded, adapter: " + adapter.AdapterName + " port: " + adapter.PortName);

            byte[] families = new byte[] { 0x33, unchecked ((byte)0xB3) };

            adapter.adapterDetected();
            adapter.targetFamily(families);
            adapter.beginExclusive(false);
            adapter.setSearchAllDevices();
            adapter.reset();
        }
        catch (Exception e)
        {
            IOHelper.writeLine("Error initializing user adapter.");
            Debug.WriteLine(e.ToString());
            Debug.Write(e.StackTrace);
            return;
        }

        // ---------------------------------------------------------------
        // Search for the button
        // ---------------------------------------------------------------
        try
        {
            long tmpID = -1;
            bool next  = adapter.findFirstDevice();
            for (; tmpID == -1 && next; next = adapter.findNextDevice())
            {
                tmpID = adapter.AddressAsLong;
                if (tmpID == coprID)
                {
                    tmpID = -1;
                }
                else
                {
                    owc33.setupContainer(adapter, tmpID);
                }
            }

            if (tmpID == -1)
            {
                IOHelper.writeLine("No buttons found!");
                return;
            }
        }
        catch (Exception)
        {
            IOHelper.writeLine("Adapter error while searching.");
            return;
        }

        IOHelper.write("Setting up user button: ");
        IOHelper.writeBytesHex(owc33.Address);
        IOHelper.writeLine();

        IOHelper.writeLine("How would you like to enter the authentication secret (unlimited bytes)? ");
        byte[] auth_secret = getBytes(0);
        IOHelper.writeBytes(auth_secret);
        IOHelper.writeLine();

        auth_secret = SHAiButtonCopr.reformatFor1961S(auth_secret);
        IOHelper.writeLine("Reformatted for compatibility with 1961S buttons");
        IOHelper.writeBytes(auth_secret);
        IOHelper.writeLine("");

        IOHelper.writeLine("Initial Balance in Cents? ");
        int initialBalance = IOHelper.readInt(100);

        trans.setParameter(SHADebit.INITIAL_AMOUNT, initialBalance);

        SHAiButtonUser user = new SHAiButtonUser33(copr, owc33, true, auth_secret);

        if (trans.setupTransactionData(user))
        {
            IOHelper.writeLine("Transaction data installation succeeded");
        }
        else
        {
            IOHelper.writeLine("Failed to initialize transaction data");
        }

        IOHelper.writeLine(user);
    }
Ejemplo n.º 19
0
        /// <summary>
        /// Method main
        ///
        /// </summary>
        /// <param name="args">
        /// </param>
        /// <exception cref="OneWireException"> </exception>
        /// <exception cref="OneWireIOException">
        ///  </exception>

        public void Main([ReadOnlyArray()] string[] args)
        {
            bool          usedefault   = false;
            DSPortAdapter access       = null;
            string        adapter_name = null;
            string        port_name    = null;

            if ((args == null) || (args.Length < 1))
            {
                try
                {
                    access = OneWireAccessProvider.DefaultAdapter;

                    if (access == null)
                    {
                        throw new Exception();
                    }
                }
                catch (Exception)
                {
                    Debug.WriteLine("Couldn't get default adapter!");
                    printUsageString();

                    return;
                }

                usedefault = true;
            }

            if (!usedefault)
            {
                //parse device instance

                //string[] st = args[0].Split(new char[] { '_' });

                if (args.Length != 2)
                {
                    printUsageString();

                    return;
                }

                adapter_name = args[0];
                port_name    = args[1];

                Debug.WriteLine("Adapter Name: " + adapter_name);
                Debug.WriteLine("Port Name: " + port_name);
            }

            if (access == null)
            {
                try
                {
                    access = OneWireAccessProvider.getAdapter(adapter_name, port_name);
                }
                catch (Exception)
                {
                    Debug.WriteLine("That is not a valid adapter/port combination.");

                    System.Collections.IEnumerator en = OneWireAccessProvider.enumerateAllAdapters();

                    while (en.MoveNext())
                    {
                        DSPortAdapter temp = (DSPortAdapter)en.Current;

                        Debug.WriteLine("Adapter: " + temp.AdapterName);

                        System.Collections.IEnumerator f = temp.PortNames;

                        while (f.MoveNext())
                        {
                            Debug.WriteLine("   Port name : " + ((DeviceInformation)f.Current).Id);
                        }
                    }

                    return;
                }
            }

            access.adapterDetected();
            access.targetAllFamilies();
            access.beginExclusive(true);
            access.reset();
            access.setSearchAllDevices();

            bool next = access.findFirstDevice();

            if (!next)
            {
                Debug.WriteLine("Could not find any iButtons!");

                return;
            }

            while (next)
            {
                OneWireContainer owc = access.DeviceContainer;

                Debug.WriteLine("====================================================");
                Debug.WriteLine("= Found One Wire Device: " + owc.AddressAsString + "          =");
                Debug.WriteLine("====================================================");
                Debug.WriteLine("=");

                bool isShaContainer   = false;
                OneWireContainer33 sc = null;

                try
                {
                    sc             = (OneWireContainer33)owc;
                    isShaContainer = true;
                }
                catch (System.InvalidCastException)
                {
                    sc             = null;
                    isShaContainer = false; //just to reiterate
                }

                if (isShaContainer)
                {
                    Debug.WriteLine("= This device is a " + owc.Name);
                    Debug.WriteLine("= Also known as a " + owc.AlternateNames);
                    Debug.WriteLine("=");
                    Debug.WriteLine("= It is a 1K-Bit protected 1-Wire EEPROM with SHA-1 Engine device.");

                    byte[] statusPage = null;
                    ReadMemoryBank(sc.StatusPageMemoryBank, out statusPage);

                    Debug.WriteLine("Status Page");
                    for (var i = 0; i < statusPage.Length; i++)
                    {
                        Debug.Write(statusPage[i].ToString("X") + " ");
                    }
                    Debug.WriteLine("");

                    byte[] mem = new byte[8];
                    Array.Copy(statusPage, 8, mem, 0, 8);

                    if ((mem[0] == 0xAA) || (mem[0] == 0x55))
                    {
                        Debug.WriteLine("SECRET IS WRITE PROTECTED - CANNOT LOAD FIRST SECRET");
                    }
                    else
                    {
                        Debug.WriteLine("SECRET IS NOT WRITE PROTECTED!");
                    }

                    if ((mem[1] == 0xAA) || (mem[1] == 0x55))
                    {
                        Debug.WriteLine("memoryPages[0].readOnly = true");
                        Debug.WriteLine("memoryPages[1].readOnly = true");
                        Debug.WriteLine("memoryPages[2].readOnly = true");
                    }
                    else
                    {
                        Debug.WriteLine("memoryPages[0].readWrite = true");
                        Debug.WriteLine("memoryPages[1].readWrite = true");
                        Debug.WriteLine("memoryPages[2].readWrite = true");
                    }

                    if ((mem[4] == 0xAA) || (mem[4] == 0x55))
                    {
                        Debug.WriteLine("memoryPages[1].writeOnce = true");
                    }
                    else
                    {
                        Debug.WriteLine("memoryPages[1].writeOnce = false");
                    }

                    if ((mem[5] == 0xAA) || (mem[5] == 0x55))
                    {
                        Debug.WriteLine("memoryPages[0].readOnly = true");
                    }
                    else
                    {
                        Debug.WriteLine("memoryPages[0].readWrite = true");
                    }

                    Debug.WriteLine("mem[0] " + mem[0].ToString("X"));
                    Debug.WriteLine("mem[1] " + mem[1].ToString("X"));
                    Debug.WriteLine("mem[3] " + mem[3].ToString("X"));

                    if (((mem[0] != 0xAA) && (mem[0] != 0x55)) &&
                        ((mem[3] != 0xAA) && (mem[3] != 0x55)))
                    {
                        Debug.WriteLine("Case 1");

                        //// Clear all memory to 0xFFh
                        //for (i = 0; i < 16; i++)
                        //{
                        //    if (!LoadFirSecret(portnum, (ushort)(i * 8), data, 8))
                        //        printf("MEMORY ADDRESS %d DIDN'T WRITE\n", i * 8);
                        //}

                        //printf("Current Bus Master Secret Is:\n");
                        //for (i = 0; i < 8; i++)
                        //    printf("%02X ", secret[i]);
                        //printf("\n");
                    }
                    else if ((mem[1] != 0xAA) || (mem[1] != 0x55))
                    {
                        Debug.WriteLine("Case 2");

                        //printf("Please Enter the Current Secret\n");
                        //printf("AA AA AA AA AA AA AA AA  <- Example\n");
                        //scanf("%s %s %s %s %s %s %s %s", &hexstr[0], &hexstr[2], &hexstr[4],
                        //       &hexstr[6], &hexstr[8], &hexstr[10], &hexstr[12], &hexstr[14]);

                        //if (!ParseData(hexstr, strlen(hexstr), data, 16))
                        //    printf("DIDN'T PARSE\n");
                        //else
                        //{
                        //    printf("The secret read was:\n");
                        //    for (i = 0; i < 8; i++)
                        //    {
                        //        secret[i] = data[i];
                        //        printf("%02X ", secret[i]);
                        //        data[i] = 0xFF;
                        //    }
                        //    printf("\n");
                        //}

                        //printf("\n");

                        //if ((indata[13] == 0xAA) || (indata[13] == 0x55))
                        //    skip = 4;
                        //else
                        //    skip = 0;

                        //for (i = (ushort)skip; i < 16; i++)
                        //{
                        //    ReadMem(portnum, (ushort)(((i * 8) / ((ushort)32)) * 32), memory);

                        //    if (WriteScratchSHAEE(portnum, (ushort)(i * 8), &data[0], 8))
                        //        CopyScratchSHAEE(portnum, (ushort)(i * 8), secret, sn, memory);
                        //}
                    }
                    else
                    {
                        Debug.WriteLine("Case 3");

                        //printf("Please Enter the Current Secret\n");
                        //printf("AA AA AA AA AA AA AA AA  <- Example\n");
                        //scanf("%s %s %s %s %s %s %s %s", &hexstr[0], &hexstr[2], &hexstr[4],
                        //       &hexstr[6], &hexstr[8], &hexstr[10], &hexstr[12], &hexstr[14]);
                        //if (!ParseData(hexstr, strlen(hexstr), secret, 16))
                        //    printf("DIDN'T PARSE\n");
                        //else
                        //{
                        //    printf("The secret that was read:\n");
                        //    for (i = 0; i < 8; i++)
                        //    {
                        //        printf("%02X ", secret[i]);
                        //    }
                        //    printf("\n");
                        //}
                    }
                }
                else
                {
                    Debug.WriteLine("= Not a SHA-1 Engine device.");
                    Debug.WriteLine("=");
                    Debug.WriteLine("=");
                }

                next = access.findNextDevice();
            }
        }