Exemplo n.º 1
0
        private DaqStatusValues QueryStatus()
        {
            var status = DaqStatusValues.Default;

            using (IsolateConnection()) {
                System.Diagnostics.Debug.Write("Status");
                ConnectIfRequired();
                var queryPacket = GenerateQueryDaqStatusPacketData();
                if (null != UsbConn && UsbConn.WritePacket(queryPacket))
                {
                    queryPacket = UsbConn.ReadPacket(QuarterSecond);
                    if (null != queryPacket)
                    {
                        var volUsbRaw = (ushort)(queryPacket[2] | (queryPacket[3] << 8));
                        var volBatRaw = (ushort)(queryPacket[4] | (queryPacket[5] << 8));
                        var tmpDaqRaw = (ushort)(queryPacket[7] | (queryPacket[6] << 8));

                        var temp   = (tmpDaqRaw / 10.0) - 40.0;
                        var volUsb = (volUsbRaw / 1024.0) * 6.4;
                        var volBat = (volBatRaw / 1024.0) * 6.4;

                        status = new DaqStatusValues(volBat, volUsb, temp);
                        System.Diagnostics.Debug.WriteLine(": " + status);
                    }
                }
                if (status == DaqStatusValues.Default)
                {
                    System.Diagnostics.Debug.WriteLine(": FAIL!");
                }
            }
            return(status);
        }
Exemplo n.º 2
0
        public CorrectionFactors GetCorrectionFactors(int nid)
        {
            using (NewQueryPause()) {
                CorrectionFactors factors = null;
                using (IsolateConnection()) {
                    ConnectIfRequired();

                    var ok = AnemEnterBootMode(nid);
                    Thread.Sleep(HalfSecond);

                    try {
                        if (ok)
                        {
                            var packet = GenerateGetCorrectionFactoryPacketData((byte)nid);
                            if (WritePacket(packet))
                            {
                                packet = UsbConn.ReadPacket(OneSecond);
                                if (null != packet)
                                {
                                    factors = CorrectionFactors.ToCorrectionFactors(packet, 3);
                                }
                            }
                        }
                    }
                    finally {
                        Thread.Sleep(HalfSecond);
                        AnemReset(nid);
                    }
                }
                return(factors);
            }
        }
Exemplo n.º 3
0
        public PackedReadingValues QueryValues(int nid)
        {
            if (nid < 0 || nid > 3)
            {
                throw new ArgumentOutOfRangeException("nid");
            }

            using (IsolateConnection()) {
                System.Diagnostics.Debug.Write(String.Format("Query {0}", nid));
                ConnectIfRequired();
                var queryPacket = GenereateQueryPacketData(nid);
                if (WritePacket(queryPacket))
                {
                    for (int i = 0; i < 3; i++)
                    {
                        queryPacket = UsbConn.ReadPacket(TenthSecond);
                        if (null != queryPacket)
                        {
                            var result = PackedReadingValues.FromDeviceBytes(queryPacket, 1);
                            System.Diagnostics.Debug.WriteLine(String.Format(", {0}: {1}", nid, result));
                            return(result);
                        }
                    }
                }
            }
            System.Diagnostics.Debug.WriteLine(String.Format(": FAIL!", nid));
            return(PackedReadingValues.Invalid);
        }
Exemplo n.º 4
0
 /// <summary>
 /// Closes and disposes the connection.
 /// </summary>
 protected virtual void DisposeComm()
 {
     if (null != UsbConn)
     {
         UsbConn.Dispose();
     }
 }
Exemplo n.º 5
0
        private QueryResult GetMemoryRegionInfos()
        {
            byte[] packet = GenerateEmptyPacketData();
            packet[1] = 0x02;             // query
            if (!UsbConn.WritePacket(packet))
            {
                return(null);
            }

            packet = UsbConn.ReadPacket();
            if (null == packet)
            {
                return(null);
            }

            var result = new QueryResult {
                BytesPerPacket = packet[2]
            };

            for (int i = 0; i < QueryResult.MaxRegions; i++)
            {
                var typeFlag = packet[4 + (i * 9)];
                if (0xff == typeFlag)
                {
                    break;
                }
                result.Add(new MemoryRegionInfo(
                               typeFlag,
                               BitConverter.ToUInt32(packet, 5 + (i * 9)),
                               BitConverter.ToUInt32(packet, 9 + (i * 9))
                               ));
            }
            return(result);
        }
Exemplo n.º 6
0
        public bool PutCorrectionFactors(int nid, CorrectionFactors factors)
        {
            using (NewQueryPause()) {
                bool ok;
                using (IsolateConnection()) {
                    ConnectIfRequired();

                    ok = AnemEnterBootMode(nid);
                    try {
                        Thread.Sleep(HalfSecond);
                        var packet = GeneratePutCorrectionFactorsPacketData((byte)nid, factors);
                        if (WritePacket(packet))
                        {
                            packet = UsbConn.ReadPacket(OneSecond);
                            ok    &= IsValidPutFactorsResponse(packet);
                        }
                    }
                    finally {
                        Thread.Sleep(HalfSecond);
                        AnemReset(nid);
                    }
                }
                return(ok);
            }
        }
Exemplo n.º 7
0
        private DateTime RawQueryClock()
        {
            ConnectIfRequired();

            var queryPacket = GenerateEmptyPacketData();

            queryPacket[1] = 0x87;
            Thread.Sleep(25);
            if (WritePacket(queryPacket))
            {
                Thread.Sleep(25);
                queryPacket = UsbConn.ReadPacket(QuarterSecond);
                if (null != queryPacket)
                {
                    Swap(queryPacket, 4, 5);
                    DateTime dt;
                    return(DaqDataFileInfo.TryConvert7ByteDateTime(queryPacket, 2, out dt)
                                                ? dt
                                                : (
                               DaqDataFileInfo.TryConvertFrom7ByteDateTimeForce(queryPacket, 2, out dt)
                                                                ? dt
                                                                : default(DateTime)
                               )
                           );
                }
            }
            return(default(DateTime));
        }
Exemplo n.º 8
0
        private bool SetDaqTempSelected(bool useDaq)
        {
            using (NewQueryPause()) {
                var anyOk = false;
                using (IsolateConnection()) {
                    ConnectIfRequired();

                    for (int nid = 0; nid < _networkSize; nid++)
                    {
                        var ok = AnemEnterBootMode(nid);
                        try {
                            var packet = GenerateSetDaqTempPacket(useDaq, (byte)nid);
                            if (WritePacket(packet))
                            {
                                var res = UsbConn.ReadPacket();
                                ok &= IsValidSetDaqTempResponse(res);
                            }
                        }
                        finally {
                            AnemReset(nid);
                        }
                        anyOk |= ok;
                    }
                }
                return(anyOk);
            }
        }
Exemplo n.º 9
0
        private bool AnemEnterBootMode(byte nid)
        {
            var packet = GenerateEnterAnemBootPacketData(nid);

            if (WritePacket(packet))
            {
                packet = UsbConn.ReadPacket(QuarterSecond);
                return(IsValidEnterAnemBootResponse(packet, nid));
            }
            return(false);
        }
Exemplo n.º 10
0
        public bool Reboot()
        {
            byte[] packet = GenerateEmptyPacketData();
            packet[1] = 0x08;
            bool ok = UsbConn.WritePacket(packet);

            ok |= UsbConn.WritePacket(packet);
            System.Threading.Thread.Sleep(100);
            ok |= UsbConn.WritePacket(packet);
            return(ok);
        }
Exemplo n.º 11
0
        private bool AnemEnterProgramModeVersion2(byte nid)
        {
            var packet = GenerateEmptyPacketData();

            packet[1] = 0xa0;
            packet[2] = nid;
            if (WritePacket(packet))
            {
                packet = UsbConn.ReadPacket(HalfSecond);
                return(null != packet && packet[1] == 0xa0 && packet[2] == 0x01);
            }
            return(false);
        }
Exemplo n.º 12
0
 public void SetNetworkSize(int size)
 {
     using (NewQueryPause()) {
         using (IsolateConnection()) {
             System.Diagnostics.Debug.Write("SetSize");
             ConnectIfRequired();
             var queryPacket = GenerateNetworkSizePacketData(0xff, 0xff, size);
             if (UsbConn.WritePacket(queryPacket))
             {
                 _networkSize = size;
             }
             System.Diagnostics.Debug.WriteLine(": OK");
         }
     }
 }
Exemplo n.º 13
0
        private bool EraseDevice()
        {
            var packet = GenerateEmptyPacketData();

            packet[1] = 0x04;
            if (!UsbConn.WritePacket(packet))
            {
                return(false);
            }

            ClearPacket(packet);
            packet[1] = 0x02;
            UsbConn.WritePacket(packet);
            packet = UsbConn.ReadPacket();
            return(true);
        }
Exemplo n.º 14
0
        private bool AnemReset(byte nid)
        {
            const int numTries = 5;
            var       packet   = GenerateResetAnemPacket(nid);

            for (int i = 0; i < numTries; i++)
            {
                if (WritePacket(packet))
                {
                    var res = UsbConn.ReadPacket(QuarterSecond);
                    if (IsValidResetAnemResponse(res))
                    {
                        Thread.Sleep(QuarterSecond);
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemplo n.º 15
0
        private bool AnemResetVersion2(byte nid)
        {
            const int numTries = 5;
            var       packet   = GenerateEmptyPacketData();

            packet[1] = 0xaf;
            for (int i = 0; i < numTries; i++)
            {
                if (WritePacket(packet))
                {
                    var res = UsbConn.ReadPacket(QuarterSecond);
                    if (null != res && res[0] == 0xaf && res[1] == 0x01)
                    {
                        Thread.Sleep(QuarterSecond);
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemplo n.º 16
0
        public bool Program(MemoryRegionDataCollection memoryRegionDataBlocks, Action <double, string> progressUpdated)
        {
            if (!UsbConn.IsConnected)
            {
                return(false);
            }

            if (null == progressUpdated)
            {
                progressUpdated = NullProgressAction;
            }

            progressUpdated(0, queryTaskDesciption);

            QueryResult deviceMemoryRegions = GetMemoryRegionInfos();

            if (null == deviceMemoryRegions || deviceMemoryRegions.Count <= 0)
            {
                return(false);
            }

            progressUpdated(0.05, eraseTaskDesciption);

            EraseDevice();             // if the erase fails, we should probably keep going.

            double writeBaseProgress  = 0.3;
            double writeTotalProgress = 1.0 - writeBaseProgress;

            progressUpdated(writeBaseProgress, progTaskDesciption);

            IEnumerable <MemoryRegionInfo> memoryRegions = deviceMemoryRegions.Where(mri => mri.TypeFlag != 0x03);

            long totalBytes              = Math.Max(memoryRegions.Sum(mr => mr.Length), 1);
            long totalBytesWritten       = 0;
            long bytesForProgressUpdate  = totalBytes / 100;
            long lastProgressUpdateBytes = 0;

            foreach (MemoryRegionInfo currentRegion in memoryRegions.OrderByDescending(mr => mr.TypeFlag))
            {
                var lastAddress = currentRegion.Address + currentRegion.Length - 1;
                var packet      = GenerateEmptyPacketData();

                IEnumerable <MemoryRegionData> blocksForWrite = memoryRegionDataBlocks
                                                                .Where(dataBlock => dataBlock.Address >= currentRegion.Address && dataBlock.Address <= lastAddress)
                                                                .OrderBy(dataBlock => dataBlock.Address)
                ;

                var finalAddress      = blocksForWrite.Max(b => (int)b.LastAddress);
                var bytes             = new byte[currentRegion.Length];
                var baseOffsetAddress = currentRegion.Address;
                var lastLocalAddress  = -1;
                foreach (var block in blocksForWrite)
                {
                    var localBlockAddress = checked ((int)(block.Address - baseOffsetAddress));
                    for (int i = lastLocalAddress + 1; i < localBlockAddress; i++)
                    {
                        bytes[i] = 0xff;
                    }
                    var chunk = block.Data.ToArray();
                    Array.Copy(chunk, 0, bytes, localBlockAddress, chunk.Length);
                    lastLocalAddress = (int)block.LastAddress;
                }

                for (int i = lastLocalAddress + 1; i < currentRegion.Length; i++)
                {
                    bytes[i] = 0xff;
                }

                for (int txOffset = 0; txOffset < bytes.Length; txOffset += deviceMemoryRegions.BytesPerPacket)
                {
                    ClearPacket(packet);
                    packet[1] = 0x05;
                    int localAddress = (int)(baseOffsetAddress + txOffset);
                    if (localAddress > finalAddress)
                    {
                        break;
                    }
                    Array.Copy(BitConverter.GetBytes(localAddress), 0, packet, 2, 4);
                    byte bytesToWrite = (
                        (txOffset + deviceMemoryRegions.BytesPerPacket > bytes.Length)
                                                ? (byte)(bytes.Length - txOffset)
                                                : deviceMemoryRegions.BytesPerPacket
                        );
                    packet[6] = bytesToWrite;
                    //bytes.CopyTo(txOffset, packet, 7, bytesToWrite);
                    Array.Copy(bytes, txOffset, packet, 7, bytesToWrite);
                    totalBytesWritten += bytesToWrite;

                    if (totalBytesWritten >= lastProgressUpdateBytes + bytesForProgressUpdate)
                    {
                        lastProgressUpdateBytes = totalBytesWritten;
                        progressUpdated(writeBaseProgress + ((totalBytesWritten * writeTotalProgress) / (double)totalBytes), progTaskDesciption);
                    }
                    System.Diagnostics.Debug.WriteLine("Wrote@: " + (baseOffsetAddress + txOffset).ToString("X2") + ',' + bytesToWrite);
                    if (UsbConn.WritePacket(packet))
                    {
                        ;                         // was OK
                    }
                    else
                    {
                        ;                         // failed to write!
                    }
                }


                ClearPacket(packet);
                packet[1] = 0x06;
                UsbConn.WritePacket(packet);
            }

            progressUpdated(writeBaseProgress + writeTotalProgress, progTaskDesciption);

            return(true);
        }
Exemplo n.º 17
0
        public bool ProgramAnem(int nid, MemoryRegionDataCollection memoryRegionDataBlocks, Action <double, string> progressUpdated)
        {
            if (nid < 0 || nid > 255)
            {
                throw new ArgumentOutOfRangeException("nid");
            }
            if (null == progressUpdated)
            {
                progressUpdated = NullAction;                 // so we can avoid null checks all over the place
            }
            using (NewQueryPause()) {
                Thread.Sleep(ThreeQuarterSecond);
                bool result = true;
                try {
                    if (!UsbConn.IsConnected)
                    {
                        return(false);
                    }

                    progressUpdated(0, "Entering boot mode.");

                    using (IsolateConnection()) {
                        var anemBootResult = AnemEnterBootMode(nid);

                        if (!anemBootResult)
                        {
                            progressUpdated(0, "Bad boot response.");
                            if (0xff != nid)
                            {
                                result = false;
                            }
                        }
                        Thread.Sleep(HalfSecond);

                        progressUpdated(0, "Writing.");
                        int       totalBytes     = memoryRegionDataBlocks.Sum(b => (int)b.Size);
                        int       bytesSent      = 0;
                        int       lastNoticeByte = 0;
                        const int noticeInterval = 128;
                        int       dotCount       = 1;
                        if (result)
                        {
                            bool firstBlock = true;
                            foreach (var block in memoryRegionDataBlocks)
                            {
                                byte[]    data             = block.Data.ToArray();
                                int       checksumFails    = 0;
                                const int maxChecksumFails = 64;
                                const int stride           = 32;
                                for (int i = 0; i < data.Length; i += stride)
                                {
                                    int bytesToWrite = Math.Min(32, data.Length - i);
                                    int address      = i + (int)block.Address;
                                    var packet       = GenerateEmptyPacketData();
                                    packet[1] = 0x75;
                                    packet[2] = checked ((byte)nid);
                                    Array.Copy(BitConverter.GetBytes(address).Reverse().ToArray(), 0, packet, 3, 4);
                                    packet[7] = (byte)bytesToWrite;
                                    byte checkSum = data[i];
                                    int  endIndex = i + bytesToWrite;
                                    for (int csi = i + 1; csi < endIndex; csi++)
                                    {
                                        checkSum = unchecked ((byte)(checkSum + data[csi]));
                                    }
                                    packet[8] = checkSum;
                                    Array.Copy(data, i, packet, 9, bytesToWrite);

                                    UsbConn.ClearPacketQueue();
                                    if (!WritePacket(packet))
                                    {
                                        progressUpdated(0, "Write failure!");
                                        result = false;
                                        break;                                         //return false;
                                    }

                                    packet = UsbConn.ReadPacket(ThreeQuarterSecond);
                                    if (null == packet || packet[3] != checkSum)
                                    {
                                        checksumFails++;
                                        if (checksumFails <= (firstBlock ? 3 : maxChecksumFails))
                                        {
                                            i -= stride;
                                            continue;
                                        }
                                        progressUpdated(0, "Checksum failure.");
                                        result = false;
                                        break;
                                    }
                                    checksumFails = 0;

                                    bytesSent += bytesToWrite;
                                    if ((bytesSent - lastNoticeByte) > noticeInterval)
                                    {
                                        lastNoticeByte = bytesSent;
                                        dotCount++;
                                        if (dotCount > 3)
                                        {
                                            dotCount = 1;
                                        }
                                        progressUpdated(
                                            bytesSent / (double)(totalBytes),
                                            String.Concat("Writing", new String(Enumerable.Repeat('.', dotCount).ToArray()))
                                            );
                                    }
                                }
                                firstBlock = false;
                            }
                        }
                    }
                }
                catch (Exception ex) {
                    progressUpdated(0, ex.ToString());
                    result = false;
                }
                finally {
                    var resetOk = AnemReset(nid);
                    if (!resetOk)
                    {
                        progressUpdated(0, "Anem reboot failure.");
                    }
                    result &= resetOk;
                }
                return(result);
            }
        }
Exemplo n.º 18
0
        public bool ProgramAnemVersion2(int nid, MemoryRegionDataCollection memoryRegionDataBlocks, Action <double, string> progressUpdated)
        {
            if (nid < 0 || nid > 255)
            {
                throw new ArgumentOutOfRangeException("nid");
            }
            if (null == progressUpdated)
            {
                progressUpdated = NullAction;                 // so we can avoid null checks all over the place
            }
            using (NewQueryPause()) {
                Thread.Sleep(ThreeQuarterSecond);
                bool result = true;
                try {
                    if (!UsbConn.IsConnected)
                    {
                        return(false);
                    }

                    progressUpdated(0, "Entering boot mode.");

                    using (IsolateConnection()) {
                        var anemEnterProgramMode = AnemEnterProgramModeVersion2(nid);

                        if (!anemEnterProgramMode)
                        {
                            progressUpdated(0, "Bad boot response.");
                            if (0xf != nid && 0 != nid)
                            {
                                result = false;                                 // NOTE: if it was corrupted or unassigned, try it anyhow
                            }
                        }
                        Thread.Sleep(HalfSecond);

                        progressUpdated(0, "Writing.");
                        int       totalBytes     = memoryRegionDataBlocks.Sum(b => (int)b.Size);
                        int       bytesSent      = 0;
                        int       lastNoticeByte = 0;
                        const int noticeInterval = 128;
                        int       dotCount       = 1;
                        if (result)
                        {
                            bool firstBlock = true;
                            foreach (
                                var block in memoryRegionDataBlocks
                                .Where(x => x.Address < 0x3fff && x.LastAddress > 0x800)
                                .OrderBy(x => x.Address)
                                )
                            {
                                byte[]    data             = block.Data.ToArray();
                                int       checksumFails    = 0;
                                const int maxChecksumFails = 64;
                                const int stride           = 32;

                                long startIndex = 0;
                                if (block.Address < 0x800)
                                {
                                    startIndex = 0x800 - block.Address;
                                }

                                long indexLimit = data.Length;
                                if (block.LastAddress > 0x3fff)
                                {
                                    indexLimit = indexLimit - (block.LastAddress - 0x3fff);
                                }
                                int chunkCount = 0;
                                for (long i = startIndex; i < indexLimit; i += stride)
                                {
                                    var bytesToWrite = Math.Min(stride, (int)(data.Length - i));
                                    var address      = i + block.Address;
                                    var packet       = GenerateEmptyPacketData();                               // NOTE: length is 65 because of the first extra byte
                                    packet[1] = 0xa1;
                                    packet[2] = unchecked ((byte)(chunkCount % 2));
                                    packet[3] = unchecked ((byte)(address >> 8));
                                    packet[4] = unchecked ((byte)address);
                                    Array.Copy(data, i, packet, 5, bytesToWrite);
                                    byte checkSum = 0;
                                    for (int csi = 2; csi < 37; csi++)
                                    {
                                        checkSum = unchecked ((byte)(checkSum + packet[csi]));
                                    }
                                    packet[37] = checkSum;

                                    UsbConn.ClearPacketQueue();
                                    if (!WritePacket(packet))
                                    {
                                        progressUpdated(0, "Write failure!");
                                        result = false;
                                        break;                                         //return false;
                                    }

                                    packet = UsbConn.ReadPacket(ThreeQuarterSecond);
                                    if (null == packet || !(packet[1] == 0xa1 && packet[2] == 0x01))
                                    {
                                        checksumFails++;
                                        if (checksumFails <= (firstBlock ? 3 : maxChecksumFails))
                                        {
                                            i -= stride;
                                            continue;
                                        }
                                        progressUpdated(0, "Checksum failure.");
                                        result = false;
                                        break;
                                    }
                                    checksumFails = 0;

                                    bytesSent += bytesToWrite;
                                    if ((bytesSent - lastNoticeByte) > noticeInterval)
                                    {
                                        lastNoticeByte = bytesSent;
                                        dotCount++;
                                        if (dotCount > 3)
                                        {
                                            dotCount = 1;
                                        }
                                        progressUpdated(
                                            bytesSent / (double)(totalBytes),
                                            String.Concat("Writing", new String(Enumerable.Repeat('.', dotCount).ToArray()))
                                            );
                                    }

                                    chunkCount++;
                                }
                                firstBlock = false;
                            }
                        }
                    }
                }
                catch (Exception ex) {
                    progressUpdated(0, ex.ToString());
                    result = false;
                }
                finally {
                    var resetOk = AnemResetVersion2(nid);
                    if (!resetOk)
                    {
                        progressUpdated(0, "Anem reboot failure.");
                    }
                    result &= resetOk;
                }
                return(result);
            }
        }
Exemplo n.º 19
0
 /// <summary>
 /// Forces a connection if possible.
 /// </summary>
 /// <returns></returns>
 public bool Connect()
 {
     return(null != UsbConn && UsbConn.Connect());
 }
Exemplo n.º 20
0
 private bool WritePacket(byte[] packet)
 {
     return(null != UsbConn && UsbConn.WritePacket(packet));
 }