Exemplo n.º 1
0
        /// <summary>
        /// 建構式
        /// </summary>
        public MainPage()
        {
            this.InitializeComponent();
            tempData         = new TemperatureModel();
            deviceId         = string.Empty;
            this.DataContext = tempData;
            timer            = new DispatcherTimer();


            //*******************************WorkShop-1***********************************//

            //timer.Interval = TimeSpan.FromMilliseconds(1200);           // 取溫度資料的時間間隔

            //*******************************************************************************//



            //*********************************WorkShop-2***********************************//

            //temperatureThreshold = 25.0;    // 溫度門檻值
            //ledPin = 26;              // 輸出之GPIO腳位

            //********************************************************************************//


            timer.Tick += Timer_Tick;
            onewire     = new OneWire();
        }
Exemplo n.º 2
0
        // ReSharper restore InconsistentNaming

        public static DS18X20[] FindAll(OneWire bus)
        {
            if (bus == null)
            {
                throw new ArgumentNullException("bus");
            }

            var       devices        = new ArrayList();
            ArrayList presensePulses = bus.FindAllDevices();

            foreach (byte[] presensePulse in presensePulses)
            {
                if (presensePulse[0] != DS18S20FamilyCode &&
                    presensePulse[0] != DS18B20FamilyCode)
                {
                    continue;
                }

                var device = new DS18X20(presensePulse, bus);
                devices.Add(device);
            }

            var result = (DS18X20[])devices.ToArray(typeof(DS18X20));

            return(result);
        }
Exemplo n.º 3
0
        public static Device[] Scan(OneWire ow, params Family[] includeFamilies)
        {
            var list = new ArrayList();
            var all  = false;
            var devs = ow.FindAllDevices();

            if (includeFamilies != null)
            {
                foreach (var f in includeFamilies)
                {
                    if (f == Family.Unknown)
                    {
                        all = true;
                    }
                }
            }
            foreach (byte[] da in devs)
            {
                if (includeFamilies == null || includeFamilies.Length == 0 || all)
                {
                    list.Add(new Device(da));
                }
                else
                {
                    foreach (var f in includeFamilies)
                    {
                        if (da[0] == (byte)f)
                        {
                            list.Add(new Device(da));
                        }
                    }
                }
            }
            return((Device[])list.ToArray(typeof(Device)));
        }
Exemplo n.º 4
0
        void Setup()
        {
            OneWire ow = new OneWire(myPin);
            ushort  temperature;

            // read every second
            while (true)
            {
                if (ow.TouchReset() > 0)
                {
                    ow.WriteByte(0xCC);     // Skip ROM, we only have one device
                    ow.WriteByte(0x44);     // Start temperature conversion

                    while (ow.ReadByte() == 0)
                    {
                        ;                          // wait while busy
                    }
                    ow.TouchReset();
                    ow.WriteByte(0xCC);                          // skip ROM
                    ow.WriteByte(0xBE);                          // Read Scratchpad

                    temperature  = (byte)ow.ReadByte();          // LSB
                    temperature |= (ushort)(ow.ReadByte() << 8); // MSB
                    TempValue    = temperature / 16;
                    Debug.Print("Temperature: " + TempValue);
                    Thread.Sleep(1000);
                }
                else
                {
                    Debug.Print("Device is not detected.");
                }

                Thread.Sleep(1000);
            }
        }
Exemplo n.º 5
0
        protected override async Task RunContinuouslyAsync(IMqttClient client, TimeSpan delay, CancellationToken stoppingToken)
        {
            var names = await LoadSensorNames(stoppingToken);

            var stateMap = new Dictionary <string, SensorState>();

            var oneWire = new OneWire();

            while (!stoppingToken.IsCancellationRequested)
            {
                var readings = await oneWire.Read(stoppingToken);

                foreach (var reading in readings)
                {
                    if (!stateMap.TryGetValue(reading.Device, out var state))
                    {
                        if (!names.TryGetValue(reading.Device, out var name))
                        {
                            Logger.LogWarning("Failed to find name for {Device}", reading.Device);
                            name = reading.Device;
                        }

                        state = new SensorState(reading.Device, name);
                        stateMap.Add(reading.Device, state);
                    }
                    if (state.Update(reading.DegreesCentigrade, reading.Timestamp))
                    {
                        await SendReading(client, state, stoppingToken);
                    }
                }
            }
        }
Exemplo n.º 6
0
        public M8_TempMgr(Cpu.Pin owPin)
        {
            this._owPin = owPin;
            this._owBus = new OneWire(this._owPin);

            this._thermometers = new ArrayList();
            this._getThermometers();
        }
Exemplo n.º 7
0
 /// <summary>
 ///     Create a new instance of a OneWire Device object.
 /// </summary>
 /// <param name="pin">Pin connected to the OneWire devices.</param>
 public Devices(Cpu.Pin pin)
 {
     Pin       = pin;
     Port      = new OutputPort(pin, false);
     DeviceBus = new OneWire(Port);
     DeviceIDs = new ArrayList();
     ScanForDevices();
 }
Exemplo n.º 8
0
 // Set device
 public static byte[] SetDevice(OneWire oneWire, object device)
 {
     byte[] b = (byte[])device;
     foreach (var bTmp in b)
     {
         oneWire.TouchByte(bTmp);
     }
     return(b);
 }
Exemplo n.º 9
0
 /// <summary>
 /// Constructs DS-18B20 object for a given 1-wire bus and a device address
 /// </summary>
 /// <param name="bus">1-wire bus to whish the sensor is attached</param>
 /// <param name="address">device address</param>
 public Ds18b20(OneWire bus, byte [] address)
 {
     OneWireBus = bus;
     Address = (byte[]) address.Clone();
     if (!bus.Search_IsDevicePresent(Address))
     {
         throw new InvalidOperationException("Device with the specified address is not present in the bus.");
     }
 }
Exemplo n.º 10
0
        /// <summary>Constructs a new OneWireX1 module.</summary>
        /// <param name="socketNumber">The socket that this module is plugged in to.</param>
        public OneWireX1(int socketNumber)
        {
            Socket socket = Socket.GetSocket(socketNumber, true, this, null);

            socket.EnsureTypeIsSupported(new char[] { 'X', 'Y' }, this);
            socket.ReservePin(Socket.Pin.Three, this);

            this.port    = new OutputPort(socket.CpuPins[(int)Socket.Pin.Three], false);
            this.oneWire = new Microsoft.SPOT.Hardware.OneWire(this.port);
        }
Exemplo n.º 11
0
            public void ShouldNotReturnNull()
            {
                var serialDeviceFactory = Mock.Create <ISerialDeviceFactory>();
                var writer = Mock.Create <IDataWriter>();
                var reader = Mock.Create <IDataReader>();

                var oneWire = new OneWire(serialDeviceFactory, _ => writer, _ => reader);
                var result  = oneWire.GetNewSerialPortAsync("foo", BaudRate.High);

                result.Should().NotBeNull();
            }
Exemplo n.º 12
0
 public MainPage()
 {
     this.InitializeComponent();
     tempData         = new TemperatureModel();
     deviceId         = string.Empty;
     this.DataContext = tempData;
     timer            = new DispatcherTimer();
     timer.Interval   = TimeSpan.FromMilliseconds(1200);
     timer.Tick      += Timer_Tick;
     onewire          = new OneWire();
 }
Exemplo n.º 13
0
        public DS18B20_Temperature(Cpu.Pin pin)
        {
            DataPin = new OneWire(pin);

            DataPin.Search_Restart();
            int i = 0;

            while (DataPin.Search_GetNextDevice(IDs[i++]))
            {
                Debug.Print("Found thermometer" + i);
            }
        }
Exemplo n.º 14
0
        public void ShouldReturnNoDeviceWhenNogthingIsCOnnected()
        {
            var mock = new Mock <IFileWrapper>();

            mock.Setup(fileWrapper => fileWrapper.ListDirectories("./sys/bus/w1/devices")).Returns(new List <string> {
            });
            var bus     = new OneWire(mock.Object);
            var devices = bus.getDevices();

            Assert.AreEqual(0, devices.Count);
            mock.Verify(fileWrapper => fileWrapper.ListDirectories("./sys/bus/w1/devices"), Times.Once());
        }
Exemplo n.º 15
0
 /// <summary>
 /// Constructs DS-18B20 object for a given 1-wire bus and a device sequence number. 
 /// </summary>
 /// <param name="bus">1-wire bus to whish the sensor is attached</param>
 /// <param name="number">sequence number of a bus element</param>
 public Ds18b20(OneWire bus, int number)
 {
     OneWireBus = bus;
     Address = new byte[8];
     int n = 0;
     bus.Search_Restart();
     while (bus.Search_GetNextDevice(Address) && n <= number)
     {
         n++;
     }
     if (n != number + 1) throw new IndexOutOfRangeException("Invalid device number.");
 }
Exemplo n.º 16
0
        public void ShouldReturnDeviceWhenBusAndDeviceConnected()
        {
            var mock = new Mock <IFileWrapper>();

            mock.Setup(fileWrapper => fileWrapper.ListDirectories("./sys/bus/w1/devices"))
            .Returns(new List <string> {
                "w1_bus_master1", "28-000006cc02c9"
            });
            var bus     = new OneWire(mock.Object);
            var devices = bus.getDevices();

            Assert.AreEqual(1, devices.Count);
            mock.Verify(fileWrapper => fileWrapper.ListDirectories("./sys/bus/w1/devices"), Times.Once());
        }
Exemplo n.º 17
0
 public Ds18B20(OneWire ow, OneWireBus.Device dev)
 {
     m_ow = ow;
     if (dev == null)
     {
         var devs = OneWireBus.Scan(ow, OneWireBus.Family.DS18B20);
         if (devs == null || devs.Length < 1)
         {
             throw new InvalidOperationException("No DS18B20 devices found on OneWire bus");
         }
         dev = devs[0];
     }
     m_dev = dev;
 }
Exemplo n.º 18
0
        public void ShouldNotReturnDeviceWithIncorrectName()
        {
            var mock = new Mock <IFileWrapper>();

            mock.Setup(fileWrapper => fileWrapper.ListDirectories("./sys/bus/w1/devices"))
            .Returns(new List <string> {
                "w28-000006cc03c9", "e28-000006cc02c9"
            });
            var bus = new OneWire(mock.Object);

            var devices = bus.getDevices();

            Assert.AreEqual(0, devices.Count);
            mock.Verify(fileWrapper => fileWrapper.ListDirectories("./sys/bus/w1/devices"), Times.Once());
        }
Exemplo n.º 19
0
        public void ShouldGetDeviceWhenNoBusAndTwoDeviceConnected()
        {
            var mock = new Mock <IFileWrapper>();

            mock.Setup(fileWrapper => fileWrapper.ListDirectories("./sys/bus/w1/devices"))
            .Returns(new List <string> {
                "28-000006cc03c9", "28-000006cc02c9"
            });
            var bus = new OneWire(mock.Object);

            var device = bus.getDevice("28-000006cc03c9");

            Assert.IsInstanceOf <DS18B20>(device);
            mock.Verify(fileWrapper => fileWrapper.ListDirectories("./sys/bus/w1/devices"), Times.Once());
        }
Exemplo n.º 20
0
 public Ds18B20(Cpu.Pin pin, OneWireBus.Device dev)
 {
     m_op = new OutputPort(pin, false);
     m_ow = new OneWire(m_op);
     if (dev == null)
     {
         var devs = OneWireBus.Scan(m_ow, OneWireBus.Family.DS18B20);
         if (devs == null || devs.Length < 1)
         {
             throw new InvalidOperationException("No DS18B20 devices found on OneWire bus");
         }
         dev = devs[0];
     }
     m_dev = dev;
 }
Exemplo n.º 21
0
        /// <summary>
        ///     Default Costructor.
        /// </summary>
        /// <param name="socket"></param>
        public Ds18B20(Hardware.Socket socket)
        {
            try
            {
                Hardware.CheckPins(socket, socket.An);

                using (var outPort = new OutputPort(socket.An, false))
                {
                    _ow = new OneWire(outPort);
                }
                ReadTemperature();
            }
            // Catch only the PinInUse exception, so that program will halt on other exceptions
            // Send it directly to caller
            catch (PinInUseException ex)
            {
                throw new PinInUseException("The An Pin is alreasy in use on " + socket.Name + " , try moving Click Board to another available socket.", ex);
            }
        }
Exemplo n.º 22
0
        public static string OneWire_Temperaturea()
        {
            // Change this your correct pin!
            Cpu.Pin myPin = (Cpu.Pin)FEZ_Pin.Digital.Di4;

            OneWire ow = new OneWire(myPin);
            ushort  temperature;

            {
                BMP085 pressureSensor = new BMP085(0x77, BMP085.DeviceMode.UltraLowPower);

                string temperature_Pressure;
                if (ow.Reset())
                {
                    ow.WriteByte(0xCC);     // Skip ROM, we only have one device
                    ow.WriteByte(0x44);     // Start temperature conversion

                    while (ow.ReadByte() == 0)
                    {
                        ;                          // wait while busy
                    }
                    ow.Reset();
                    ow.WriteByte(0xCC);                          // skip ROM
                    ow.WriteByte(0xBE);                          // Read Scratchpad

                    temperature  = ow.ReadByte();                // LSB
                    temperature |= (ushort)(ow.ReadByte() << 8); // MSB

                    temperature_Pressure = "Temperature: " + temperature / 16 + "\n" + "BMP085 Pascal: " + pressureSensor.Pascal +
                                           "   BMP085 InchesMercury: " + pressureSensor.InchesMercury.ToString("F2") + "   BMP085 Temp*C: " + pressureSensor.Celsius.ToString("F2");
                }
                else
                {
                    temperature_Pressure = "Temperature Device is not Detected";
                }

                ow.Dispose();
                Thread.Sleep(1000);
                return(temperature_Pressure);
            }
        }
Exemplo n.º 23
0
        public static void Main()
        {
            var op = new OutputPort(Stm32F4Discovery.FreePins.PA15, false);
            var ow = new OneWire(op);

            IDisplay display = new Display();

            DS18X20[] devices = DS18X20.FindAll(ow);
            if (devices.Length == 0)
            {
                display.ShowError("Brak DS18B20");
                return;
            }

            DS18X20 tempDev = devices[0];

            for (;;)
            {
                float  currentTemp  = 0;
                string exceptionMsg = String.Empty;
                try
                {
                    currentTemp = tempDev.GetTemperature();
                }
                catch (IOException ex)
                {
                    exceptionMsg = ex.Message;
                }

                if (exceptionMsg.Length == 0)
                {
                    display.ShowTemperature(currentTemp);
                }
                else
                {
                    display.ShowError(exceptionMsg);
                }

                Thread.Sleep(1000);
            }
        }
Exemplo n.º 24
0
        private DS18X20(byte[] presensePulse, OneWire bus)
        {
            if (presensePulse == null)
            {
                throw new ArgumentNullException("presensePulse");
            }

            if (bus == null)
            {
                throw new ArgumentNullException("bus");
            }

            if (presensePulse[0] != DS18S20FamilyCode &&
                presensePulse[0] != DS18B20FamilyCode)
            {
                throw new ArgumentException("Wrong pulses", "presensePulse");
            }

            _presensePulse = presensePulse;
            _bus           = bus;

            _sSeries = _presensePulse[0] == DS18S20FamilyCode;
        }
Exemplo n.º 25
0
        public static async Task Main()
        {
            try
            {
                var ct      = CancellationToken.None;
                var oneWire = new OneWire();
                while (true)
                {
                    var readings = await oneWire.Read(ct).ConfigureAwait(false);

                    foreach (var reading in readings)
                    {
                        Console.WriteLine(reading);
                    }
                    await Task.Delay(TimeSpan.FromSeconds(10), ct).ConfigureAwait(false);
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
#pragma warning restore CA1031 // Do not catch general exception types
            {
                Console.WriteLine(FormattableString.Invariant($"Error: {ex}"));
            }
        }
Exemplo n.º 26
0
 /// <summary>
 ///     Construct a DS18B20
 /// </summary>
 /// <param name="oneWire">The OneWire bus the sensor is attached to</param>
 /// <param name="address">The address of the DS18B20, or 0 to use the all-call mode</param>
 /// <remarks>
 ///     In most applications, there is a single DS18B20 attached to the OneWire bus, and there are no other peripherals on
 ///     the bus. In this case, there's no need to worry about addressing, and you can simply read from the device directly:
 ///     \code
 ///     var sensor = new Ds18b20(board.Uart);
 ///     while(!Console.KeyAvailable)
 ///     {
 ///     Console.WriteLine(sensor.Fahrenheit);
 ///     }
 ///     \endcode
 ///     Note that this property read will take more than 750 ms to complete, as the conversion time of this sensor is long.
 ///     If using this in a GUI-based project, you should fetch the update asynchronously to avoid blocking the GUI thread:
 ///     \code
 ///     sensor.AutoUpdateWhenPropertyRead = false // set this once to disable updates when invoking property reads
 ///     ...
 ///     await sensor.UpdateAsync(); // request an update -- will take ~750 ms.
 ///     this.SensorValue = sensor.Celsius; // copy the updated sensor data to our data-binding property
 ///     RaisePropertyChanged("SensorValue"); // inform the UWP/WPF GUI that we have new sensor data
 ///     \endcode
 /// </remarks>
 public Ds18b20(OneWire oneWire, ulong address = 0)
 {
     this.oneWire = oneWire;
     Address      = address;
     Task.Run(oneWire.StartOneWireAsync).Wait();
 }
Exemplo n.º 27
0
 /// <summary>
 ///     Construct a Group of Ds18b20 sensors
 /// </summary>
 /// <param name="oneWire">The OneWire interface (UART) this group is attached to</param>
 public Group(OneWire oneWire)
 {
     this.oneWire = oneWire;
 }
Exemplo n.º 28
0
 /// <summary>
 /// Costruttore
 /// </summary>
 /// <param name="res">Nome del canale 1-Wire</param>
 protected OneWireDevice(OW_Pin res)
 {
     Ow = new OneWire(new OutputPort((Cpu.Pin)res, false));
 }
Exemplo n.º 29
0
        static int Parse(string[] args)
        {
            Console.WriteLine("Preparing data...");
            string text = File.ReadAllText(args[0]).Trim('\n').Trim('\r');
            //Handle device verbose output
            int header_index = text.IndexOf('\r');

            if (!text.Substring(0, header_index).Contains(':'))
            {
                text = text.Remove(0, header_index + 1);
                BackupAndOverwrite(args[0], text);
            }
            //Handle multiple captures
            if (text.Contains("EOF"))
            {
                string[] files = text.Split(new string[] { "EOF" }, StringSplitOptions.RemoveEmptyEntries);
                if (files.Length > 1)
                {
                    for (int i = 0; i < files.Length; i++)
                    {
                        File.WriteAllText(args[0].Replace(Path.GetFileName(args[0]),
                                                          Path.GetFileNameWithoutExtension(args[0]) + "_splitted" + (i + 1).ToString() + Path.GetExtension(args[0])),
                                          files[i]);
                    }
                    if (args.Contains("\\i:"))
                    {
                        text = files[int.Parse(args.Where(x => x.Contains("\\i:")).First()) - 1];
                    }
                    else
                    {
                        Console.WriteLine("File contained multiple captures and was split (code 3).");
                        return(3);
                    }
                }
                else
                {
                    text = files[0];
                    BackupAndOverwrite(args[0], text);
                }
            }
            //Handle single capture
            string[] lines = text.Split('\r').Select(x => x.Trim('\n')).ToArray();
            //Add additional points for the data to be plotted properly in any software (e.g. in excel) and write .csv file
            List <KeyValuePair <uint, bool> > data = new List <KeyValuePair <uint, bool> >(lines.Length * 2);

            string[] s = lines[0].Split(':');
            data.Add(new KeyValuePair <uint, bool>(uint.Parse(s[0]), uint.Parse(s[1]) > 0));
            for (int i = 1; i < lines.Length; i++) //Max 2560 lines
            {
                if (lines[i] != "")
                {
                    s = lines[i].Split(':');
                    data.Add(new KeyValuePair <uint, bool>(uint.Parse(s[0]), uint.Parse(s[1]) > 0));
                    data.Insert(data.Count - 1, new KeyValuePair <uint, bool>(data.Last().Key - 1, data[data.Count - 2].Value));
                }
            }
            if (args.Contains("/csv"))
            {
                lines = new string[data.Count];
                char c = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator == "," ? ';' : ',';
                for (int i = 0; i < data.Count; i++)
                {
                    lines[i] = data[i].Key.ToString() + c + Convert.ToInt32(data[i].Value).ToString();
                }
                Console.WriteLine("Writing prepared data to a new file...");
                File.WriteAllLines(args[0].Replace(Path.GetExtension(args[0]), ".csv"), lines);
            }
            Console.WriteLine("Parsing data...");
            //Parse 1-Wire pulses
            List <OneWire.Pulse> pulses = new List <OneWire.Pulse>(data.Count);

            for (int i = 1; i < data.Count; i++)
            {
                if (!data[i].Value && !data[i - 1].Value)   //If we've got a low pulse (two consecutive low points)
                {
                    pulses.Add(new OneWire.Pulse(data[i - 1].Key, data[i].Key - data[i - 1].Key));
                    if (pulses.Last().Duration == 0)
                    {
                        pulses.Last().Duration = 1;                               //Possible zeros are imperfections of the logic sniffer
                    }
                }
            }
            OneWire.CommandRow <OneWire.Pulse.OperationClass> op_class =
                new OneWire.CommandRow <OneWire.Pulse.OperationClass>
                (
                    OneWire.Pulse.OperationClass.OWReadWrite, 64
                );
            OneWire.CommandRow <OneWire.Pulse.PulseTypes> p_types = new OneWire.CommandRow <OneWire.Pulse.PulseTypes>();
            OneWire OWC = new OneWire(ref pulses, new OneWire.Slave(ref op_class, ref p_types, Decode));

            //Use everything parsed by OWC (transactions):
            Console.WriteLine("Writing parsed data to a new file...");
            string new_text = "";

            for (int i = 0; i < OWC.Transactions.Count; i++)
            {
                new_text += '#' + (i + 1).ToString() + " @ " + OWC.Transactions[i].Pulses[0].Time.ToString() + " > ";
                if (OWC.Transactions[i].DataParsable.Key)
                {
                    new_text += "M: " + OWC.Transactions[i].HEXMaster + ", ";
                }
                if (OWC.Transactions[i].DataParsable.Value)
                {
                    new_text += "S: " + OWC.Transactions[i].HEXSlave + ", ";
                }
                if (OWC.Transactions[i].Error != OneWire.Transaction.Errors.TRNoErorrs)
                {
                    new_text += "E: " + OneWire.Transaction.ErrorName(OWC.Transactions[i].Error);
                }
                new_text = new_text.Trim(',', ' ');
                if (OWC.Transactions[i].InnerErrors.InitialRow.Length > 1)
                {
                    new_text += " =>";
                    for (uint j = 0; j < OWC.Transactions[i].InnerErrors.Length; j++)
                    {
                        if (OWC.Transactions[i].InnerErrors[j] != OneWire.Transaction.Errors.TRNoErorrs)
                        {
                            new_text += Environment.NewLine + '\t' + OneWire.Transaction.ErrorName(OWC.Transactions[i].InnerErrors[j]);
                            new_text += " @ " + (OWC.Transactions[i].Pulses[j].Time).ToString();
                        }
                    }
                }
                new_text += Environment.NewLine;
            }
            new_text += "L:";
            for (int i = 0; i < OWC.Pulses.Count; i++)
            {
                new_text += Environment.NewLine + OneWire.Pulse.GetTypeName(OWC.Pulses[i].Type, true);
                new_text += " = " + OWC.Pulses[i].Duration + " @ " + OWC.Pulses[i].Time;
            }
            File.WriteAllText(args[0].Replace(Path.GetFileName(args[0]),
                                              Path.GetFileNameWithoutExtension(args[0]) + "_parsed" + Path.GetExtension(args[0])), new_text);
            return(0);
        }
Exemplo n.º 30
0
 private bool PreInit(object sender, EventArgs e)
 {
     BlinkingLed = new OutputCompare(EMX.Pin.IO17, false, 2);
     Blink(100);
     OneWireBus = new OneWire(EMX.Pin.IO13);
     return true;
 }
Exemplo n.º 31
0
 public DS18B20(OneWire ow) : this(ow, null)
 {
 }
Exemplo n.º 32
0
 public DS18B20Sensor(Cpu.Pin pin)
 {
     oneWire = new OneWire(new OutputPort(pin, false));
 }
Exemplo n.º 33
0
 public BusMasterOneWire(OneWire bus)
     : base(0)
 {
     this.bus = bus;
 }