// Overridden from IDeviceManager
        public IDevice CreateDevice(ISerialNumber serialNumber, string connectionAddress, EProtocolVersion protocolVersion)
        {
            lock (locker) {
                IDevice ret = this[serialNumber];

                if (ret == null)
                {
                    var connection = connectionManager.CreateConnection(connectionAddress, protocolVersion);

                    var protocol = Protocol.FindProtocolFromVersion(protocolVersion);
                    if (protocol == null)
                    {
                        protocol = Protocol.FindProtocolFromVersion(EProtocolVersion.V1);
                    }
                    var definition = deviceFactory.GetDeviceDefinition(serialNumber);
                    ret = definition.CreateDevice(ion, serialNumber, connection, protocol);
                    ret.onDeviceEvent += OnDeviceEvent;
                }

                if (ret == null)
                {
                    var msg = BuildErrorHeader(serialNumber, protocolVersion) +
                              ": Please ensure that the serial number is resgistered in ION.Core.Devices.Devices.xml";
                    Log.C(this, msg);
                    throw new Exception(msg);
                }

                return(ret);
            }
        }
        private IDevice CreateDeviceInternal(ISerialNumber serialNumber, EProtocolVersion protocolVersion, bool connected)
        {
            IDevice ret = this[serialNumber];

            if (ret == null)
            {
                var connectionState = EConnectionState.Disconnected;
                if (connected)
                {
                    connectionState = EConnectionState.Connected;
                }
                var connection = new RemoteConnection(serialNumber.rawSerial, connectionState);

                var protocol = Protocol.FindProtocolFromVersion(protocolVersion);

                var definition = deviceFactory.GetDeviceDefinition(serialNumber);

                ret = definition.CreateDevice(ion, serialNumber, connection, protocol);

                ret.onDeviceEvent += OnDeviceEvent;
            }

            if (ret == null)
            {
                var msg = BuildErrorHeader(serialNumber, protocolVersion) +
                          ": Please ensure that the serial number is resgistered in ION.Core.Devices.Devices.xml";
                Log.C(this, msg);
                throw new Exception(msg);
            }
            //ret.isConnected = connected;
            return(ret);
        }
 /// <summary>
 /// Notifes the OnDeviceFound callback of a newly found device.
 /// </summary>
 /// <param name="serialNumber">Serial number.</param>
 /// <param name="address">Address.</param>
 /// <param name="packet">Packet.</param>
 /// <param name="version">Version.</param>
 private void NotifyDeviceFound(ISerialNumber serialNumber, string address, byte[] packet, EProtocolVersion version)
 {
     if (onDeviceFound != null)
     {
         onDeviceFound(this, serialNumber, address, packet, version);
     }
 }
 public LeConnection(AppService service, BluetoothDevice device, ISerialNumber serialNumber)
 {
     this.service      = service;
     this.device       = device;
     this.serialNumber = serialNumber;
     this.protocol     = Protocol.FindProtocolFromVersion(EProtocolVersion.V1);
 }
Example #5
0
        /// <summary>
        /// Creates an IDevice from this device definition.
        /// </summary>
        /// <returns>The device.</returns>
        /// <exception cref="ArgumentException">If the IDevice could not be created with the given arguments.</exception>
        /// <param name="serialNumber">Serial number.</param>
        /// <param name="connection">Connection.</param>
        /// <param name="protocol">Protocol.</param>
        public IDevice CreateDevice(IION ion, ISerialNumber serialNumber, IConnection connection, IProtocol protocol)
        {
            if (!(serialNumber is GaugeSerialNumber))
            {
                /////should not throw exeptions
                //throw new ArgumentException("Cannot create device: expected GaugeSerialNumber, received: " + serialNumber.GetType().Name);
                return(null);
            }

            if (!(protocol is IGaugeProtocol))
            {
                /////should not throw exeptions
                //throw new ArgumentException("Cannot create device: expected an IGaugeProtocol, received: " + protocol.GetType().Name);
                return(null);
            }

            var ret = new GaugeDevice(serialNumber as GaugeSerialNumber, connection, protocol as IGaugeProtocol);
            var s   = new List <GaugeDeviceSensor>();

            int i = 0;

            foreach (var sensorDefinition in sensorDefinitions)
            {
                var sensor = new GaugeDeviceSensor(ion, ret, i++, sensorDefinition.sensorType, sensorDefinition.isRelative);
                sensor.removable      = sensorDefinition.isRemovable;
                sensor.minMeasurement = sensorDefinition.minimumMeasurement;
                sensor.maxMeasurement = sensorDefinition.maximumMeasurement;
                sensor.SetSupportedUnits(sensorDefinition.supportedUnits.ToArray());
                s.Add(sensor);
            }

            ret.sensors = s.ToArray();

            return(ret);
        }
Example #6
0
        public bool Validated(ISerialNumber serialNumber)
        {
            var number = serialNumber.Get().Encrypt();

            if (!File.Exists(FileName))
            {
                AddSerialNumber(number);
                return(true);
            }

            var serials = File.ReadAllLines(FileName);

            if (serials.Length > LicenseLimitedCount)
            {
                throw new Exception("You should have a license to copy this application.");
            }
            if (serials.Contains(number))
            {
                return(true);
            }
            var sb = new StringBuilder();

            sb.AppendLine(number);
            foreach (var serial in serials)
            {
                sb.AppendLine(serial);
            }
            AddSerialNumber(sb.ToString());
            return(true);
        }
Example #7
0
 /// <summary>
 /// Attempts to resolve the serial number from the device and its scan record.
 /// </summary>
 /// <returns><c>true</c>, if serial number was resolved, <c>false</c> otherwise.</returns>
 /// <param name="device">Device.</param>
 /// <param name="scanRecord">Scan record.</param>
 /// <param name="sn">Sn.</param>
 private bool ResolveSerialNumber(BluetoothDevice device, byte[] scanRecord, out ISerialNumber sn)
 {
     if (device.Name.IsValidSerialNumber())
     {
         sn = device.Name.ParseSerialNumber();
         return(true);
     }
     else if (scanRecord != null)
     {
         var ussn = System.Text.Encoding.UTF8.GetString(scanRecord, 0, 8);
         if (ussn.IsValidSerialNumber())
         {
             sn = ussn.ParseSerialNumber();
             // We need to format the scan record.
             var buffer = new byte[20];
             Array.Copy(scanRecord, 8, buffer, 0, buffer.Length);
             Array.Clear(scanRecord, 0, scanRecord.Length);
             Array.Copy(buffer, scanRecord, buffer.Length);
             return(true);
         }
         else
         {
             sn = null;
             return(false);
         }
     }
     else
     {
         sn = null;
         return(false);
     }
 }
        // Overridden from IDeviceManager
        public IDevice CreateDevice(ISerialNumber serialNumber, EProtocolVersion protocolVersion, bool connected)
        {
            var ret = CreateDeviceInternal(serialNumber, protocolVersion, connected);

            // The register proved superfluous. Consider merging this functions with the internal one.
            // Register(ret);
            return(ret);
        }
Example #9
0
 // Implemented from IDeviceManager
 public IDevice this[ISerialNumber serialNumber] {
     get {
         if (serialNumber != null && __devices.ContainsKey(serialNumber))
         {
             return(__devices[serialNumber]);
         }
         else
         {
             return(null);
         }
     }
 }
        public IConnection GetConnection(ISerialNumber serialNumber)
        {
            foreach (var connection in addressConnectionLookup.Values)
            {
                if (connection.serialNumber.Equals(serialNumber))
                {
                    return(connection);
                }
            }

            return(null);
        }
        /// <summary>
        /// The delegate that is called when a device is found by the device manager's scan mode.
        /// </summary>
        private void OnDeviceFound(IConnectionManager cm, ISerialNumber serialNumber, string address, byte[] packet, EProtocolVersion protocol)
        {
            lock (locker) {
                var device = this[serialNumber];

                if (device == null)
                {
                    device = CreateDevice(serialNumber, address, protocol);
                    MarkDeviceAsFound(device, true);
                }

                device.connection.lastPacket = packet;
                device.connection.lastSeen   = DateTime.Now;
                NotifyOfDeviceEvent(DeviceEvent.EType.Found, device);
            }
        }
        // Overridden from IDeviceManager
        public async Task <bool> DeleteDevice(ISerialNumber serialNumber)
        {
            var device = this[serialNumber];

            if (device != null)
            {
                device.Dispose();
                Unregister(device);
                var db      = ion.database;
                var deleted = await db.DeleteAsync <DeviceRow>(await db.DeconstructDevice(device));

                NotifyOfDeviceEvent(DeviceEvent.EType.Deleted, device);
                return(true);
            }
            return(false);
        }
        // Overridden form IDeviceManager
        public IDevice this[ISerialNumber serialNumber] {
            get {
                IDevice ret = null;

                if (__knownDevices.ContainsKey(serialNumber))
                {
                    ret = __knownDevices[serialNumber];
                }

                if (ret == null && __foundDevices.ContainsKey(serialNumber))
                {
                    ret = __foundDevices[serialNumber];
                }

                return(ret);
            }
        }
Example #14
0
 /// <Docs>To be added.</Docs>
 /// <para>Returns the sort order of the current instance compared to the specified object.</para>
 /// <summary>
 /// Compares to.
 /// </summary>
 /// <returns>The to.</returns>
 /// <param name="other">Other.</param>
 public int CompareTo(ISerialNumber other)
 {
     if (other is GaugeSerialNumber)
     {
         if (deviceModel == other.deviceModel)
         {
             return(batchId.CompareTo(other.batchId));
         }
         else
         {
             return(deviceModel.CompareTo(other.deviceModel));
         }
     }
     else
     {
         return(deviceType.CompareTo(other.deviceType));
     }
 }
Example #15
0
        internal void OnDeviceFound(BluetoothDevice device, byte[] scanRecord)
        {
            ISerialNumber sn = null;

            if (!ResolveSerialNumber(device, scanRecord, out sn))
            {
                // We could not resolve the device (or it is not ours)
                return;
            }

            // Note: gauges that have a scan record come with an interesting issue. There are two radios on those devices. As
            // such, the radio that would actually provide a scan record is NOT the radio that accepts connections. So, we
            // must filter out the connections that are providing scan records and only pass empty scan record connections to
            // device manager.

            if (scanRecord == null)
            {
                // Notify the device manager a newly found device.
                var pv = ResolveProtocolVersion(device, sn, scanRecord);

                if (onDeviceFound != null)
                {
                    onDeviceFound(this, sn, device.Address, scanRecord, pv);
                }
            }
            else
            {
                // We need to simply get the ACTUAL connection and pass it the scan record.
                var idevice = ion.deviceManager[sn];
                if (idevice == null)
                {
                    // The device manager does not know about this device. This is actually an issue as we can't create the device
                    // with the current bluetooth device that we were given. So we must ignore the device until we can get in
                    // enough in range to discover the actual connectable bluetoothdevice.
                    Log.E(this, "Received a broadcast packet for an unknown device. Ignoring device");
                }
                else
                {
                    // The application is aware of the device, this is great. Just simply set the connection's last packet to
                    // perform the broadcast update.
                    idevice.connection.lastPacket = scanRecord;
                }
            }
        }
        /// <summary>
        /// Gets the index of the device.
        /// </summary>
        /// <returns>The device index.</returns>
        /// <param name="serialNumber">Serial number.</param>
        /// <param name="unitCode">Unit code.</param>
        public int GetDeviceIndex(ISerialNumber serialNumber, int sensorIndex)
        {
            if (serialNumber != null)
            {
                //for (int i = 0; i < manifolds.Count; i++) {
                for (int i = 0; i < sensors.Count; i++)
                {
                    //var p = manifolds[i].primarySensor as GaugeDeviceSensor;
                    var p = sensors[i] as GaugeDeviceSensor;

                    if (p != null)
                    {
                        if (serialNumber.rawSerial == p.device.serialNumber.rawSerial && p.index == sensorIndex)
                        {
                            return(i);
                        }
                        ;
                    }
                }
            }
            return(-1);
        }
        /// <summary>
        /// The delegate that is called when a device is found by the device manager's scan mode.
        /// </summary>
        /// <param name="device">Device.</param>
        private void OnDeviceFound(IConnectionManager cm, ISerialNumber serialNumber, string address, byte[] packet, EProtocolVersion protocol)
        {
            var device = this[serialNumber];

            if (device == null)
            {
                device = CreateDeviceInternal(serialNumber, EProtocolVersion.V4, false);
                __foundDevices[serialNumber] = device;
            }

            if (device.protocol is IGaugeProtocol)
            {
                var gp = device.protocol as IGaugeProtocol;
                if (gp.supportsBroadcasting)
                {
                    device.HandlePacket(packet);
                }
            }
            device.connection.lastSeen = DateTime.Now;

            NotifyOfDeviceEvent(DeviceEvent.EType.Found, device);
        }
        /// <summary>
        /// Parses the Rigado gauge broadcast packet.
        /// </summary>
        /// <returns><c>true</c>, if broadcast packet was parsed, <c>false</c> otherwise.</returns>
        /// <param name="source">Source.</param>
        /// <param name="serialNumber">Serial number.</param>
        /// <param name="packet">Packet.</param>
        public static bool ParseBroadcastPacket(byte[] source, out ISerialNumber serialNumber, out byte[] packet)
        {
            if (source == null || source.Length < 10)
            {
                serialNumber = null;
                packet       = null;
                return(false);
            }

            //Log.D(typeof(RigadoBroadcastParser).Name, "Resolving advertising packet for: " + source.ToByteString());

            var rawId    = source.Subset(2, 4);
            var manfacId = rawId[0] | rawId[1] << 8;

            if (manfacId == AppionConstants.MANFAC_ID)
            {
                var rawSerialNumber = source.Subset(4, 12);
                var sn = System.Text.Encoding.UTF8.GetString(rawSerialNumber, 0, rawSerialNumber.Length);
                if (sn.IsValidSerialNumber())
                {
                    serialNumber = sn.ParseSerialNumber();
                    packet       = source.Subset(12);
                    return(true);
                }
                else
                {
                    serialNumber = null;
                    packet       = null;
                    return(false);
                }
            }
            else
            {
                serialNumber = null;
                packet       = null;
                return(false);
            }
        }
Example #19
0
 /// <summary>
 /// Attempts to resolve the protocol version for the device.
 /// </summary>
 /// <returns>The protocol version.</returns>
 /// <param name="device">Device.</param>
 /// <param name="sn">Sn.</param>
 /// <param name="scanRecord">Scan record.</param>
 private EProtocolVersion ResolveProtocolVersion(BluetoothDevice device, ISerialNumber sn, byte[] scanRecord)
 {
     if (scanRecord != null && scanRecord[0] == 4)
     {
         return(EProtocolVersion.V4);
     }
     else
     {
         // TODO [email protected]: We need a better way to determine a device's protocol.
         if (sn.rawSerial.Length == 8)
         {
             return(EProtocolVersion.V4);
         }
         else if (device.Type == BluetoothDeviceType.Classic)
         {
             return(EProtocolVersion.Classic);
         }
         else
         {
             return(EProtocolVersion.V1);
         }
     }
 }
Example #20
0
 public CalibrationCertificateRequestResult(ISerialNumber serialNumber)
 {
     this.serialNumber = serialNumber;
     this.success      = false;
 }
Example #21
0
        // Implemented from IDeviceManager
        public IDevice CreateDevice(ISerialNumber serialNumber, string connectionAddress, EProtocolVersion protocol)
        {
            var p = Protocol.FindProtocolFromVersion(protocol);

            return(deviceFactory.GetDeviceDefinition(serialNumber).CreateDevice(ion, serialNumber, new RemoteConnection(serialNumber.ToString()), p));
        }
Example #22
0
 // Implemented from IDeviceManager
 public Task <bool> DeleteDevice(ISerialNumber serialNumber)
 {
     return(Task.FromResult(false));
 }
Example #23
0
 /// <summary>
 /// Queries the device definition from the given serial number.
 /// </summary>
 /// <returns>The device definition.</returns>
 /// <param name="serialNumber">Serial number.</param>
 public IDeviceDefinition GetDeviceDefinition(ISerialNumber serialNumber)
 {
     return(definitions[serialNumber.deviceCode]);
 }
 // Implemented from ISerialNumber
 public int CompareTo(ISerialNumber other)
 {
     return(rawSerial.CompareTo(other.rawSerial));
 }
 /// <summary>
 /// Builds a string that can be used as an error header for the logger.
 /// </summary>
 /// <returns>The error header.</returns>
 /// <param name="serialNumber">Serial number.</param>
 /// <param name="protocol">Protocol.</param>
 private string BuildErrorHeader(ISerialNumber serialNumber, EProtocolVersion protocol)
 {
     return("Failed to create device from serial number: " + serialNumber + ", Protocol: " + protocol);
 }
Example #26
0
 public IONBtDevice(BluetoothDevice device, ISerialNumber serialNumber)
 {
     this.bluetoothDevice = device;
     this.serialNumber    = serialNumber;
 }
        // Overridden form CBCentralManagerDelegate
        public override void DiscoveredPeripheral(CBCentralManager central, CBPeripheral peripheral, NSDictionary advertisementData, NSNumber RSSI)
        {
            string name = null;

            var values = advertisementData.Values;

            var data = advertisementData[CBAdvertisement.DataManufacturerDataKey];

            if (!AttemptNameFetch(peripheral, advertisementData, out name))
            {
//        Log.E(this, "Failed to resolve peripheral name '" + name + "'. The peripheral will not be presented to the application.");
                return;
            }

            if (!name.IsValidSerialNumber())
            {
                return;
            }

            IConnection connection = null;
            var         uuid       = CBUUID.FromNSUuid(peripheral.Identifier);

            if (connectionLookup.ContainsKey(uuid))
            {
                connection = connectionLookup[uuid];
            }

            ISerialNumber sn = null;

            byte[] packet = null;

            if (RigadoBroadcastParser.ParseBroadcastPacket(ExtractBroadcastData(advertisementData), out sn, out packet))
            {
                // We received a fully valid broadcast packet. We know that the gauge is an Appion gauge and should resolve it.
                if (connection == null)
                {
                    // We have not discovered this device before. Notify the world
                    NotifyDeviceFound(sn, uuid.ToString(), packet, EProtocolVersion.V4);
                }
                else
                {
                    // The connection already exists. Give it a new packet.
                    NotifyDeviceFound(sn, uuid.ToString(), null, EProtocolVersion.V4);
                    connection.lastPacket = packet;
                    connection.lastSeen   = DateTime.Now;
                }
            }
            else
            {
                // We didn't receive a valid broadcasting packet, but the device may still be ours.
                if (name.IsValidSerialNumber())
                {
                    // See, the device has a valid serial number.
                    sn = name.ParseSerialNumber();
                    // Check that an iserialnumber was returned
                    if (sn != null)
                    {
                        if (connection == null)
                        {
                            var p = FindProtocolFromDeviceModel(sn.deviceModel);
                            // We have not discovered this device before. Notify the world
                            NotifyDeviceFound(sn, uuid.ToString(), null, p);
                        }
                        else
                        {
                            // The connection already exists. Update the last time that it was seen.
                            var d = ion.deviceManager[sn];
                            if (d == null)
                            {
                                //Log.E(this, "Failed to get device from device manager");
                                return;
                            }
                            NotifyDeviceFound(sn, uuid.ToString(), null, d.protocol.version);
                            connection.lastSeen = DateTime.Now;
                        }
                    }
                }
                else
                {
                    Log.D(this, "Ignoring non-appion device: " + name);
                }
            }
        }
 public IDevice CreateDevice(ISerialNumber serialNumber, string connectionAddress, EProtocolVersion protocol)
 {
     return(null);
 }
 /// <summary>
 /// Queries for the device with the given serial number.
 /// </summary>
 /// <returns>The for using serial number async.</returns>
 /// <param name="serialNumber">Serial number.</param>
 public static Task <DeviceRow> QueryForUsingSerialNumberAsync(this IONDatabase db, ISerialNumber serialNumber)
 {
     //Log.D("DeviceDatabaseExtensions", "QueryFor: " + serialNumber);
     try {
         var serial = serialNumber.ToString();
         if (db.Table <DeviceRow>().Count() > 0)
         {
             return(Task.FromResult(db.Table <DeviceRow>().Where(x => x.serialNumber == serial).First()));
         }
         else
         {
             return(Task.FromResult(default(DeviceRow)));
         }
     } catch (Exception e) {
         Log.E(typeof(DeviceDatabaseExtensions).Name, "Failed to query for using serial number.", e);
         return(Task.FromResult(default(DeviceRow)));
     }
 }
        /// <summary>
        /// </summary>
        /// <param name="ion">Ion.</param>
        public static DeviceSensorGaugeReportData QueryFromSessionOrThrow(IION ion, long sessionId, ISerialNumber serialNumber, int index)
        {
            var def = ion.deviceManager.deviceFactory.GetDeviceDefinition(serialNumber);

            if (def == null)
            {
                throw new Exception("Cannot query sensor data for " + serialNumber + ": failed to find device definition");
            }

            var gaugeDef = def as GaugeDeviceDefinition;

            if (gaugeDef == null)
            {
                throw new Exception("Cannot query sensor data for " + serialNumber + ": serial number returned an invalid device definition");
            }

            var sensorDef = gaugeDef[index];

            if (sensorDef == null)
            {
                throw new Exception("Cannot query sensor data for " + serialNumber + ": serial number returned a device definition with invalid sensor definition");
            }

            var table           = ion.database.Table <SensorMeasurementRow>();
            var rawSerialNumber = serialNumber.ToString();
            var rows            = table.Where(smr => smr.frn_SID == sessionId && smr.serialNumber.Equals(rawSerialNumber) && smr.sensorIndex == index)
                                  .OrderBy(smr => smr.recordedDate);

            var measurements = new List <MeasurementData>();

            foreach (var row in rows)
            {
                measurements.Add(new MeasurementData()
                {
                    measurement  = sensorDef.minimumMeasurement.unit.standardUnit.OfScalar(row.measurement),
                    recordedDate = row.recordedDate,
                });
            }

            return(null);
        }