Example #1
0
        public void GotCANFrame(CANFrame frame)
        {
            byte[] tempbytes = new byte[16];

            frameCache.Add(frame);
            if (contLogging)
            {
                writeOneLogLine(frame);              //if continuous logging is on then log this frame
            }
            if (!DisplayFrames)
            {
                return;
            }

            showFrame(frame);

            if (cbAutoScroll.Checked)
            {
                dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.RowCount - 1;
            }
            //if (dataGridView1.SortOrder == SortOrder.None) Debug.Print("No sort");
            //Resort the thing if it was previously sorted.
            if (dataGridView1.SortOrder == SortOrder.Ascending)
            {
                dataGridView1.Sort(dataGridView1.SortedColumn, ListSortDirection.Ascending);
            }
            if (dataGridView1.SortOrder == SortOrder.Descending)
            {
                dataGridView1.Sort(dataGridView1.SortedColumn, ListSortDirection.Descending);
            }
        }
Example #2
0
        public void GotCANFrame(CANFrame frame)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new GotCANDelegate(GotCANFrame), frame);
            }
            else
            {

                //first of all, always try to keep track of every ID we've ever seen while this form is open
                //if we find one we haven't seen yet then add it
                //foundID is really only used as a fast way to know if the frame ID has been seen before.
                //I believe it to be faster to search than directly searching entries in the listbox
                if (!foundID.Contains(frame.ID))
                {
                    foundID.Add(frame.ID);
                    listFrameIDs.Items.Add("0x" + frame.ID.ToString("X4"));
                }
                /*
                if (frame.ID == targettedID)
                {

                }
                 * */
            }
        }
Example #3
0
        public void GotCANFrame(CANFrame frame)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new GotCANDelegate(GotCANFrame), frame);
            }
            else
            {
                //first of all, always try to keep track of every ID we've ever seen while this form is open
                //if we find one we haven't seen yet then add it
                //foundID is really only used as a fast way to know if the frame ID has been seen before.
                //I believe it to be faster to search than directly searching entries in the listbox
                if (!foundID.Contains(frame.ID))
                {
                    foundID.Add(frame.ID);
                    listFrameIDs.Items.Add("0x" + frame.ID.ToString("X4"));
                }

                /*
                 * if (frame.ID == targettedID)
                 * {
                 *
                 * }
                 * */
            }
        }
Example #4
0
/* Sample data in CRTD format
 * 1320745424.000 CXX OVMS Tesla Roadster cando2crtd converted log
 * 1320745424.000 CXX OVMS Tesla roadster log: charge.20111108.csv
 * 1320745424.002 R11 402 FA 01 C3 A0 96 00 07 01
 * 1320745424.015 R11 400 02 9E 01 80 AB 80 55 00
 * 1320745424.066 R11 400 01 01 00 00 00 00 4C 1D
 * 1320745424.105 R11 100 A4 53 46 5A 52 45 38 42
 * 1320745424.106 R11 100 A5 31 35 42 33 30 30 30
 * 1320745424.106 R11 100 A6 35 36 39
 * 1320745424.106 CEV Open charge port door
 * 1320745424.106 R11 100 9B 97 A6 31 03 15 05 06
 * 1320745424.107 R11 100 07 64
 */
        private void loadCRTDFile(string filename)
        {
            CANFrame     thisFrame;
            StreamReader logStream = new StreamReader(filename);
            string       thisLine;

            System.Globalization.NumberStyles style;

            style = System.Globalization.NumberStyles.HexNumber;

            loadedFrames = new List <CANFrame>();

            while (!logStream.EndOfStream)
            {
                thisLine = logStream.ReadLine();

                /*
                 * tokens:
                 * 0 = timestamp
                 * 1 = line type
                 * 2 = ID
                 * 3-x = The data bytes
                 */
                if (thisLine.Length > 1)
                {
                    string[] theseTokens = thisLine.Split(' ');
                    thisFrame = new CANFrame();
                    for (int c = 0; c < 8; c++)
                    {
                        thisFrame.data[c] = 0;
                    }
                    thisFrame.timestamp = (UInt64)(Double.Parse(theseTokens[0]) * 1000);
                    if (theseTokens[1] == "R11" || theseTokens[1] == "R29")
                    {
                        thisFrame.ID       = int.Parse(theseTokens[2], style);
                        thisFrame.extended = false;
                        if (theseTokens[1] == "R29")
                        {
                            thisFrame.extended = true;
                        }
                        thisFrame.bus = 0;
                        thisFrame.len = theseTokens.Length - 3;
                        for (int d = 0; d < thisFrame.len; d++)
                        {
                            if (theseTokens[3 + d] != "")
                            {
                                thisFrame.data[d] = byte.Parse(theseTokens[3 + d], style);
                            }
                            else
                            {
                                thisFrame.data[d] = 0;
                            }
                        }
                        loadedFrames.Add(thisFrame);
                    }
                }
            }
            logStream.Close();
        }
Example #5
0
        private void loadMicrochipFile(string filename)
        {
            CANFrame     thisFrame;
            bool         inComment = false;
            StreamReader logStream = new StreamReader(filename);
            string       thisLine;

            loadedFrames = new List <CANFrame>();

            while (!logStream.EndOfStream)
            {
                thisLine = logStream.ReadLine();

                if (thisLine.StartsWith("//"))
                {
                    inComment = !inComment;
                }
                else
                {
                    /*
                     * tokens:
                     * 0 = timestamp
                     * 1 = Transmission direction
                     * 2 = ID
                     * 3 = Data byte length
                     * 4-x = The data bytes
                     */
                    if (thisLine.Length > 1 && !inComment)
                    {
                        string[] theseTokens = thisLine.Split(';');
                        thisFrame           = new CANFrame();
                        thisFrame.timestamp = Utility.GetTimeMS();
                        thisFrame.ID        = Utility.ParseStringToNum(theseTokens[2]);
                        if (thisFrame.ID <= 0x7FF)
                        {
                            thisFrame.extended = false;
                        }
                        else
                        {
                            thisFrame.extended = true;
                        }
                        thisFrame.bus = 0;
                        thisFrame.len = int.Parse(theseTokens[3]);
                        for (int c = 0; c < 8; c++)
                        {
                            thisFrame.data[c] = 0;
                        }
                        for (int d = 0; d < thisFrame.len; d++)
                        {
                            thisFrame.data[d] = (byte)Utility.ParseStringToNum(theseTokens[4 + d]);
                        }
                        loadedFrames.Add(thisFrame);
                    }
                }
            }
            logStream.Close();
        }
Example #6
0
 public void GotCANFrame(CANFrame frame)
 {
     //if we are currently capturing and this frame matches the ID we'd like
     //to capture then place it into the buffer.
     if (ckCapture.Checked)
     {
         //enqueue frame
         frameCache.Add(frame);                
     }
 }
Example #7
0
 public void GotCANFrame(CANFrame frame)
 {
     //if we are currently capturing and this frame matches the ID we'd like
     //to capture then place it into the buffer.
     if (ckCapture.Checked)
     {
         //enqueue frame
         frameCache.Add(frame);
     }
 }
Example #8
0
        private void loadNativeCSVFile(string filename)
        {
            CANFrame thisFrame;
            long     temp;

            System.Globalization.NumberStyles style;

            if (ckUseHex.Checked)
            {
                style = System.Globalization.NumberStyles.HexNumber;
            }
            else
            {
                style = System.Globalization.NumberStyles.Integer;
            }

            StreamReader csvStream = null;

            csvStream = new StreamReader(filename);
            csvStream.ReadLine(); //ignore header line
            loadedFrames = new List <CANFrame>();
            while (!csvStream.EndOfStream)
            {
                string thisLine = csvStream.ReadLine();
                if (thisLine.Length > 1)
                {
                    string[] theseTokens = thisLine.Split(',');
                    thisFrame = new CANFrame();
                    if (theseTokens[0].Length > 10)
                    {
                        temp = Int64.Parse(theseTokens[0]);
                        DateTime stamp = DateTime.MinValue.AddTicks(temp);
                        thisFrame.timestamp = (UInt32)(((stamp.Hour * 3600) + (stamp.Minute * 60) + (stamp.Second) * 1000) + stamp.Millisecond);
                    }
                    else
                    {
                        thisFrame.timestamp = Utility.GetTimeMS();
                    }
                    thisFrame.ID       = int.Parse(theseTokens[1], style);
                    thisFrame.extended = bool.Parse(theseTokens[2]);
                    thisFrame.bus      = int.Parse(theseTokens[3]);
                    thisFrame.len      = int.Parse(theseTokens[4]);
                    for (int c = 0; c < 8; c++)
                    {
                        thisFrame.data[c] = 0;
                    }
                    for (int d = 0; d < thisFrame.len; d++)
                    {
                        thisFrame.data[d] = byte.Parse(theseTokens[5 + d], style);
                    }
                    loadedFrames.Add(thisFrame);
                }
            }
            csvStream.Close();
        }
        public void GotCANFrame(CANFrame frame)
        {
            int found = -1;

            for (int x = 0; x < foundID.Count; x++)
            {
                if (foundID[x].ID == frame.ID)
                {
                    found = x;
                    break;
                }
            }

            if (found == -1)
            {
                UniqueFrameData tempData = new UniqueFrameData();
                tempData.ID = frame.ID;
                tempData.referenceBitfield = bytesToUInt64(frame.data);
                tempData.staticBits        = 0xFFFFFFFFFFFFFFFF; //that'd be 64 binary 1's
                foundID.Add(tempData);
            }

            UInt64 newdata  = bytesToUInt64(frame.data);
            UInt64 bitDiffs = newdata ^ foundID[found].referenceBitfield;

            //The above XOR will cause bitDiffs to have a 1 anywhere the bits were different.
            //This would be wherever a change occurred in bits from the reference.
            //This needs to be inverted so that a 1 appears wherever the bits were the same.
            bitDiffs = ~bitDiffs;
            //Now that we've got a variable with a 1 in the bit positions that did not change
            //we can AND it with the staticBits member for the frame ID. This will cause there to be a 1
            //in this field only where 1 is currently there and in the bitDiffs variable. The
            //end result is that staticBits will only have a 1 where the bits have NEVER changed
            //in any frame we've seen. These are candidates for trying to find a switched value.
            UInt64 staticTemp = foundID[found].staticBits & bitDiffs;

            if (initialBaseline)
            {
                //Since this is the initial baseline we store the new static bits
                foundID[found].staticBits = staticTemp;
            }
            else
            {
                //initial baseline is already complete so compare the result to what is stored. See if there is a change
                if (foundID[found].staticBits != staticTemp)
                {
                }
            }
            //enqueue frame
            frameCache.Add(frame);
        }
Example #10
0
        //Displays the given frame in the data view grid.
        private void showFrame(CANFrame frame)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new showFrameDelegate(showFrame), frame);
            }
            else
            {
                StringBuilder data   = new StringBuilder();
                int           rowIdx = 0;
                //two choices - either we directly add the frame or we find the unique frame ID and update the old record
                if (cbStaticMode.Checked)
                {
                    //first try to find a match
                    bool found = false;
                    for (int x = 0; x < uniqueFrames.Count; x++)
                    {
                        if (uniqueFrames[x].ID == frame.ID)
                        {
                            found           = true;
                            rowIdx          = x;
                            uniqueFrames[x] = frame;
                        }
                    }
                    if (!found)
                    {
                        uniqueFrames.Add(frame);
                        rowIdx = dataGridView1.Rows.Add();
                    }
                }
                else
                {
                    rowIdx = dataGridView1.Rows.Add();
                }

                //In all cases use the rowIdx variable to update the proper grid row
                //time, id, ext, bus, len, data
                dataGridView1.Rows[rowIdx].Cells[0].Value = frame.timestamp.ToString();
                dataGridView1.Rows[rowIdx].Cells[1].Value = "0x" + frame.ID.ToString("X8");
                dataGridView1.Rows[rowIdx].Cells[2].Value = frame.extended.ToString();
                dataGridView1.Rows[rowIdx].Cells[3].Value = frame.bus.ToString();
                dataGridView1.Rows[rowIdx].Cells[4].Value = frame.len.ToString();
                data.Clear();
                for (int c = 0; c < frame.len; c++)
                {
                    data.Append("0x" + frame.data[c].ToString("X2"));
                    data.Append(" ");
                }
                dataGridView1.Rows[rowIdx].Cells[5].Value = data.ToString(); //Payload
            }
        }
Example #11
0
        public void GotCANFrame(CANFrame frame)
        {
            int found = -1;
            for (int x = 0; x < foundID.Count; x++)
            {
                if (foundID[x].ID == frame.ID)
                {
                    found = x;
                    break;
                }
            }

            if (found == -1)
            {
                UniqueFrameData tempData = new UniqueFrameData();
                tempData.ID = frame.ID;
                tempData.referenceBitfield = bytesToUInt64(frame.data);
                tempData.staticBits = 0xFFFFFFFFFFFFFFFF; //that'd be 64 binary 1's
                foundID.Add(tempData);   
            }

            UInt64 newdata = bytesToUInt64(frame.data);
            UInt64 bitDiffs = newdata ^ foundID[found].referenceBitfield;
            //The above XOR will cause bitDiffs to have a 1 anywhere the bits were different.
            //This would be wherever a change occurred in bits from the reference.
            //This needs to be inverted so that a 1 appears wherever the bits were the same.
            bitDiffs = ~bitDiffs;
            //Now that we've got a variable with a 1 in the bit positions that did not change
            //we can AND it with the staticBits member for the frame ID. This will cause there to be a 1
            //in this field only where 1 is currently there and in the bitDiffs variable. The
            //end result is that staticBits will only have a 1 where the bits have NEVER changed
            //in any frame we've seen. These are candidates for trying to find a switched value.
            UInt64 staticTemp = foundID[found].staticBits & bitDiffs;

            if (initialBaseline)
            {
                //Since this is the initial baseline we store the new static bits
                foundID[found].staticBits = staticTemp;
            }
            else
            {
                //initial baseline is already complete so compare the result to what is stored. See if there is a change
                if (foundID[found].staticBits != staticTemp)
                {

                }
            }
            //enqueue frame
            frameCache.Add(frame);
        }
Example #12
0
        public void GotCANFrame(CANFrame frame)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new GotCANDelegate(GotCANFrame), frame);
            }
            else
            {
                //first of all, always try to keep track of every ID we've ever seen while this form is open
                //if we find one we haven't seen yet then add it
                //foundID is really only used as a fast way to know if the frame ID has been seen before.
                //I believe it to be faster to search than directly searching entries in the listbox
                if (!foundID.Contains(frame.ID))
                {
                    foundID.Add(frame.ID);
                    listFrameIDs.Items.Add("0x" + frame.ID.ToString("X4"));
                }

                //if we are currently capturing and this frame matches the ID we'd like
                //to capture then place it into the buffer.
                if (ckCapture.Checked)
                {
                    if (frame.ID == targettedID)
                    {
                        if (frameCacheWritePos == cacheSize)
                        {
                            return;
                        }
                        //enqueue frame
                        frameCache[frameCacheWritePos++] = frame;

                        //The special significance of this if is that it fills out the frame
                        //on screen because we will be showing that frame by default according to the program
                        //so it makes sense to ensure we see it immediately.
                        if (frameCacheWritePos == 1)
                        {
                            updateDataView();
                        }
                        else
                        {
                            updateFrameCounter();
                        }
                    }
                }
            }
        }
Example #13
0
        private void writeOneLogLine(CANFrame thisFrame)
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            Byte[] bytes;
            int    temp;

            try
            {
                bytes = encoding.GetBytes(thisFrame.timestamp.ToString());
                continuousOutput.Write(bytes, 0, bytes.Length);
                continuousOutput.WriteByte(44);

                bytes = encoding.GetBytes(thisFrame.ID.ToString("X8"));
                continuousOutput.Write(bytes, 0, bytes.Length);
                continuousOutput.WriteByte(44);

                bytes = encoding.GetBytes(thisFrame.extended.ToString());
                continuousOutput.Write(bytes, 0, bytes.Length);
                continuousOutput.WriteByte(44);

                bytes = encoding.GetBytes(thisFrame.bus.ToString());
                continuousOutput.Write(bytes, 0, bytes.Length);
                continuousOutput.WriteByte(44);

                bytes = encoding.GetBytes(thisFrame.len.ToString());
                continuousOutput.Write(bytes, 0, bytes.Length);
                continuousOutput.WriteByte(44);

                for (temp = 0; temp < 8; temp++)
                {
                    bytes = encoding.GetBytes(thisFrame.data[temp].ToString("X2"));
                    continuousOutput.Write(bytes, 0, bytes.Length);
                    continuousOutput.WriteByte(44);
                }

                continuousOutput.WriteByte(13);
                continuousOutput.WriteByte(10);
            }
            catch (Exception ed)
            {
                contLogging = false; //stop trying to log on error.
                Debug.Print(ed.ToString());
            }
        }
Example #14
0
        public void SendCANFrame(CANFrame frame, int bus)
        {
            byte[]        buffer = new byte[20];
            int           c, d;
            int           ID;
            StringBuilder dbug    = new StringBuilder();
            CANFrame      myFrame = new CANFrame();

            myFrame.timestamp = Utility.GetTimeMS();

            ID = frame.ID;
            if (frame.extended)
            {
                ID |= 1 << 31;
            }

            buffer[0] = 0xF1;              //start of a command over serial
            buffer[1] = 0;                 //command ID for sending a CANBUS frame
            buffer[2] = (byte)(ID & 0xFF); //four bytes of ID LSB first
            buffer[3] = (byte)(ID >> 8);
            buffer[4] = (byte)(ID >> 16);
            buffer[5] = (byte)(ID >> 24);
            buffer[6] = (byte)(bus & 1);
            buffer[7] = (byte)frame.len;
            for (c = 0; c < frame.len; c++)
            {
                buffer[8 + c] = frame.data[c];
            }
            buffer[8 + frame.len] = 0;

            GotCANFrame(frame); //pretend we got this frame on the line so that even frames we send show up in the table
            //FrameCtl = 0

            if (isConnected)
            {
                serialPort1.Write(buffer, 0, frame.len + 9);
            }
        }
Example #15
0
        //scans over the input buffer to find full frames
        //if we find one we advance the read pointer and use this
        //to chop off the first part of the string that contains full frames. When
        //we're done we'll be left with either nothing in the buffer or just a partial
        //frame
        public void ProcessInput()
        {
            byte c;

            byte[] decbytes = new byte[16];

            c = 0;

            lock (inputBuffer)
            {
                while (1 == 1) //so long as we have some bytes to read
                {
                    if (bufferReadPointer == bufferWritePointer)
                    {
                        return;                                          //if there is nothing to do then leave
                    }
                    c = inputBuffer[bufferReadPointer];
                    bufferReadPointer++;
                    bufferReadPointer = bufferReadPointer % 2048;
                    //Debug.Print(c.ToString("X2"));
                    //Debug.Print(rx_state.ToString());
                    switch (rx_state)
                    {
                    case STATE.IDLE:
                        if (c == 0xF1)
                        {
                            rx_state = STATE.GET_COMMAND;
                        }
                        break;

                    case STATE.GET_COMMAND:
                        switch (c)
                        {
                        case 0:         //receiving a can frame
                            rx_state = STATE.BUILD_CAN_FRAME;
                            rx_step  = 0;
                            break;

                        case 1:         //we don't accept time sync commands from the firmware
                            rx_state = STATE.IDLE;
                            break;

                        case 2:         //process a return reply for digital input states.
                            rx_state = STATE.GET_DIG_INPUTS;
                            rx_step  = 0;
                            break;

                        case 3:         //process a return reply for analog inputs
                            rx_state = STATE.GET_ANALOG_INPUTS;
                            break;

                        case 4:         //we set digital outputs we don't accept replies so nothing here.
                            rx_state = STATE.IDLE;
                            break;

                        case 5:         //we set canbus specs we don't accept replies.
                            rx_state = STATE.IDLE;
                            break;
                        }
                        break;

                    case STATE.BUILD_CAN_FRAME:
                        buffer[1 + rx_step] = c;
                        switch (rx_step)
                        {
                        case 0:
                            buildFrame.timestamp = c;
                            break;

                        case 1:
                            buildFrame.timestamp |= (uint)(c << 8);
                            break;

                        case 2:
                            buildFrame.timestamp |= (uint)c << 16;
                            break;

                        case 3:
                            buildFrame.timestamp |= (uint)c << 24;
                            break;

                        case 4:
                            buildFrame.ID = c;
                            break;

                        case 5:
                            buildFrame.ID |= c << 8;
                            break;

                        case 6:
                            buildFrame.ID |= c << 16;
                            break;

                        case 7:
                            buildFrame.ID |= c << 24;
                            if ((buildFrame.ID & 1 << 31) == 1 << 31)
                            {
                                buildFrame.ID      &= 0x7FFFFFFF;
                                buildFrame.extended = true;
                            }
                            else
                            {
                                buildFrame.extended = false;
                            }
                            break;

                        case 8:
                            buildFrame.len = c & 0xF;
                            if (buildFrame.len > 8)
                            {
                                buildFrame.len = 8;
                            }
                            buildFrame.bus = (c & 0xF0) >> 4;
                            break;

                        default:
                            if (rx_step < buildFrame.len + 9)
                            {
                                buildFrame.data[rx_step - 9] = c;
                            }
                            else
                            {
                                rx_state = STATE.IDLE;
                                //this would be the checksum byte. Compute and compare.
                                //byte temp8 = c;//checksumCalc(buff, step);
                                //if (temp8 == c)
                                //{
                                onGotCANFrame(buildFrame);         //call the listeners
                                frameCount++;
                                buildFrame = new CANFrame();       //easy way to clear it out
                                //}
                            }
                            break;
                        }
                        rx_step++;
                        break;

                    case STATE.GET_ANALOG_INPUTS:     //get 9 bytes - 2 per analog input plus checksum
                        buffer[1 + rx_step] = c;
                        switch (rx_step)
                        {
                        case 0:
                            break;
                        }
                        rx_step++;
                        break;

                    case STATE.GET_DIG_INPUTS:     //get two bytes. One for digital in status and one for checksum.
                        buffer[1 + rx_step] = c;
                        switch (rx_step)
                        {
                        case 0:
                            break;

                        case 1:
                            rx_state = STATE.IDLE;
                            break;
                        }
                        rx_step++;
                        break;
                    }
                }
            }
        }
Example #16
0
        public void GotCANFrame(CANFrame frame)
        {
            byte[] tempbytes = new byte[16];

            frameCache.Add(frame);
            if (contLogging) writeOneLogLine(frame); //if continuous logging is on then log this frame

            if (!DisplayFrames) return;

            showFrame(frame);

            if (cbAutoScroll.Checked) dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.RowCount - 1;
            //if (dataGridView1.SortOrder == SortOrder.None) Debug.Print("No sort");
            //Resort the thing if it was previously sorted.
            if (dataGridView1.SortOrder == SortOrder.Ascending)
                dataGridView1.Sort(dataGridView1.SortedColumn, ListSortDirection.Ascending);
            if (dataGridView1.SortOrder == SortOrder.Descending)
                dataGridView1.Sort(dataGridView1.SortedColumn, ListSortDirection.Descending);
        }
Example #17
0
        private void loadLogFile(string filename)
        {
            CANFrame     thisFrame;
            StreamReader logStream = new StreamReader(filename);
            string       thisLine;

            System.Globalization.NumberStyles style;

            if (ckUseHex.Checked)
            {
                style = System.Globalization.NumberStyles.HexNumber;
            }
            else
            {
                style = System.Globalization.NumberStyles.Integer;
            }

            loadedFrames = new List <CANFrame>();

            while (!logStream.EndOfStream)
            {
                thisLine = logStream.ReadLine();

                if (thisLine.StartsWith("***"))
                {
                    continue;
                }

                /*
                 * tokens:
                 * 0 = timestamp
                 * 1 = Transmission direction
                 * 2 = Channel
                 * 3 = ID
                 * 4 = Type (s = standard, I believe x = extended)
                 * 5 = Data byte length
                 * 6-x = The data bytes
                 */
                if (thisLine.Length > 1)
                {
                    string[] theseTokens = thisLine.Split(' ');
                    thisFrame           = new CANFrame();
                    thisFrame.timestamp = Utility.GetTimeMS();
                    thisFrame.ID        = int.Parse(theseTokens[3].Substring(2), style);
                    if (theseTokens[4] == "s")
                    {
                        thisFrame.extended = false;
                    }
                    else
                    {
                        thisFrame.extended = true;
                    }
                    thisFrame.bus = int.Parse(theseTokens[2]) - 1;
                    thisFrame.len = int.Parse(theseTokens[5]);
                    for (int c = 0; c < 8; c++)
                    {
                        thisFrame.data[c] = 0;
                    }
                    for (int d = 0; d < thisFrame.len; d++)
                    {
                        thisFrame.data[d] = byte.Parse(theseTokens[6 + d], style);
                    }
                    loadedFrames.Add(thisFrame);
                }
            }
            logStream.Close();
        }
Example #18
0
        //Displays the given frame in the data view grid.
        private void showFrame(CANFrame frame)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new showFrameDelegate(showFrame), frame);
            }
            else
            {
                StringBuilder data = new StringBuilder();
                int rowIdx = 0;
                //two choices - either we directly add the frame or we find the unique frame ID and update the old record
                if (cbStaticMode.Checked)
                {
                    //first try to find a match
                    bool found = false;
                    for (int x = 0; x < uniqueFrames.Count; x++)
                    {
                        if (uniqueFrames[x].ID == frame.ID)
                        {
                            found = true;
                            rowIdx = x;
                            uniqueFrames[x] = frame;
                        }
                    }
                    if (!found)
                    {
                        uniqueFrames.Add(frame);
                        rowIdx = dataGridView1.Rows.Add();
                    }
                }
                else
                {
                    rowIdx = dataGridView1.Rows.Add();
                }

                //In all cases use the rowIdx variable to update the proper grid row
                //time, id, ext, bus, len, data
                dataGridView1.Rows[rowIdx].Cells[0].Value = frame.timestamp.ToString();
                dataGridView1.Rows[rowIdx].Cells[1].Value = "0x" + frame.ID.ToString("X8");
                dataGridView1.Rows[rowIdx].Cells[2].Value = frame.extended.ToString();
                dataGridView1.Rows[rowIdx].Cells[3].Value = frame.bus.ToString();
                dataGridView1.Rows[rowIdx].Cells[4].Value = frame.len.ToString();
                data.Clear();
                for (int c = 0; c < frame.len; c++)
                {
                    data.Append("0x" + frame.data[c].ToString("X2"));
                    data.Append(" ");
                }
                dataGridView1.Rows[rowIdx].Cells[5].Value = data.ToString(); //Payload                
            }
        }
Example #19
0
/* Sample data in CRTD format
1320745424.000 CXX OVMS Tesla Roadster cando2crtd converted log
1320745424.000 CXX OVMS Tesla roadster log: charge.20111108.csv
1320745424.002 R11 402 FA 01 C3 A0 96 00 07 01
1320745424.015 R11 400 02 9E 01 80 AB 80 55 00
1320745424.066 R11 400 01 01 00 00 00 00 4C 1D
1320745424.105 R11 100 A4 53 46 5A 52 45 38 42
1320745424.106 R11 100 A5 31 35 42 33 30 30 30
1320745424.106 R11 100 A6 35 36 39
1320745424.106 CEV Open charge port door
1320745424.106 R11 100 9B 97 A6 31 03 15 05 06
1320745424.107 R11 100 07 64         
*/
        private void loadCRTDFile(string filename)
        {
            CANFrame thisFrame;
            StreamReader logStream = new StreamReader(filename);
            string thisLine;
            System.Globalization.NumberStyles style;

            style = System.Globalization.NumberStyles.HexNumber;

            loadedFrames = new List<CANFrame>();

            while (!logStream.EndOfStream)
            {
                thisLine = logStream.ReadLine();

                /*
                tokens:
                0 = timestamp
                1 = line type
                2 = ID
                3-x = The data bytes
                */
                if (thisLine.Length > 1)
                {
                    string[] theseTokens = thisLine.Split(' ');
                    thisFrame = new CANFrame();
                    for (int c = 0; c < 8; c++) thisFrame.data[c] = 0;
                    thisFrame.timestamp = (UInt64)(Double.Parse(theseTokens[0]) * 1000);
                    if (theseTokens[1] == "R11" || theseTokens[1] == "R29")
                    {
                        thisFrame.ID = int.Parse(theseTokens[2], style);
                        thisFrame.extended = false;
                        if (theseTokens[1] == "R29") thisFrame.extended = true;
                        thisFrame.bus = 0;
                        thisFrame.len = theseTokens.Length - 3;
                        for (int d = 0; d < thisFrame.len; d++)
                        {
                            if (theseTokens[3 + d] != "")
                            {
                                thisFrame.data[d] = byte.Parse(theseTokens[3 + d], style);
                            }
                            else thisFrame.data[d] = 0;
                        }
                        loadedFrames.Add(thisFrame);
                    }
                }
            }
            logStream.Close();
        }
Example #20
0
 //Allows another window to cause a frame to appear as if it came into the system via a normal route.
 //Mostly just used by file loading windows to inject frames from a file
 //Could also be used by node simulators
 public void sideloadFrame(CANFrame frame)
 {
     onGotCANFrame(frame);
 }
Example #21
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            string[] theSerialPortNames = System.IO.Ports.SerialPort.GetPortNames();
            cbPortNum.Items.AddRange(theSerialPortNames);
            if (cbPortNum.Items.Count > 0)
            {
                cbPortNum.SelectedIndex = 0;
            }

            label3.Text  = "";
            label11.Text = "";
            cbCAN1Speed.SelectedIndex = 0;
            cbCAN2Speed.SelectedIndex = 0;

            //a fast background thread that does nothing but check the buffer for new data
            bufferProc.DoWork += new DoWorkEventHandler(delegate(object o, DoWorkEventArgs args)
            {
                do
                {
                    try
                    {
                        this.Invoke(new ProcessDelegate(ProcessInput));
                    }
                    catch (Exception ed)
                    {
                        Debug.Print(ed.ToString());
                    }
                    Thread.Sleep(8);
                } while (runBGThread);
            });


            //slower moving thread that displays a graph of packet levels
            trafficGraph.DoWork += new DoWorkEventHandler(delegate(object o, DoWorkEventArgs args)
            {
                byte[] buffer = new byte[1];
                int loops     = 0;
                int sizeViewX, sizeViewY;
                sizeViewX       = pbActivity.Width;
                sizeViewY       = pbActivity.Height;
                Int32[] history = new Int32[125];
                int runningTotal;
                BufferedGraphicsContext myContext;
                BufferedGraphics myBuffer;
                myContext        = BufferedGraphicsManager.Current;
                myBuffer         = myContext.Allocate(pbActivity.CreateGraphics(), pbActivity.DisplayRectangle);
                Graphics gHandle = myBuffer.Graphics;
                double sx, sy, ex, ey;
                double yScale   = 14.0;
                int highest     = 0;
                int historySpan = 5;
                Pen myPen       = new Pen(Brushes.Black);
                int secCount    = 0;

                do
                {
                    Thread.Sleep(80);
                    secCount++;
                    if (secCount >= 12)
                    {
                        secCount = 0;
                        try
                        {
                            this.Invoke(new ProcessDelegate(UpdateLabels));
                        }
                        catch (Exception ed)
                        {
                            Debug.Print(ed.ToString());
                        }
                    }
                    loops++;
                    if (loops > 20)
                    {
                        loops     = 0;
                        buffer[0] = 0x4b;
                        //if (radioSerial.Checked) serialPort1.Write(buffer, 0, 1);
                        //Debug.Print("BG Thread GO!");
                    }
                    if (loops % 6 == 0)
                    {
                        //copy all values back one.
                        for (int i = 0; i < 124; i++)
                        {
                            history[i] = history[i + 1];
                        }
                        history[124] = frameCount; //fill last entry with current frame count
                        frameCount   = 0;
                        runningTotal = 0;
                        highest      = 0;

                        for (int i = 124 - historySpan; i < 125; i++)
                        {
                            runningTotal += history[i];
                        }

                        int tempTotal = runningTotal;
                        for (int i = 123; i > 25; i--)
                        {
                            tempTotal -= history[i + 1];
                            tempTotal += history[i - historySpan];
                            if (highest < tempTotal)
                            {
                                highest = tempTotal;
                            }
                        }

                        //Debug.Print(highest.ToString());
                        if (highest < 4)
                        {
                            highest = 4;
                        }

                        sx = sizeViewX;
                        sy = sizeViewY - yScale * runningTotal;
                        gHandle.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        gHandle.Clear(Color.White);

                        double figure = 0.0f;
                        yScale        = 117 / highest;
                        float yPos;

                        //Debug.Print(highest.ToString());
                        //Debug.Print(yScale.ToString());


                        for (int ct = 1; ct < 8; ct++)
                        {
                            yPos = (float)sizeViewY - (ct / 8.0f * (float)sizeViewY);
                            gHandle.DrawLine(myPen, sizeViewX - 10, yPos, sizeViewX, yPos);
                            figure = (double)highest * (double)((double)ct / 8);
                            gHandle.DrawString(figure.ToString("F1"), System.Drawing.SystemFonts.DefaultFont, Brushes.Black, (float)sizeViewX - 35.0f, yPos - 5.0f);
                        }


                        int run2 = runningTotal;
                        for (int i = 123; i > 25; i--)
                        {
                            run2          = runningTotal;
                            runningTotal -= history[i + 1];
                            runningTotal += history[i - historySpan];
                            ex            = sizeViewX - (sizeViewX / 98.0) * (124 - i);
                            ey            = sizeViewY - yScale * (runningTotal + run2) / 2.0;
                            if (ey < 0.0)
                            {
                                ey = 0.0;
                            }
                            gHandle.DrawLine(myPen, (float)sx, (float)sy, (float)ex, (float)ey);
                            sx = ex;
                            sy = ey;
                        }
                        myBuffer.Render();
                    }
                } while (runBGThread);
            });


            onGotCANFrame += GotCANFrame;
            buildFrame     = new CANFrame();
            //Run the background threads right away so that things like
            //simulators and file loaders can still inject canbus messages without an actual
            //physical connection
            runBGThread = true;
            bufferProc.RunWorkerAsync();
            trafficGraph.RunWorkerAsync();
        }
Example #22
0
 //Allows another window to cause a frame to appear as if it came into the system via a normal route.
 //Mostly just used by file loading windows to inject frames from a file
 //Could also be used by node simulators
 public void sideloadFrame(CANFrame frame)
 {
     onGotCANFrame(frame);
 }
Example #23
0
        private void writeOneLogLine(CANFrame thisFrame)
        {
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            Byte[] bytes;
            int temp;

            try
            {

                bytes = encoding.GetBytes(thisFrame.timestamp.ToString());
                continuousOutput.Write(bytes, 0, bytes.Length);
                continuousOutput.WriteByte(44);

                bytes = encoding.GetBytes(thisFrame.ID.ToString("X8"));
                continuousOutput.Write(bytes, 0, bytes.Length);
                continuousOutput.WriteByte(44);

                bytes = encoding.GetBytes(thisFrame.extended.ToString());
                continuousOutput.Write(bytes, 0, bytes.Length);
                continuousOutput.WriteByte(44);

                bytes = encoding.GetBytes(thisFrame.bus.ToString());
                continuousOutput.Write(bytes, 0, bytes.Length);
                continuousOutput.WriteByte(44);

                bytes = encoding.GetBytes(thisFrame.len.ToString());
                continuousOutput.Write(bytes, 0, bytes.Length);
                continuousOutput.WriteByte(44);

                for (temp = 0; temp < 8; temp++)
                {
                    bytes = encoding.GetBytes(thisFrame.data[temp].ToString("X2"));
                    continuousOutput.Write(bytes, 0, bytes.Length);
                    continuousOutput.WriteByte(44);
                }

                continuousOutput.WriteByte(13);
                continuousOutput.WriteByte(10);

            }
            catch (Exception ed)
            {
                contLogging = false; //stop trying to log on error.
                Debug.Print(ed.ToString());
            }
        }
Example #24
0
        private void loadGenericCSVFile(string filename)
        {
            CANFrame thisFrame;
            long temp;

            System.Globalization.NumberStyles style;

            if (ckUseHex.Checked) style = System.Globalization.NumberStyles.HexNumber;
            else style = System.Globalization.NumberStyles.Integer;

            StreamReader csvStream = new StreamReader(filename);

            loadedFrames = new List<CANFrame>();
            while (!csvStream.EndOfStream)
            {
                string thisLine = csvStream.ReadLine();
                if (thisLine.Length > 1)
                {
                    string[] theseTokens = thisLine.Split(',');
                    thisFrame = new CANFrame();
                    if (theseTokens.Length > 1)
                    {
                        thisFrame.timestamp = Utility.GetTimeMS();
                        thisFrame.ID = int.Parse(theseTokens[0], style);
                        if (thisFrame.ID > 0x7FF) thisFrame.extended = true;
                        else thisFrame.extended = false;
                        thisFrame.bus = 0;

                        string[] dataBytes = theseTokens[1].Split(' ');
                        thisFrame.len = dataBytes.Length;
                        if (thisFrame.len > 8) thisFrame.len = 8;
                        for (int c = 0; c < 8; c++) thisFrame.data[c] = 0;
                        for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = byte.Parse(dataBytes[d], style);

                        loadedFrames.Add(thisFrame);
                    }
                }
            }
            csvStream.Close();
        }
Example #25
0
        /// <summary>
        /// Event callback for reception of canbus frames
        /// </summary>
        /// <param name="frame">The frame that came in</param>
        public void GotCANFrame(CANFrame frame)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new GotCANDelegate(GotCANFrame), frame);
            }
            else
            {
                //search list of frames and add if no frame with this ID is found
                //or update if one was found.
                bool found = false;
                for (int a = 0; a < frames.Count; a++)
                {
                    if ((frame.ID == frames[a].ID) && (frame.bus == frames[a].bus))
                    {
                        found          = true;
                        frames[a].len  = frame.len;
                        frames[a].data = frame.data;
                    }
                }
                if (!found)
                {
                    frames.Add(frame);
                }

                //now that frame cache has been updated, try to see if this incoming frame
                //satisfies any triggers

                for (int b = 0; b < sendingData.Count; b++)
                {
                    for (int c = 0; c < sendingData[b].triggers.Length; c++)
                    {
                        Trigger thisTrigger = sendingData[b].triggers[c];
                        if (thisTrigger.ID > 0)
                        {
                            if ((thisTrigger.bus == frame.bus) || (thisTrigger.bus == -1))
                            {
                                if (thisTrigger.ID == frame.ID)
                                {
                                    //seems to match this trigger.
                                    if (thisTrigger.currCount < thisTrigger.maxCount)
                                    {
                                        if (thisTrigger.milliseconds == 0) //don't want to time the frame, send it right away
                                        {
                                            sendingData[b].triggers[c].currCount++;
                                            sendingData[b].count++;
                                            doModifiers(b);
                                            updateGridRow(b);
                                            parent.SendCANFrame(sendingData[b], sendingData[b].bus);
                                        }
                                        else //instead of immediate sending we start the timer
                                        {
                                            sendingData[b].triggers[c].readyCount = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Example #26
0
        private void loadMicrochipFile(string filename)
        {
            CANFrame thisFrame;
            bool inComment = false;
            StreamReader logStream = new StreamReader(filename);
            string thisLine;

            loadedFrames = new List<CANFrame>();

            while (!logStream.EndOfStream)
            {
                thisLine = logStream.ReadLine();

                if (thisLine.StartsWith("//"))
                {
                    inComment = !inComment;
                }
                else
                {

                    /*
                    tokens:
                    0 = timestamp
                    1 = Transmission direction
                    2 = ID
                    3 = Data byte length
                    4-x = The data bytes
                    */
                    if (thisLine.Length > 1 && !inComment)
                    {
                        string[] theseTokens = thisLine.Split(';');
                        thisFrame = new CANFrame();
                        thisFrame.timestamp = Utility.GetTimeMS();
                        thisFrame.ID = Utility.ParseStringToNum(theseTokens[2]);
                        if (thisFrame.ID <= 0x7FF) thisFrame.extended = false;
                        else thisFrame.extended = true;
                        thisFrame.bus = 0;
                        thisFrame.len = int.Parse(theseTokens[3]);
                        for (int c = 0; c < 8; c++) thisFrame.data[c] = 0;
                        for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = (byte)Utility.ParseStringToNum(theseTokens[4 + d]);
                        loadedFrames.Add(thisFrame);
                    }
                }
            }
            logStream.Close();
        }
Example #27
0
        private void loadNativeCSVFile(string filename)
        {
            CANFrame thisFrame;
            long temp;

            System.Globalization.NumberStyles style;

            if (ckUseHex.Checked) style = System.Globalization.NumberStyles.HexNumber;
            else style = System.Globalization.NumberStyles.Integer;

            StreamReader csvStream = null;

            csvStream = new StreamReader(filename);
            csvStream.ReadLine(); //ignore header line
            loadedFrames = new List<CANFrame>();
            while (!csvStream.EndOfStream)
            {
                string thisLine = csvStream.ReadLine();
                if (thisLine.Length > 1)
                {
                    string[] theseTokens = thisLine.Split(',');
                    thisFrame = new CANFrame();
                    if (theseTokens[0].Length > 10)
                    {
                        temp = Int64.Parse(theseTokens[0]);
                        DateTime stamp = DateTime.MinValue.AddTicks(temp);
                        thisFrame.timestamp = (UInt32)(((stamp.Hour * 3600) + (stamp.Minute * 60) + (stamp.Second) * 1000) + stamp.Millisecond);
                    }
                    else
                    {
                        thisFrame.timestamp = Utility.GetTimeMS();
                    }
                    thisFrame.ID = int.Parse(theseTokens[1], style);
                    thisFrame.extended = bool.Parse(theseTokens[2]);
                    thisFrame.bus = int.Parse(theseTokens[3]);
                    thisFrame.len = int.Parse(theseTokens[4]);
                    for (int c = 0; c < 8; c++) thisFrame.data[c] = 0;
                    for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = byte.Parse(theseTokens[5 + d], style);
                    loadedFrames.Add(thisFrame);
                }
            }
            csvStream.Close();
        }
Example #28
0
        //scans over the input buffer to find full frames
        //if we find one we advance the read pointer and use this
        //to chop off the first part of the string that contains full frames. When
        //we're done we'll be left with either nothing in the buffer or just a partial
        //frame
        public void ProcessInput()
        {
            byte c;
            byte[] decbytes = new byte[16];
            
            c = 0;

            lock (inputBuffer)
            {

                while (1 == 1) //so long as we have some bytes to read
                {
                    
                    if (bufferReadPointer == bufferWritePointer) return; //if there is nothing to do then leave

                    c = inputBuffer[bufferReadPointer];
                    bufferReadPointer++;
                    bufferReadPointer = bufferReadPointer % 2048;
                    //Debug.Print(c.ToString("X2"));
                    //Debug.Print(rx_state.ToString());
                    switch (rx_state)
                    {
                        case STATE.IDLE:
                            if (c == 0xF1) rx_state = STATE.GET_COMMAND;
                            break;
                        case STATE.GET_COMMAND:
                            switch (c)
                            {
                                case 0: //receiving a can frame
                                    rx_state = STATE.BUILD_CAN_FRAME;
                                    rx_step = 0;
                                    break;
                                case 1: //we don't accept time sync commands from the firmware
                                    rx_state = STATE.IDLE;
                                    break;
                                case 2: //process a return reply for digital input states.
                                    rx_state = STATE.GET_DIG_INPUTS;
                                    rx_step = 0;
                                    break;
                                case 3: //process a return reply for analog inputs
                                    rx_state = STATE.GET_ANALOG_INPUTS;
                                    break;
                                case 4: //we set digital outputs we don't accept replies so nothing here.
                                    rx_state = STATE.IDLE;
                                    break;
                                case 5: //we set canbus specs we don't accept replies.
                                    rx_state = STATE.IDLE;
                                    break;
                            }
                            break;
                        case STATE.BUILD_CAN_FRAME:
                		    buffer[1 + rx_step] = c;
		                    switch (rx_step) {
                            case 0:
                                buildFrame.timestamp = c;
                                break;
                            case 1:
                                buildFrame.timestamp |= (uint)(c << 8);
                                break;
                            case 2:
                                buildFrame.timestamp |= (uint)c << 16;
                                break;
                            case 3:
                                buildFrame.timestamp |= (uint)c << 24;
                                break;
		                    case 4:
			                    buildFrame.ID = c;
			                    break;
		                    case 5:
			                    buildFrame.ID |= c << 8;
			                    break;
		                    case 6:
			                    buildFrame.ID |= c << 16;
			                    break;
		                    case 7:
			                    buildFrame.ID |= c << 24;
			                    if ((buildFrame.ID & 1 << 31) == 1 << 31) 
			                    {
				                    buildFrame.ID &= 0x7FFFFFFF;
				                    buildFrame.extended = true;
			                    }
			                    else buildFrame.extended = false;
			                    break;
		                    case 8:
			                    buildFrame.len = c & 0xF;
			                    if (buildFrame.len > 8) buildFrame.len = 8;
                                buildFrame.bus = (c & 0xF0) >> 4;
			                    break;
		                    default:
			                    if (rx_step < buildFrame.len + 9)
			                    {
			                        buildFrame.data[rx_step - 9] = c;
			                    }
			                    else 
			                    {
				                    rx_state = STATE.IDLE;
				                    //this would be the checksum byte. Compute and compare.
				                    //byte temp8 = c;//checksumCalc(buff, step);
				                    //if (temp8 == c) 
				                    //{
                                        onGotCANFrame(buildFrame); //call the listeners
                                        frameCount++;
                                        buildFrame = new CANFrame(); //easy way to clear it out				                
				                    //}
			                    }
			                    break;
		                    }
                    		rx_step++;
                            break;
                        case STATE.GET_ANALOG_INPUTS: //get 9 bytes - 2 per analog input plus checksum
                		    buffer[1 + rx_step] = c;
                            switch (rx_step)
                            {
                            case 0:
                                    break;
                            }
                            rx_step++;
                            break;
                        case STATE.GET_DIG_INPUTS: //get two bytes. One for digital in status and one for checksum.
                		    buffer[1 + rx_step] = c;
                            switch (rx_step)
                            {
                                case 0:
                                    break;
                                case 1:
                                    rx_state = STATE.IDLE;
                                    break;
                            }
                            rx_step++;
                            break;                         
                    }
                }
            }
        }
Example #29
0
        /// <summary>
        /// Event callback for reception of canbus frames
        /// </summary>
        /// <param name="frame">The frame that came in</param>
        public void GotCANFrame(CANFrame frame)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new GotCANDelegate(GotCANFrame), frame);
            }
            else
            {
                //search list of frames and add if no frame with this ID is found
                //or update if one was found.
                bool found = false;
                for (int a = 0; a < frames.Count; a++)
                {
                    if ((frame.ID == frames[a].ID) && (frame.bus == frames[a].bus))
                    {
                        found = true;
                        frames[a].len = frame.len;
                        frames[a].data = frame.data;
                    }
                }
                if (!found)
                {
                    frames.Add(frame);
                }

                //now that frame cache has been updated, try to see if this incoming frame
                //satisfies any triggers

                for (int b = 0; b < sendingData.Count; b++)
                {
                    for (int c = 0; c < sendingData[b].triggers.Length; c++)
                    {
                        Trigger thisTrigger = sendingData[b].triggers[c];
                        if (thisTrigger.ID > 0) 
                        {
                            if ((thisTrigger.bus == frame.bus) || (thisTrigger.bus == -1))
                            {
                                if (thisTrigger.ID == frame.ID)
                                {
                                    //seems to match this trigger.
                                    if (thisTrigger.currCount < thisTrigger.maxCount)
                                    {
                                        if (thisTrigger.milliseconds == 0) //don't want to time the frame, send it right away
                                        {
                                            sendingData[b].triggers[c].currCount++;
                                            sendingData[b].count++;
                                            doModifiers(b);
                                            updateGridRow(b);
                                            parent.SendCANFrame(sendingData[b], sendingData[b].bus);
                                        }
                                        else //instead of immediate sending we start the timer
                                        {
                                            sendingData[b].triggers[c].readyCount = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Example #30
0
        public void SendCANFrame(CANFrame frame, int bus)
        {
            byte[] buffer = new byte[20];
            int c, d;
            int ID;
            StringBuilder dbug = new StringBuilder();
            CANFrame myFrame = new CANFrame();
            myFrame.timestamp = Utility.GetTimeMS();

            ID = frame.ID;
            if (frame.extended) ID |= 1 << 31;

            buffer[0] = 0xF1; //start of a command over serial
            buffer[1] = 0; //command ID for sending a CANBUS frame
            buffer[2] = (byte)(ID & 0xFF); //four bytes of ID LSB first
            buffer[3] = (byte)(ID >> 8);
            buffer[4] = (byte)(ID >> 16);
            buffer[5] = (byte)(ID >> 24);
            buffer[6] = (byte)(bus & 1);
            buffer[7] = (byte)frame.len;
            for (c = 0; c < frame.len; c++)
            {
                buffer[8 + c] = frame.data[c];
            }
            buffer[8 + frame.len] = 0;

            GotCANFrame(frame); //pretend we got this frame on the line so that even frames we send show up in the table
            //FrameCtl = 0

            if (isConnected) serialPort1.Write(buffer, 0, frame.len + 9);
        }
Example #31
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            string[] theSerialPortNames = System.IO.Ports.SerialPort.GetPortNames();
            cbPortNum.Items.AddRange(theSerialPortNames);
            if (cbPortNum.Items.Count > 0) cbPortNum.SelectedIndex = 0;

            label3.Text = "";
            label11.Text = "";
            cbCAN1Speed.SelectedIndex = 0;
            cbCAN2Speed.SelectedIndex = 0;

            //a fast background thread that does nothing but check the buffer for new data
            bufferProc.DoWork += new DoWorkEventHandler(delegate(object o, DoWorkEventArgs args)
            {                                
                do
                {
                    try
                    {
                        this.Invoke(new ProcessDelegate(ProcessInput));
                    }
                    catch (Exception ed)
                    {
                        Debug.Print(ed.ToString());
                    }
                    Thread.Sleep(8);
                } while (runBGThread);
            });


            //slower moving thread that displays a graph of packet levels
            trafficGraph.DoWork += new DoWorkEventHandler(delegate(object o, DoWorkEventArgs args)
            {
                byte[] buffer = new byte[1];
                int loops = 0;                                
                int sizeViewX, sizeViewY;
                sizeViewX = pbActivity.Width;
                sizeViewY = pbActivity.Height;
                Int32[] history = new Int32[125];
                int runningTotal;
                BufferedGraphicsContext myContext;
                BufferedGraphics myBuffer;
                myContext = BufferedGraphicsManager.Current;
                myBuffer = myContext.Allocate(pbActivity.CreateGraphics(), pbActivity.DisplayRectangle);
                Graphics gHandle = myBuffer.Graphics;
                double sx, sy, ex, ey;
                double yScale = 14.0;
                int highest=0;
                int historySpan = 5;
                Pen myPen = new Pen(Brushes.Black);
                int secCount = 0;

                do
                {
                    Thread.Sleep(80);
                    secCount++;
                    if (secCount >= 12)
                    {
                        secCount = 0;
                        try
                        {
                            this.Invoke(new ProcessDelegate(UpdateLabels));
                        }
                        catch (Exception ed)
                        {
                            Debug.Print(ed.ToString());
                        }                        
                    }
                    loops++;
                    if (loops > 20)
                    {
                        loops = 0;
                        buffer[0] = 0x4b;
                        //if (radioSerial.Checked) serialPort1.Write(buffer, 0, 1);
                        //Debug.Print("BG Thread GO!");
                    }
                    if (loops % 6 == 0)
                    {
                        //copy all values back one.
                        for (int i = 0; i < 124; i++) history[i] = history[i + 1];
                        history[124] = frameCount; //fill last entry with current frame count
                        frameCount = 0;
                        runningTotal = 0;
                        highest = 0;

                        for (int i = 124 - historySpan; i < 125; i++)
                        {
                            runningTotal += history[i];
                        }

                        int tempTotal = runningTotal;
                        for (int i = 123; i > 25; i--)
                        {
                            tempTotal -= history[i + 1];
                            tempTotal += history[i - historySpan];
                            if (highest < tempTotal) highest = tempTotal;
                        }

                        //Debug.Print(highest.ToString());
                        if (highest < 4) highest = 4;
                
                        sx = sizeViewX;
                        sy = sizeViewY - yScale * runningTotal;
                        gHandle.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        gHandle.Clear(Color.White);
                        
                        double figure = 0.0f;
                        yScale = 117 / highest;
                        float yPos;

                        //Debug.Print(highest.ToString());
                        //Debug.Print(yScale.ToString());
                        

                        for (int ct = 1; ct < 8; ct++)
                        {
                            yPos = (float)sizeViewY - (ct / 8.0f * (float)sizeViewY);
                            gHandle.DrawLine(myPen, sizeViewX - 10, yPos, sizeViewX, yPos);
                            figure = (double)highest * (double)((double)ct / 8);                         
                            gHandle.DrawString(figure.ToString("F1"), System.Drawing.SystemFonts.DefaultFont, Brushes.Black, (float)sizeViewX - 35.0f, yPos - 5.0f);
                        }


                        int run2 = runningTotal;
                        for (int i = 123; i > 25; i--)
                        {
                            run2 = runningTotal;
                            runningTotal -= history[i + 1];
                            runningTotal += history[i - historySpan];
                            ex = sizeViewX - (sizeViewX / 98.0) * (124 - i);
                            ey = sizeViewY - yScale * (runningTotal + run2) / 2.0;
                            if (ey < 0.0) ey = 0.0;
                            gHandle.DrawLine(myPen, (float)sx, (float)sy, (float)ex, (float)ey);
                            sx = ex;
                            sy = ey;
                        }
                        myBuffer.Render();
                    }
                } while (runBGThread);
            });


            onGotCANFrame += GotCANFrame;
            buildFrame = new CANFrame();
            //Run the background threads right away so that things like
            //simulators and file loaders can still inject canbus messages without an actual
            //physical connection
            runBGThread = true;
            bufferProc.RunWorkerAsync();
            trafficGraph.RunWorkerAsync();

        }
Example #32
0
        private void loadGenericCSVFile(string filename)
        {
            CANFrame thisFrame;
            long     temp;

            System.Globalization.NumberStyles style;

            if (ckUseHex.Checked)
            {
                style = System.Globalization.NumberStyles.HexNumber;
            }
            else
            {
                style = System.Globalization.NumberStyles.Integer;
            }

            StreamReader csvStream = new StreamReader(filename);

            loadedFrames = new List <CANFrame>();
            while (!csvStream.EndOfStream)
            {
                string thisLine = csvStream.ReadLine();
                if (thisLine.Length > 1)
                {
                    string[] theseTokens = thisLine.Split(',');
                    thisFrame = new CANFrame();
                    if (theseTokens.Length > 1)
                    {
                        thisFrame.timestamp = Utility.GetTimeMS();
                        thisFrame.ID        = int.Parse(theseTokens[0], style);
                        if (thisFrame.ID > 0x7FF)
                        {
                            thisFrame.extended = true;
                        }
                        else
                        {
                            thisFrame.extended = false;
                        }
                        thisFrame.bus = 0;

                        string[] dataBytes = theseTokens[1].Split(' ');
                        thisFrame.len = dataBytes.Length;
                        if (thisFrame.len > 8)
                        {
                            thisFrame.len = 8;
                        }
                        for (int c = 0; c < 8; c++)
                        {
                            thisFrame.data[c] = 0;
                        }
                        for (int d = 0; d < thisFrame.len; d++)
                        {
                            thisFrame.data[d] = byte.Parse(dataBytes[d], style);
                        }

                        loadedFrames.Add(thisFrame);
                    }
                }
            }
            csvStream.Close();
        }
Example #33
0
        public void GotCANFrame(CANFrame frame) 
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new GotCANDelegate(GotCANFrame), frame);
            }
            else
            {

                //first of all, always try to keep track of every ID we've ever seen while this form is open
                //if we find one we haven't seen yet then add it
                //foundID is really only used as a fast way to know if the frame ID has been seen before.
                //I believe it to be faster to search than directly searching entries in the listbox
                if (!foundID.Contains(frame.ID))
                {
                    foundID.Add(frame.ID);
                    listFrameIDs.Items.Add("0x" + frame.ID.ToString("X4"));
                }

                //if we are currently capturing and this frame matches the ID we'd like
                //to capture then place it into the buffer.
                if (ckCapture.Checked)
                {
                    if (frame.ID == targettedID)
                    {
                        if (frameCacheWritePos == cacheSize) return;
                        //enqueue frame
                        frameCache[frameCacheWritePos++] = frame;

                        //The special significance of this if is that it fills out the frame
                        //on screen because we will be showing that frame by default according to the program
                        //so it makes sense to ensure we see it immediately.
                        if (frameCacheWritePos == 1) updateDataView();
                        else updateFrameCounter();
                    }
                }
            }
        }
Example #34
0
        private void loadLogFile(string filename)
        {
            CANFrame thisFrame;
            StreamReader logStream = new StreamReader(filename);
            string thisLine;
            System.Globalization.NumberStyles style;

            if (ckUseHex.Checked) style = System.Globalization.NumberStyles.HexNumber;
            else style = System.Globalization.NumberStyles.Integer;

            loadedFrames = new List<CANFrame>();
            
            while (!logStream.EndOfStream)
            {
                thisLine = logStream.ReadLine();

                if (thisLine.StartsWith("***")) continue;

                /*
                tokens:
                0 = timestamp
                1 = Transmission direction
                2 = Channel
                3 = ID
                4 = Type (s = standard, I believe x = extended)
                5 = Data byte length
                6-x = The data bytes
                */
                if (thisLine.Length > 1)
                {
                    string[] theseTokens = thisLine.Split(' ');
                    thisFrame = new CANFrame();
                    thisFrame.timestamp = Utility.GetTimeMS();
                    thisFrame.ID = int.Parse(theseTokens[3].Substring(2), style);
                    if (theseTokens[4] == "s") thisFrame.extended = false;
                    else thisFrame.extended = true;                    
                    thisFrame.bus = int.Parse(theseTokens[2]) - 1;
                    thisFrame.len = int.Parse(theseTokens[5]);
                    for (int c = 0; c < 8; c++) thisFrame.data[c] = 0;
                    for (int d = 0; d < thisFrame.len; d++) thisFrame.data[d] = byte.Parse(theseTokens[6 + d], style);
                    loadedFrames.Add(thisFrame);
                }
            }
            logStream.Close();
        }