Beispiel #1
0
    public void thread()
    {
        CanPacket cp = null;
        while (running) {
            Thread.Sleep(1);
            bool hasMessage = sc.getPacket(out cp);
            if (hasMessage) {
                tcps.sendCanPacket(cp);

                if (DEBUG_LEVEL>2) { Console.WriteLine(">"+cp.toRawString()); }
            }

            string tcpdata;
            bool hasData = tcps.getData(out tcpdata);
            if (hasData) {
                if (tcpdata.Length>3) {
                    //string canraw = tcpdata.Substring(4);
                    cp = new CanPacket(tcpdata.Substring(4));
                    //cp.setData(tcpdata.Substring(4));
                    if (sc.writePacket(cp)) {
                        if (DEBUG_LEVEL>2) { Console.WriteLine("<"+cp.toRawString()); }
                    }
                }
            }
        }
    }
Beispiel #2
0
        public void TestPacket2()
        {
            CanPacket canPacket = new CanPacket((int)0x505)
            {
                RawBytesString = "005472697469756d008e0ea8c00047eb0000040400080020000000100000"
            };

            Assert.IsFalse(canPacket.Extended);
            Assert.AreEqual(canPacket.Flags, "");

            canPacket.RawBytesString = "005472697469756d008e0ea8c00047eb0000040401080020000000100000";
            Assert.IsTrue(canPacket.Extended);
            Assert.IsFalse(canPacket.Rtr);
            Assert.AreEqual(canPacket.Flags, "E");

            canPacket.RawBytesString = "005472697469756d008e0ea8c00047eb0000040403000000000000000000";
            Assert.IsTrue(canPacket.Extended);
            Assert.IsTrue(canPacket.Rtr);
            Assert.AreEqual(canPacket.Flags, "ER");

            canPacket.RawBytesString = "005472697469756d008e0ea8c00047eb0000040402000000000000000000";
            Assert.IsFalse(canPacket.Extended);
            Assert.IsTrue(canPacket.Rtr);
            Assert.AreEqual(canPacket.Flags, "R");
        }
Beispiel #3
0
        public static void TestUInt16(CanPacket canPacket)
        {
            if (canPacket == null)
            {
                canPacket = new CanPacket((int)0x1806E5F4ul);
            }
            canPacket.SetUint16(0, 32760);
            Assert.AreEqual(canPacket.GetUint16(0), (uint)32760);

            Boolean gotException = false;

            try
            {
                canPacket.SetUint16(4, 321);
            }
            catch (IndexOutOfRangeException)
            {
                gotException = true;
            }

            Assert.IsTrue(gotException);

            gotException = false;

            try
            {
                canPacket.GetUint16(4);
            }
            catch (IndexOutOfRangeException)
            {
                gotException = true;
            }

            Assert.IsTrue(gotException);
        }
Beispiel #4
0
        private void timerTick(object sender, EventArgs e)
        {
            if (!this.isNewPacket)
            {
                return;
            }

            CanPacket[] canPacketListCopy = new CanPacket[canPacketList.Count];

            try
            {
                this.canPacketList.CopyTo(canPacketListCopy, 0);
                canPacketList.Clear();
            }
            catch {
                canPacketList.Clear();
            }


            foreach (CanPacket cp in canPacketListCopy)
            {
                recieveCan(cp);
            }

            this.isNewPacket = false;
        }
Beispiel #5
0
        public void StartStopChargeTest()
        {
            CanService.Instance.ConnectViaLoopBack();
            Assert.IsTrue(CanService.Instance.IsConnected());

            ElconService elconService = ElconService.Instance;

            elconService.SupplyVoltageLimit = 230;
            elconService.SupplyCurrentLimit = 10;

            elconService.StartCharge();

            CanPacket statusPacket = new CanPacket(ElconService.ELCON_CAN_STATUS)
            {
                IsLittleEndian = false
            };

            statusPacket.SetUint16(0, (uint)1600);
            statusPacket.SetUint16(1, (uint)100);
            CanService.Instance.SendMessage(statusPacket);
            Assert.IsTrue(elconService.IsCharging);

            elconService.StopCharge();
            Assert.IsFalse(elconService.IsCharging);

            CanPacket canPacket = CanService.Instance.LastestCanPacketById(ElconService.ELCON_CAN_COMMAND);

            // Update voltage requested to 0
            Assert.AreEqual(canPacket.Int16Pos3, 0);
            Assert.AreEqual(canPacket.Int16Pos2, 0);

            CanService.Instance.Disconnect();
            Assert.IsFalse(CanService.Instance.IsConnected());
        }
Beispiel #6
0
        public override void CanPacketReceived(CanPacket canPacket)
        {
            try
            {
                if (isRecording)
                {
                    string newLine = "";
                    packetNumber++;

                    newLine = newLine + MyExtensions.AlignLeft(DateTime.Now.ToString("HH:mm:ss.fff"), 14, false);
                    newLine = newLine + MyExtensions.AlignLeft(packetNumber.ToString(), 12, true);
                    newLine = newLine + MyExtensions.AlignLeft("0x" + canPacket.CanIdAsHex, 12, true);
                    newLine = newLine + MyExtensions.AlignLeft(canPacket.Flags, 7, true);

                    byte[] dataBytes = canPacket.DataBytes;
                    Array.Reverse(dataBytes, 0, dataBytes.Length);

                    newLine = newLine + MyExtensions.AlignLeft("0x" + MyExtensions.ByteArrayToString(dataBytes), 20, true);
                    newLine = newLine + MyExtensions.AlignLeft(canPacket.Float1.ToString(), 15, true);
                    newLine = newLine + MyExtensions.AlignLeft(canPacket.Float0.ToString(), 15, true);
                    newLine = newLine + MyExtensions.AlignLeft(canPacket.SourceIPAddress.ToString(), 7, true);

                    recordStream.WriteLine(newLine);

                    recordStatus = "Recording Can Packet No : " + packetNumber;
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.StackTrace);
            }
        }
 private void ReceivedCanPacketCallBack(CanPacket canPacket)
 {
     if (canPacket.CanId == TEST_CAN_ID)
     {
         receivedIt = true;
     }
 }
Beispiel #8
0
        public async Task <bool> EngageContactors()
        {
            CanPacket ControlPacket505 = new CanPacket(0x505); // 0x505

            ControlPacket505.SetInt8(0, 0);
            CanService.Instance.SetCanToSendAt10Hertz(ControlPacket505);

            await Task.Delay(500);

            ControlPacket505.SetInt8(0, 112);
            CanService.Instance.SetCanToSendAt10Hertz(ControlPacket505);

            await Task.Delay(500);

            await WaitUntilBMUPrechargeStateEquals(BMU.PRECHARGE_STATUS_IDLE, 5000);

            // Set up the heartbeat for the battery so that we are ready to go
            CanPacket ControlPacket500 = new CanPacket(0x500); // 0x500

            CanService.Instance.SetCanToSendAt10Hertz(ControlPacket500);

            await WaitUntilContactorsEngage(5000);

            return(true);
        }
Beispiel #9
0
        public void TestByte()
        {
            CanPacket canPacket = new CanPacket((int)0x1806E5F4ul);

            canPacket.SetByte(0, 1);
            Assert.AreEqual(canPacket.GetByte(0), 1);
            canPacket.SetByte(0, 12);
            Assert.AreEqual(canPacket.GetByte(0), 12);

            Boolean gotException = false;

            try
            {
                canPacket.SetByte(8, 12);
            }
            catch
            {
                gotException = true;
            }

            Assert.IsTrue(gotException);

            gotException = false;

            try
            {
                canPacket.GetByte(8);
            }
            catch
            {
                gotException = true;
            }

            Assert.IsTrue(gotException);
        }
Beispiel #10
0
        public void TestUInt32(CanPacket canPacket)
        {
            if (canPacket == null)
            {
                canPacket = new CanPacket((int)0x1806E5F4ul);
            }
            canPacket.SetUint32(0, 2147483);
            Assert.AreEqual(canPacket.GetUint32(0), (uint)2147483);

            Boolean gotException = false;

            try
            {
                canPacket.SetUint32(4, 321);
            }
            catch
            {
                gotException = true;
            }

            Assert.IsTrue(gotException);

            gotException = false;

            try
            {
                canPacket.GetUint32(4);
            }
            catch
            {
                gotException = true;
            }

            Assert.IsTrue(gotException);
        }
Beispiel #11
0
        public static List <CanPacket> UnknownCanIds(Bus bus)
        {
            if (bus == null)
            {
                throw new ArgumentNullException(nameof(bus));
            }

            List <CanPacket> unknownPackets = null;

            Dictionary <String, Configuration.Message> messages = new Dictionary <String, Configuration.Message>();

            foreach (Configuration.Message message in bus.Message)
            {
                if (message.id != null)
                {
                    messages.Add(message.id, message);
                }
            }

            foreach (DictionaryEntry pair in CanService.Instance.LatestCanPacket)
            {
                CanPacket canPacket = (CanPacket)pair.Value;

                if (!messages.ContainsKey(canPacket.CanIdAsHex))
                {
                    if (unknownPackets == null)
                    {
                        unknownPackets = new List <CanPacket>();
                    }
                    unknownPackets.Add(canPacket);
                }
            }

            return(unknownPackets);
        }
Beispiel #12
0
        private void EngageContactors(Battery battery)
        {
            CanPacket bmuOneEngaged = new CanPacket(0x6F7);

            bmuOneEngaged.SetUint8(1, BMU.PRECHARGE_STATUS_RUN);
            bmuOneEngaged.SetUint8(0, 0x04);

            CanPacket bmuTwoEngaged = new CanPacket(0x2F7);

            bmuTwoEngaged.SetUint8(1, BMU.PRECHARGE_STATUS_RUN);
            bmuTwoEngaged.SetUint8(0, 0x04);

            CanPacket bmuOneES = new CanPacket(0x6FD);

            bmuOneES.SetUint32(0, 0x00000080);

            CanPacket bmuTwoES = new CanPacket(0x2FD);

            bmuTwoES.SetUint32(0, 0x00000080);

            if (battery.GetBMU(0) != null)
            {
                battery.GetBMU(0).CanPacketReceived(bmuOneEngaged);
                battery.GetBMU(0).CanPacketReceived(bmuOneES);
            }

            if (battery.GetBMU(1) != null)
            {
                battery.GetBMU(1).CanPacketReceived(bmuTwoEngaged);
                battery.GetBMU(1).CanPacketReceived(bmuTwoES);
            }
        }
Beispiel #13
0
        private void TimerTick(object sender, EventArgs e)
        {
            lock (timerLock)
            {
                if (!this.isNewPacket)
                {
                    return;
                }

                CanPacket[] canPacketListCopy = new CanPacket[canPacketList.Count];

                try
                {
                    this.canPacketList.GetRange(0, canPacketListCopy.Length).CopyTo(canPacketListCopy, 0);
                    canPacketList.Clear();
                }
                catch
                {
                    canPacketList.Clear();
                }

                foreach (CanPacket cp in canPacketListCopy)
                {
                    if (cp != null)
                    {
                        ReceiveCan(cp);
                    }
                }

                this.isNewPacket = false;
            }
        }
Beispiel #14
0
        private void SendBatteryHeartBeat(CanService canService, Battery battery)
        {
            CanPacket bmuOne = new CanPacket(0x600);
            CanPacket bmuTwo = new CanPacket(0x200);

            CanPacket cmuOne = new CanPacket(0x601);
            CanPacket cmuTwo = new CanPacket(0x201);

            canService.SendMessage(bmuOne);
            canService.SendMessage(bmuTwo);

            canService.SendMessage(cmuOne);
            canService.SendMessage(cmuTwo);

            if (battery.GetBMU(0) != null)
            {
                battery.GetBMU(0).CanPacketReceived(bmuOne);
            }
            if (battery.GetBMU(1) != null)
            {
                battery.GetBMU(1).CanPacketReceived(bmuTwo);
            }

            if (battery.GetBMU(0) != null)
            {
                battery.GetBMU(0).GetCMU(0).CanPacketReceived(cmuOne);
            }
            if (battery.GetBMU(1) != null)
            {
                battery.GetBMU(1).GetCMU(0).CanPacketReceived(cmuTwo);
            }
        }
 public void StopSendingCanAt10Hertz(CanPacket canPacket)
 {
     if (canPacket == null)
     {
         throw new ArgumentNullException(nameof(canPacket));
     }
     StopSendingCanAt10Hertz(canPacket.CanId);
 }
        private void packetRecieved(UdpRecievedEventArgs e)
        {
            CanPacket cp = e.Message;

            this.canPacketList.Add(e.Message);

            this.isNewPacket = true;
        }
Beispiel #17
0
        public void TestByteStringBigEndian()
        {
            CanPacket canPacket = new CanPacket((int)0x505)
            {
                IsLittleEndian = false
            };

            TestByteString(canPacket);
        }
Beispiel #18
0
 private void ReceivedCanPacketCallBack(CanPacket canPacket)
 {
     CanQueue.Enqueue(canPacket);
     if (LatestCanPacket.ContainsKey(canPacket.CanId))
     {
         LatestCanPacket.Remove(canPacket.CanId);
     }
     LatestCanPacket.Add(canPacket.CanId, canPacket);
 }
Beispiel #19
0
        public void TestCanIdChange()
        {
            CanPacket canPacket = new CanPacket(0x500)
            {
                CanId = 0x505
            };

            Assert.AreEqual(canPacket.CanIdAsHex.ToString(), "0x505");
        }
Beispiel #20
0
        public void TestFloatBigEndian()
        {
            CanPacket canPacket = new CanPacket((int)0x505)
            {
                IsLittleEndian = false
            };

            TestFloat(canPacket);
        }
Beispiel #21
0
        public void ShutdownService()
        {
            CanPacket ControlPacket505 = new CanPacket(0x505); // 0x505
            CanPacket ControlPacket500 = new CanPacket(0x500); // 0x500

            // Set up the heartbeat for the battery so that we are ready to go
            CanService.Instance.StopSendingCanAt10Hertz(ControlPacket505);
            CanService.Instance.StopSendingCanAt10Hertz(ControlPacket500);
        }
        public void DisengageContactor()
        {
            contactorUpdateTimer.Stop();

            CanPacket canPacket = new CanPacket(0x508);

            canPacket.SetByte(7, 0x0);
            canControl.ComponentCanService.SetCanToSendAt10Hertz(canPacket);
        }
 public bool getData(out CanPacket cp)
 {
     cp = null;
     if (canPackets.Count>0) {
         cp = (CanPacket)canPackets.Dequeue();
         return true;
     }
     return false;
 }
Beispiel #24
0
        public override void CanPacketReceived(CanPacket cp)
        {
            // Elcon uses big endian
            cp.IsLittleEndian = false;

            Boolean gotStatusMessage = false;

            try
            {
                switch (cp.CanIdBase10)
                {
                case ELCON_CAN_STATUS:     // 0x18FF50E5
                    ActualVoltage = (float)cp.GetUint16(0) / 10.0f;
                    ActualCurrent = (float)cp.GetUint16(1) / 10.0f;

                    // Calculate and send updated dynamic current limit based on pack voltage
                    if (ActualVoltage > 0.0f)
                    {
                        ChargerCurrentLimit = ChargerPowerLimit / ActualVoltage;

                        if (ChargerCurrentLimit > ELCON_CURRENT_LIMIT)
                        {
                            ChargerCurrentLimit = ELCON_CURRENT_LIMIT;
                        }
                    }

                    // Get status flags
                    ChargerStatus    = cp.GetUint8(4);
                    gotStatusMessage = true;
                    break;
                }
            }
            catch
            {
                //Let it go, let it go. Can't hold it back anymore...
            }

            if (chargeOutputOn && gotStatusMessage)
            {
                // We use the receipt of the status message to send the charger the latest power details
                CanPacket elconCommand = new CanPacket(ELCON_CAN_COMMAND)
                {
                    IsLittleEndian = false
                };

                // Update voltage requested by the ChargeService
                elconCommand.SetUint16(0, (UInt16)(RequestedVoltage * 10));

                // Update current requested by the ChargeService
                elconCommand.SetUint16(1, (UInt16)(RequestedCurrent * 10));

                ComponentCanService.SendMessage(elconCommand);
            }

            UpdateStatus();
        }
        public Boolean IsDischargeContactorsEngaged()
        {
            CanPacket contactorStatus = canControl.ComponentCanService.LastestCanPacketById(0x302);

            if (contactorStatus == null)
            {
                return(false);
            }
            return(contactorStatus.Byte1 == 0x30 && contactorStatus.MilisecondsSinceReceived < TIME_VALID);
        }
Beispiel #26
0
        public async void DisengageContactors()
        {
            CanPacket ControlPacket505 = new CanPacket(0x505); // 0x505
            CanPacket ControlPacket500 = new CanPacket(0x500); // 0x500

            ControlPacket505.SetInt8(0, 2);
            CanService.Instance.SetCanToSendAt10Hertz(ControlPacket505);

            await WaitUntilContactorsDisengage(5000);
        }
Beispiel #27
0
        public bool IsPacketCurrent(uint canId, uint milliseconds)
        {
            CanPacket canPacket = LastestCanPacketById(canId);

            if (canPacket == null)
            {
                return(false);
            }

            return(canPacket.MilisecondsSinceReceived <= milliseconds);
        }
Beispiel #28
0
        public void TestExtended()
        {
            CanPacket canPacket = new CanPacket((int)0x1806E5F4ul)
            {
                Extended = true
            };

            Assert.AreEqual(canPacket.Extended, true);
            canPacket.Extended = false;
            Assert.AreEqual(canPacket.Extended, false);
        }
Beispiel #29
0
        public void TestRtr()
        {
            CanPacket canPacket = new CanPacket((int)0x1806E5F4ul)
            {
                Rtr = true
            };

            Assert.AreEqual(canPacket.Rtr, true);
            canPacket.Rtr = false;
            Assert.AreEqual(canPacket.Rtr, false);
        }
 public bool getPacket(out CanPacket cp)
 {
     queueMutex.WaitOne();
     cp = null;
     bool had = false;
     if (cpq.Count > 0)
     {
         cp = cpq.Dequeue();
         had = true;
     }
     queueMutex.ReleaseMutex();
     return had;
 }
Beispiel #31
0
        public void SetCanToSendAt10Hertz(CanPacket canPacket)
        {
            if (canOn10Hertz.ContainsKey(canPacket.CanId))
            {
                canOn10Hertz.Remove(canPacket.CanId);
            }

            canOn10Hertz.Add(canPacket.CanId, canPacket);

            if (sendImmediateMode)
            {
                CanSenderLoopInner();
                CanUpdateLoopInner();
            }
        }
    public void sendCanPacket(CanPacket cp)
    {
        if (running) {
            try {
                byte[] data = new byte[1024];

                data = Encoding.ASCII.GetBytes(cp.toRawString()+"\n");
                ns.Write(data, 0, data.Length);
            }
            catch (Exception) {
                Console.WriteLine("Unknown error occured when trying to send data to host");
                running = false;
            }
        }
    }
Beispiel #33
0
        public void TestCanIdBase10Change()
        {
            CanPacket canPacket = new CanPacket(0x500)
            {
                CanIdBase10 = 1285
            };

            Assert.AreEqual(canPacket.CanIdAsHex.ToString(), "0x505");

            canPacket.CanId = 0x600;
            Assert.AreEqual(canPacket.CanIdAsHex.ToString(), "0x600");

            canPacket.CanIdBase10 = 1285;
            Assert.AreEqual(canPacket.CanIdAsHex.ToString(), "0x505");
        }
Beispiel #34
0
        public SendPacketForm()
        {
            InitializeComponent();

            this.looping = false;

            this.btnReset.Enabled   = !looping;
            this.btnLoop.Enabled    = !looping;
            this.btnSend.Enabled    = !looping;
            this.tbLoopRate.Enabled = !looping;

            this.canPacket = new CanPacket(samplePacket);

            UpdateInputFields();
        }
    public bool writePacket(CanPacket cp)
    {
        if (serial_conn != null) {
            if (serial_conn.IsOpen) {
                byte[] bytes = new byte[PACKET_LENGTH];
                Array.Copy(cp.getBytes(), 0, bytes, 1, PACKET_LENGTH - 2);
                bytes[0] = UART_START_BYTE;
                bytes[PACKET_LENGTH - 1] = UART_END_BYTE;
                serial_conn.Write(bytes, 0, PACKET_LENGTH);
                return true;
            }
            return false;
        } else if (udpserver != null) {
            byte[] bytes = new byte[PACKET_LENGTH];
            Array.Copy(cp.getBytes(), 0, bytes, 1, PACKET_LENGTH - 2);
            bytes[0] = UART_START_BYTE;
            bytes[PACKET_LENGTH - 1] = UART_END_BYTE;

            udpserver.SendTo(bytes, bytes.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse(remoteIP), remotePort));
            return true;
        } else {
            return false;
        }
    }
Beispiel #36
0
 public bool isBiosStart(CanPacket cp, byte sender)
 {
     bool returnval = false;
     uint id = cp.getId();
     if ((id&0x00FF0000) == (CAN_NMT_BIOS_START<<16) && (id&0x0000FF00) == (sender<<8)) {
         returnval = true;
         byte[] data = cp.getData();
         string appinfo = "Application installed";
         if (data[2] == 0) {
             appinfo = "No application installed";
         }
         Console.WriteLine("Bios started on node 0x" + String.Format("{0:x2}", sender) +
                             ", bios version 0x" + String.Format("{0:x2}", data[1]) + String.Format("{0:x2}", data[0]) +
                             ", " + appinfo
                             );
     }
     return returnval;
 }
Beispiel #37
0
        public Boolean learn(Byte[] buffer)
        {
            if (buffer[0] != 0x03)
            {
                showMessageBox("Invalid packet detected.");
                return false;
            }

            if (learnedPackets == null) { learnedPackets = new HashSet<CanPacket>(); }

            UInt32 time = epoch();
            if (time > learnStart + 60)
            {
                learning = false;
                SetBusLogEnabled(false);
                showMessageBox("Learning complete with " + learnedPackets.Count.ToString() + " unique packets");
                return false;
            }

            updateStatusLabel("Learning (" + (time - learnStart).ToString() + " seconds elapsed)");

            CanPacket packet = new CanPacket(buffer);
            learnedPackets.Add(packet);

            return true;
        }
Beispiel #38
0
 public bool isBiosStart(CanPacket cp, byte sender, uint hwid)
 {
     bool returnval = false;
     uint id = cp.getId();
     if (HWID_INUSE) {
         byte[] data = cp.getData();
         if ((id&0x00FF0000) == (CAN_NMT_BIOS_START<<16) && data[4]==((hwid)&0xff) && data[5]==((hwid>>8)&0xff) && data[6]==((hwid>>16)&0xff) && data[7]==((hwid>>24)&0xff)) {
             returnval = true;
             string appinfo = "application installed";
             if (data[2] == 0) {
                 appinfo = "no application installed";
             }
             if (data[3]==0) {
                appinfo += ", device type unkown";
             }
             if (data[3]!=0) {
                 switch(data[3]){
                     case DEVICETYPE_AVR_ATmega8:
                         appinfo += ", device type ATmega8";
                         break;
                     case DEVICETYPE_AVR_ATmega48:
                         appinfo += ", device type ATmega48";
                         break;
                     case DEVICETYPE_AVR_ATmega88:
                         appinfo += ", device type ATmega88";
                         break;
                     case DEVICETYPE_AVR_ATmega168:
                         appinfo += ", device type ATmega168";
                         break;
                     case DEVICETYPE_AVR_ATmega328:
                         appinfo += ", device type ATmega328";
                         break;
                     default:
                         appinfo += ", device type unknown";
                         break;
                 }
             }
             Console.WriteLine("Bios started on node 0x" + String.Format("{0:x2}", sender) +
                                 ", bios version 0x" + String.Format("{0:x2}", data[1]) + String.Format("{0:x2}", data[0]) +
                                 ", " + appinfo
                                 );
         }
     } else {
         if ((id&0x00FF0000) == (CAN_NMT_BIOS_START<<16) && (id&0x0000FF00) == (sender<<8)) {
             returnval = true;
             byte[] data = cp.getData();
             string appinfo = "Application installed";
             if (data[2] == 0) {
                 appinfo = "No application installed";
             }
             Console.WriteLine("Bios started on node 0x" + String.Format("{0:x2}", sender) +
                                 ", bios version 0x" + String.Format("{0:x2}", data[1]) + String.Format("{0:x2}", data[0]) +
                                 ", " + appinfo
                                 );
         }
     }
     return returnval;
 }
Beispiel #39
0
 public CanNMT()
 {
     cp = new CanPacket();
     cp.setExt(1);
 }
Beispiel #40
0
 public CanNMT(CanPacket cp)
 {
     this.cp = cp;
     this.cp.setExt(1);
 }
    public void thread()
    {
        byte[] data = new byte[1024];
        int recv;
        while (running) {
            Thread.Sleep(1);
            //Console.Write(".");
            if (ns.DataAvailable) {
                recv = ns.Read(data, 0, data.Length);
                if (recv == 0)
                    break;

                string tcpdata = Encoding.ASCII.GetString(data, 0, recv);
                string [] split = null;
                split = tcpdata.Split( '\n' );
                for (int i = 0; i < split.Length; i++)
                {
                    if (split[i].Trim().Length>3) {
                        CanPacket cp = new CanPacket(split[i].Trim().Substring(4));
                        canPackets.Enqueue(cp);
                        //Console.WriteLine(cp.toRawString());
                    }
                }
            }
        }

        ns.Close();
        tc.Close();
    }
 public bool writePacket(CanPacket cp)
 {
     if (serial_conn.IsOpen)
     {
         byte[] bytes = new byte[PACKET_LENGTH];
         Array.Copy(cp.getBytes(), 0, bytes, 1, PACKET_LENGTH - 2);
         bytes[0] = UART_START_BYTE;
         bytes[PACKET_LENGTH - 1] = UART_END_BYTE;
         serial_conn.Write(bytes, 0, PACKET_LENGTH);
         return true;
     }
     return false;
 }
        private void serial_conn_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            System.IO.Ports.SerialPort port = (System.IO.Ports.SerialPort)sender;
            byte[] data = new byte[port.BytesToRead];

            int bytesToRead = port.BytesToRead;

            // Fyll på array hela tiden i slutet.
            port.Read(data, 0, data.Length);
            Array.Copy(data, 0, iBuff, iBuffPointer, data.Length);
            iBuffPointer += bytesToRead;

            // När array större eller lika med PACKET_LENGTH...
            while (iBuffPointer >= PACKET_LENGTH)
            {
                int startIndex = 0;

                // Sök igenom efter start byte från början.
                for (int i = 0; i < iBuffPointer; i++)
                {
                    // Poppa alla bytes som inte är startbyte.
                    if (iBuff[i] != UART_START_BYTE) startIndex++;
                    else
                    {
                        // När startbyte hittas, kolla om återstående längd är större eller lika med PACKET_LENGTH (inkl startbyte)
                        if ((iBuffPointer - startIndex) >= PACKET_LENGTH)
                        {
                            //om så, kolla PACKET_LENGTH-1 byte fram.
                            if (iBuff[startIndex + PACKET_LENGTH - 1] == UART_END_BYTE)
                            {
                                // Om byte PACKET_LENGTH-1 är slutbyte så extraktas startIndex till slutbyteindex.
                                CanPacket cm = new CanPacket(iBuff, (uint)startIndex + 1);
                                queueMutex.WaitOne();
                                cpq.Enqueue(cm);
                                queueMutex.ReleaseMutex();
                                // Sätt ny startindex och avsluta loop.
                                startIndex += PACKET_LENGTH;
                                break;
                            }
                        }
                    }
                }
                // och i slutet göra en array copy.
                // Flytta ner allt efter slutbyte till index 0 i array.
                Array.Copy(iBuff, startIndex, iBuff, 0, iBuffPointer - PACKET_LENGTH);
                iBuffPointer -= startIndex;
            }
        }
Beispiel #44
0
 public CanNMT(bool HWID_INUSE)
 {
     cp = new CanPacket();
     cp.setExt(1);
     this.HWID_INUSE = HWID_INUSE;
 }
Beispiel #45
0
 public void sendCanPacket(CanPacket cp)
 {
     foreach (Connection client in clients) {
         client.sendData(cp);
     }
 }
Beispiel #46
0
 public CanNMT(CanPacket cp, bool HWID_INUSE)
 {
     this.cp = cp;
     this.cp.setExt(1);
     this.HWID_INUSE = HWID_INUSE;
 }
Beispiel #47
0
 public bool isBiosStart(CanPacket cp, byte sender, uint hwid)
 {
     bool returnval = false;
     uint id = cp.getId();
     if (HWID_INUSE) {
         byte[] data = cp.getData();
         if ((id&0x00FF0000) == (CAN_NMT_BIOS_START<<16) && data[4]==((hwid)&0xff) && data[5]==((hwid>>8)&0xff) && data[6]==((hwid>>16)&0xff) && data[7]==((hwid>>24)&0xff)) {
             returnval = true;
             string appinfo = "Application installed";
             if (data[2] == 0) {
                 appinfo = "No application installed";
             }
             if (data[3]!=0 && data[3]!=0xff) {
                appinfo += ", application can-id "+data[3];
             }
             Console.WriteLine("Bios started on node 0x" + String.Format("{0:x2}", sender) +
                                 ", bios version 0x" + String.Format("{0:x2}", data[1]) + String.Format("{0:x2}", data[0]) +
                                 ", " + appinfo
                                 );
         }
     } else {
         if ((id&0x00FF0000) == (CAN_NMT_BIOS_START<<16) && (id&0x0000FF00) == (sender<<8)) {
             returnval = true;
             byte[] data = cp.getData();
             string appinfo = "Application installed";
             if (data[2] == 0) {
                 appinfo = "No application installed";
             }
             Console.WriteLine("Bios started on node 0x" + String.Format("{0:x2}", sender) +
                                 ", bios version 0x" + String.Format("{0:x2}", data[1]) + String.Format("{0:x2}", data[0]) +
                                 ", " + appinfo
                                 );
         }
     }
     return returnval;
 }
Beispiel #48
0
        public void downloader()
        {
            int t = 0;
            CanPacket outCp = null;
            CanPacket cp = null;
            byte[] data = new byte[8];
            byte offset = 0;
            ulong currentAddress = 0;

            try
            {
                while (true)
                {
                    bool hasMessage = sc.getPacket(out cp);
                    if (hasMessage)
                    {
                        Array.Copy(cp.data, data, 8);
                    }
                    bool hasMessageFromTarget = (hasMessage && cp.type== td.PACKET_TYPE.ptBOOT && cp.boot.rid==MY_ID && cp.sid == TARGET_ID);

                    switch (pgs)
                    {
                        case dState.SEND_START:
                            // Send boot start packet to target.
                            // and wait for ack.
                            currentAddress = hf.getAddrLower();
                            data[2] = (byte)((currentAddress & 0xFF0000) >> 16);
                            data[1] = (byte)((currentAddress & 0xFF00) >> 8);
                            data[0] = (byte)(currentAddress & 0xFF);
                            outCp = new CanPacket(new CanPacket.canBOOTPacket(td.BOOT_TYPE.btADDR, 0, TARGET_ID), MY_ID, 3, data);

                            sc.writePacket(outCp);
                            t = Environment.TickCount;
                            pgs = dState.WAIT_ACK;
                            timeStart = Environment.TickCount;
                            hasFoundNode = false;
                            break;

                        case dState.WAIT_ACK:

                            // Check for timeout, resend start packet in that case..
                            if ((Environment.TickCount - t) > TIMEOUT_MS)
                            {
                                pgs = dState.SEND_START;
                            }

                            // If received ack.
                            if (hasMessageFromTarget && cp.boot.type == td.BOOT_TYPE.btACK)
                            {
                                // Start sending program data..
                                offset = 0;
                                pgs = dState.SEND_PGM_DATA;
                                hasFoundNode = true;
                            }
                            // if nack
                            if (hasMessageFromTarget && cp.boot.type == td.BOOT_TYPE.btNACK)
                            {
                                // else resend start..
                                pgs = dState.SEND_START;
                            }

                            break;

                        case dState.SEND_PGM_DATA:
                            // Send program data.
                            for (ulong i = 0; i < 8; i++)
                            {
                                // Populate data.
                                data[i] = hf.getByte(currentAddress + i + offset);
                            }
                            outCp = new CanPacket(new CanPacket.canBOOTPacket(td.BOOT_TYPE.btPGM, offset, TARGET_ID), MY_ID, 8, data);
                            sc.writePacket(outCp);
                            t = Environment.TickCount;
                            pgs = dState.WAIT_OWN_PACKET;
                            break;

                        case dState.WAIT_OWN_PACKET:
                            // Wait reciving own packet, if timeout, resend last.
                            if ((Environment.TickCount - t) > TIMEOUT_MS)
                            {
                                pgs = dState.SEND_PGM_DATA;
                            }

                            // If received own packet..
                            if (hasMessage && outCp.Equals(cp))
                            {
                                offset += 8;

                                // Check if 64 bytes sent or not..
                                if (offset % 64 == 0)
                                {
                                    // Yes, send crc.
                                    t = Environment.TickCount;
                                    pgs = dState.SEND_CRC;
                                }
                                else
                                {
                                    // No, send more.
                                    pgs = dState.SEND_PGM_DATA;
                                }

                            }
                            break;

                        case dState.SEND_CRC:
                            byte[] pgmData = new byte[64];
                            for(ulong i=0;i<64;i++) pgmData[i] = hf.getByte(i+currentAddress);

                            ushort crc = crc16.calc_crc(pgmData, 64);
                            data[4] = (byte)((crc & 0xFF00) >> 8);
                            data[3] = (byte)(crc & 0xFF);
                            data[2] = (byte)(((currentAddress + offset) & 0xFF0000) >> 16);
                            data[1] = (byte)(((currentAddress + offset) & 0xFF00) >> 8);
                            data[0] = (byte)((currentAddress + offset) & 0xFF);
                            outCp = new CanPacket(new CanPacket.canBOOTPacket(td.BOOT_TYPE.btCRC, offset, TARGET_ID), MY_ID, 8, data);
                            sc.writePacket(outCp);
                            t = Environment.TickCount;
                            pgs = dState.WAIT_CRC_ACK;
                            break;

                        case dState.WAIT_CRC_ACK:
                            // Check for timeout, resend start packet in that case..
                            if ((Environment.TickCount - t) > TIMEOUT_MS)
                            {
                                pgs = dState.SEND_CRC;
                            }

                            // If received ack.
                            if (hasMessageFromTarget && cp.boot.type == td.BOOT_TYPE.btACK)
                            {
                                // Start send more program data..
                                currentAddress += offset;

                                offset = 0;
                                pgs = dState.SEND_PGM_DATA;
                                hasFoundNode = true;

                                if (currentAddress > hf.getAddrUpper())
                                {
                                    // Yes, we are done, send done.
                                    pgs = dState.SEND_DONE;
                                }
                            }
                            // if nack
                            if (hasMessageFromTarget && cp.boot.type == td.BOOT_TYPE.btNACK)
                            {
                                // else resend pgm data...
                                offset = 0;
                                pgs = dState.SEND_PGM_DATA;
                            }

                            break;

                        case dState.SEND_DONE:
                            outCp = new CanPacket(new CanPacket.canBOOTPacket(td.BOOT_TYPE.btDONE, offset, TARGET_ID), MY_ID, 8, data);
                            sc.writePacket(outCp);
                            t = Environment.TickCount;
                            pgs = dState.DONE;
                            break;

                        case dState.DONE:
                            abortmode = abortMode.PROGRAM;
                            down.Abort();
                            break;

             // -------------------------------- CHANGE ID NID ------------------------------------

                        case dState.CHANGE_ID_START:
                            // Send change id packet
                            // and wait for own packet.
                            data[0] = tmp_new_id;
                            outCp = new CanPacket(new CanPacket.canBOOTPacket(td.BOOT_TYPE.btCHANGEID, 0, TARGET_ID), MY_ID, 1, data);

                            sc.writePacket(outCp);
                            t = Environment.TickCount;
                            pgs = dState.CHANGE_ID_WAIT_ACK_PACKET;
                            timeStart = Environment.TickCount;
                            break;

                        case dState.CHANGE_ID_WAIT_ACK_PACKET:
                            // Wait reciving own packet, if timeout, resend last.
                            if ((Environment.TickCount - t) > TIMEOUT_MS)
                            {
                                pgs = dState.CHANGE_ID_START;
                            }

                            if (hasMessage && cp.type == td.PACKET_TYPE.ptBOOT && cp.sid == tmp_new_id && cp.boot.type == td.BOOT_TYPE.btACK)
                            {
                                pgs = dState.CHANGE_ID_DONE;
                            }

                            break;

                        case dState.CHANGE_ID_DONE:
                            abortmode = abortMode.CHANGE_ID;
                            down.Abort();
                            break;

                    }

                    Thread.Sleep(0);
                }

            } catch(Exception)
            {
                int hfLength = 0;
                if (hf != null) hfLength = (int)hf.getLength();
                threadAbort.Invoke(this, new threadAbortEvent((int)(Environment.TickCount - timeStart), hfLength, abortmode));
            }
        }
Beispiel #49
0
        public void log(Byte[] readBuffer)
        {
            if (readBuffer[0] == 0x03)
            {
                /* successful packet read */
                CanPacket packet = new CanPacket(readBuffer);
                if (learnedPackets != null)
                {
                    /* filter out learned packets */
                    if (!learnedPackets.Contains(packet))
                    {
                        String packetString = packet.ToString();
                        updateRow(packetString);

                        /* do the log file append on the UI thread to save cpu ticks */
                        appendToLogFile(packetString);
                    }
                }
                else
                {
                    /* no learned packets so log everything */
                    String packetString = packet.ToString();
                    updateRow(packetString);

                    /* do the log file append on the UI thread to save cpu ticks */
                    appendToLogFile(packetString);
                }
            }
            else
            {
                updateStatusLabel("no");
            }
        }
    public void thread()
    {
        byte[] data = new byte[1024];
        int recv;
        while (running) {
            Thread.Sleep(1);
            //Console.Write(".");
            if (ns.DataAvailable) {
                recv = ns.Read(data, 0, data.Length);
                if (recv == 0)
                    break;

                string tcpdata = Encoding.ASCII.GetString(data, 0, recv);
                if (tcpdata.Length>3) {
                    CanPacket cp = new CanPacket(tcpdata.Substring(4));
                    canPackets.Enqueue(cp);
                    //Console.WriteLine(cp.toRawString());
                }
            }
        }

        ns.Close();
        tc.Close();
    }
    public bool getPacket(out CanPacket cp)
    {
        cp = null;
        if ((serial_conn != null) || (udpserver != null)) {

            if (serial_conn != null) {
               	int bytesToRead = serial_conn.BytesToRead;
                if (bytesToRead > 0) {
                    byte[] data = new byte[bytesToRead];

                    try {
                        serial_conn.Read(data, 0, data.Length);
                    } catch (Exception e) {
                        Console.WriteLine("Exception " + e + " occured\n");
                    }

                    Array.Copy(data, 0, iBuff, iBuffPointer, data.Length);
                    iBuffPointer += bytesToRead;
                }
            } else if (udpserver != null) {
               	int bytesToRead = udpserver.Available;
                if (udpserver.Available > 0) {
                    byte[] data = new byte[bytesToRead];
                    try {
                        EndPoint tmpRemote = (EndPoint)iep;
                        udpserver.ReceiveFrom(data, ref tmpRemote);
                    } catch (Exception e) {
                        Console.WriteLine("Exception " + e + " occured\n");
                    }

                    int bytestomove = data.Length;
                    if (bytestomove ==18) {
                        bytestomove = data.Length -1;
                    }
                    Array.Copy(data, 0, iBuff, iBuffPointer, bytestomove);
                    iBuffPointer += bytestomove;
                }

            }

            // N�r array st�rre eller lika med PACKET_LENGTH...
            while (iBuffPointer >= PACKET_LENGTH) {
                int startIndex = 0;

                // S�k igenom efter start byte fr�n b�rjan.
                for (int i = 0; i < iBuffPointer; i++) {
                    // Poppa alla bytes som inte �r startbyte.
                    if (iBuff[i] != UART_START_BYTE) startIndex++;
                    else {
                        // N�r startbyte hittas, kolla om �terst�ende l�ngd �r st�rre eller lika med PACKET_LENGTH (inkl startbyte)
                        if ((iBuffPointer - startIndex) >= PACKET_LENGTH) {
                            //om s�, kolla PACKET_LENGTH-1 byte fram.
                            if (iBuff[startIndex + PACKET_LENGTH - 1] == UART_END_BYTE) {
                                // Om byte PACKET_LENGTH-1 �r slutbyte s� extraktas startIndex till slutbyteindex.
                                CanPacket cm = new CanPacket(iBuff, (uint)startIndex + 1);
                                // S�tt ny startindex och avsluta loop.
                                startIndex += PACKET_LENGTH;
                                cp = cm;
                                // och i slutet g�ra en array copy.
                                // Flytta ner allt efter slutbyte till index 0 i array.
                                Array.Copy(iBuff, startIndex, iBuff, 0, iBuffPointer - PACKET_LENGTH);
                                iBuffPointer -= startIndex;

                                return true;
                            }
                        }
                    }
                }
                // och i slutet g�ra en array copy.
                // Flytta ner allt efter slutbyte till index 0 i array.
                Array.Copy(iBuff, startIndex, iBuff, 0, iBuffPointer - PACKET_LENGTH);
                iBuffPointer -= startIndex;
            }
            return false;

        } else {
            return false;
        }
    }
Beispiel #52
0
    public void sendData(CanPacket cp)
    {
        if (connected) {
            try {
                byte[] data = new byte[1024];

                data = Encoding.ASCII.GetBytes(cp.toRawString()+"\n");
                ns.Write(data, 0, data.Length);
            }
            catch (Exception) {
                connected = false;
            }
        }
    }