Program reading CPU temperature incorrectly when put on new computer - vb.net

I am trying to add a feature to an existing program that would display the current CPU core temperature using the Open Hardware Monitor. I have it working properly on my personal computer where it displays the temperature on a tool strip status label and refreshes on a timer. However, when I copy everything over to a new PC and test run the program the temperatures it returns are always coming back roughly 25 degrees higher than what the Monitor shows. If anyone has any ideas as to why it would read correctly on one computer but not another I would appreciate it as I'm stumped...
Here are the Monitor Temps and what my program is displaying on my PC both matched up.
Open Hardware Monitor temperatures
Temperature displayed in program
Now these are the temperatures displayed on the new PC that would be shipped out.
New PC Open Hardware Monitor
Program temperature display on New PC
This is the code I am currently using to get the temps.
Private Sub Timer3_Tick(sender As Object, e As EventArgs) Handles Timer3.Tick
Dim cp As New Computer()
cp.Open()
cp.HDDEnabled = True
cp.FanControllerEnabled = True
cp.RAMEnabled = True
cp.GPUEnabled = True
cp.MainboardEnabled = True
cp.CPUEnabled = True
Dim Info As String = ""
Timer3.Interval = 5000
For i As Integer = 0 To cp.Hardware.Length - 1
Dim hw = cp.Hardware(i)
Select Case hw.HardwareType
Case HardwareType.CPU
ToolStripStatusLabel5.Text = "CPU" & vbCrLf
For j = 0 To hw.Sensors.Length - 1
Dim sensor = hw.Sensors(j)
If cp.Hardware(i).Sensors(j).SensorType = SensorType.Temperature Then
ToolStripStatusLabel5.Text = sensor.Name & " - " & sensor.Value & vbCrLf
End If
Next
End Select
Next
End Sub

I didn't see the error in the code, here is an example of using OpenHardwaremonitor and WMI to get the CPU temperature, maybe you can try it.

Related

Do...Loop starts too quickly, how to brake it?

With my program, user have to download and save csv files to two different specific directories. Unfortunately automatic downloading not possible. To download file I use command WebBrowser1.Navigate(url), which run php script on the target web page and after one second webBrowser ask path where I or user want to download file. After that again button click and .Navigate to download second one.
But I have to be sure, that user had download file exactly to the specific directory and first, I want to check if file exists there. And here problems are starts. Because of small delay before "Save" possibility, program run immediately Do...Loop process and "Save" window doesn't even come. Also I tried to use thread.sleep, but it doesn't help. Because it immediately go to sleep and "save" window have not time to present. After sleep it immediately starts Do...Loop process.
Is here some other instruments to say to my program, that it wait a little and continue to run code after user "Save" file?
Here is My code:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim kraporttila As String
Dim dt1 As Date = DateTimePicker1.Value
Dim dt2 As Date = DateTimePicker2.Value
Dim faa As String = dt1.ToString("yyyy-MM-dd")
Dim fla As String = dt2.ToString("yyyy-MM-dd")
Dim ddla As String = dt2.ToString("MM.yy")
Dim kuitti As Uri = New Uri("https:url/kuitti.php?faa=" & faa & "&fla=" & fla & "&fk_e=&fa_e=&fm=&ftil=&kuittiexportcsv=Lataa%CSV")
WebBrowser1.Navigate(kuitti)
Button2.Visible = False
Do While
If System.IO.File.Exists(kraporttila) = True Then
Button3.Text = "Lataa maksuvirheet"
Button3.Visible = True
Label3.Text = "Nyt lataa maksuviheet ja tellenna kansioon ""C:\Users\Ivan\" & ddla & "\Laskutukset ja Maksuvirheet\Maksuvirheet"""
Exit Do
Else
Continue Do
End If
Loop
End Sub

Memory files get trashed by third party software

I have an collection of apps that rely on memory files. I create them with a persistent app, then 3 apps update the files with GPS, IMU and switch data, and 3 apps read the current status and generate commands to servo controllers. This has worked fine for years, but today the apps failed due to missing memory files when I started a third party c# camera control app.
I suspect the other app overwrites the memory area. Is there a way to protect these memory files.
I am in Visual Studio 2017, Win10/64 and .net 4.6.1
I have included the create and sample read and write code - all of which have worked for years. I did update the system to current .net 4.6.1, and without the 3rd party app the system runs for hours without error. The instant I start the c# app compiled app the memory files disappear. I do not have access to the source, and am hopeless with C#.
Not a clue now, one solution is to install a new CPU and run the 3rd partys app on a separate box. There is no communication between my apps and it.
I create with :
Dim LoopForever As Boolean = True
Dim AHRS_Memory_File_Name As String = "AHRSMemoryData"
Dim GPS_Memory_File_Name As String = "GPSMemoryData"
Dim Switch_Memory_File_Name As String = "SwitchMemoryData"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim MMS = MemoryMappedFile.CreateNew(Switch_Memory_File_Name, 20,
MemoryMappedFileAccess.ReadWrite)
Dim GPS = MemoryMappedFile.CreateNew(GPS_Memory_File_Name, 200,
MemoryMappedFileAccess.ReadWrite)
Dim AHRS = MemoryMappedFile.CreateNew(AHRS_Memory_File_Name, 200,
MemoryMappedFileAccess.ReadWrite)
Do Until LoopForever = False
Thread.Sleep(10000)
Loop
End Sub
A sample Write is
Sub WriteGPS_To_Memory()
Dim GPS_MMF = MemoryMappedFile.OpenExisting(GPS_Memory_File_Name)
Dim Bytes As Byte()
' This is the format of the current gps memory message
outMessage = GPSSpeedIn & "," & GPSBearing & "," & GPSLongitude & ","
& GPSLatitude & "," & GarminMagDeviationText & "," & GPSMessageCount
& "," & GPSAltitude & ","
Bytes = StrToByteArray(outMessage)
Try
Using writer = GPS_MMF.CreateViewAccessor(0, Bytes.Length)
writer.WriteArray(Of Byte)(0, Bytes, 0, Bytes.Length)
' writer.Dispose()
End Using
Catch ex As Exception
MsgBox("mem write error = " & ex.ToString)
End Try
And a sample read is
Dim MMF = MemoryMappedFile.OpenExisting(MEMS_Memory_File_Name)
Using reader = MMF.CreateViewAccessor(0, 200,
MemoryMappedFileAccess.Read)
Dim NewByteString = New Byte(200) {}
reader.ReadArray(Of Byte)(0, NewByteString, 0,
NewByteString.Length)
InMessage = Convert.ToString(NewByteString)
teststring = ""
CycleCount = CycleCount + 1
teststring = BitConverter.ToString(NewByteString)
For i As Integer = 0 To NewByteString.Length - 1
AHRS_CommDataIn =
System.Text.Encoding.ASCII.GetString(NewByteString)
Next
End Using
MMF.Dispose()
Best outcome is to find a way to protect these files. I am in the US, the vendor is in Israel and not particularly responsive.
There is time pressure on this as my company uses this software to locate water bodies producing mosquitoes (hate those pests) which distribute West Nile Virus, Denge and Malaria. Today we scrubbed a 300 sq mi mission affecting about 500K persons.
The issue was apparently in the third party software - they issued a updated program the day we posted the issue to their support site - so we must not have been to only site with this issue

Detect when Removable USB Volume Drive Devices are Attached or Removed – VB.NET [duplicate]

This question already has an answer here:
Portable Device Detection
(1 answer)
Closed 5 years ago.
Below is some code I saw on a vb message board along time ago but I can’t remember where. It may have been vbforums.com. I made some code changes and then tested the code to have it throw a messagebox with the drive letter of the new usb device being attached or removed. It uses application subclassing to intercept the messages and checks if any are activated by a removable volume being Removed, Inserted, Attached, etc.. If it is then it will parse the volume drive letter of the device and throw a messagebox letting you know. USB devices like flash drives (Thumb Drives or Pen Drive’s as they are also called), external hard drives, etc. with a removable disk volume should be detected just fine. My testing recognized different usb volumes with no problems. You can use this code with VB.NET, Visual Basic 2008, VB 2010, 2013, etc. to check for both the arrival of usb volume devices and the removal. You can also make some changes to make it work for VB 6.0 as well. Visual Basic 6.0 will need an addiional API call or two for the subclassing portion.
Protected Overrides Sub WndProc(ByRef M As System.Windows.Forms.Message)
'
'These are the required subclassing codes for detecting device based removal and arrival.
'
If M.Msg = WM_DEVICECHANGE Then
Select Case M.WParam
'
'Check if a device was added.
Case DBT_DEVICEARRIVAL
Dim DevType As Integer = Runtime.InteropServices.Marshal.ReadInt32(M.LParam, 4)
If DevType = DBT_DEVTYP_VOLUME Then
Dim Vol As New DEV_BROADCAST_VOLUME
Vol = Runtime.InteropServices.Marshal.PtrToStructure(M.LParam, GetType(DEV_BROADCAST_VOLUME))
If Vol.Dbcv_Flags = 0 Then
For i As Integer = 0 To 20
If Math.Pow(2, i) = Vol.Dbcv_Unitmask Then
Dim Usb As String = Chr(65 + i) + ":\"
MsgBox("Looks like a USB device was plugged in!" & vbNewLine & vbNewLine & "The drive letter is: " & Usb.ToString)
Exit For
End If
Next
End If
End If
'
'Check if the message was for the removal of a device.
Case DBT_DEVICEREMOVECOMPLETE
Dim DevType As Integer = Runtime.InteropServices.Marshal.ReadInt32(M.LParam, 4)
If DevType = DBT_DEVTYP_VOLUME Then
Dim Vol As New DEV_BROADCAST_VOLUME
Vol = Runtime.InteropServices.Marshal.PtrToStructure(M.LParam, GetType(DEV_BROADCAST_VOLUME))
If Vol.Dbcv_Flags = 0 Then
For i As Integer = 0 To 20
If Math.Pow(2, i) = Vol.Dbcv_Unitmask Then
Dim Usb As String = Chr(65 + i) + ":\"
MsgBox("Looks like a volume device was removed!" & vbNewLine & vbNewLine & "The drive letter is: " & Usb.ToString)
Exit For
End If
Next
End If
End If
End Select
End If
MyBase.WndProc(M)
End Sub

Unsure on proper use of Serial Port Data Received Event

I'm working on a VSTO add-in for Excel 2013 in VB.NET that will help me interface with an instrument via a serial connection. I currently have the COM connection set up correctly and it will allow me to send and receive one command at a time. I'd like to set it up so that I can push one button and have it collect two separate readings in different worksheet cells. Using the code below, the tools work great to collect a single reading, but when I enable the code to send a second command to the instrument the Data Received event stops working entirely until I send another single read command. I know that the instrument received and processed the second command, but it never appears in excel. Could anyone help with a way to modify this code?
Private Sub mySerialPort_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)
'Handles serial port data received events
UpdateFormDeligate1 = New UpdateFormDeligate(AddressOf UpdateDisplay)
Dim n As Integer = mySerialPort.BytesToRead 'find number of bytes in buff
comBuffer = New Byte(n - 1) {} 're-dimension storage buffer (n - 1)
mySerialPort.Read(comBuffer, 0, n) 'read data from the buffer
comBuffer2 = mySerialPort.ReadTo(vbCr)
Me.Invoke(UpdateFormDeligate1) 'call the deligate
mySerialPort.Close()
End Sub
Private Sub Invoke(updateFormDeligate1 As UpdateFormDeligate)
lblReading.Label = processReading() 'write to a Current Reading lable on the ribbon
Dim myApp As Excel.Application = Globals.ThisAddIn.Application
Dim currentCell = myApp.ActiveCell
currentCell.Value = processReading() 'write data in the excel active cell
Try
advanceCell()
Catch ex As Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
End Try
If measureNo = 2 Then 'this case is selected when I want to read 2 measurements with a single button push
cmdSent = 2
sendCommand(measureCmd)
End If
End Sub
Private Sub UpdateDisplay()
End Sub
Note that I did not include my sendCommand sub because this is a simple .write command to the instrument that appears to be working correctly in all cases. I'd much appreciate any help anyone could provide as I'm pretty new to using data received events.
OK, I tried to isolate only the relevant the part of the script that was having an issue and I created a completely new toolbar for testing. Below is the full code for this new toolbar that contains one connect/measure button and a label that displays the status/result. I tried to comment the code to make it readable, hopefully this helps.
This new toolbar does appear to be working correctly. I'm still a little unsure on my correct usage of the DataReceived event handler in conjunction with the Invoke method (which Visual Studio slightly changed for use with Excel2013). Could anyone please provide comment as to whether I'm still using these events in an unclear way and provide a suggestion on how I may make it better?
Thanks again in advance for any help. I really appreciate it.
Imports Microsoft.Office.Tools.Ribbon
Imports System.IO.Ports
Public Class Measure2x_COM
Dim mySerialPort As New SerialPort
Dim CMD As String = "M" & vbCr 'statement telling instrument to measure
Dim measureNo As Integer = 0 'counts the number of measure commands sent to the instrument
Private Delegate Sub UpdateFormDeligate()
Private UpdateFormDeligate1 As UpdateFormDeligate
Dim sngReading As Single 'this is the reading received from the instrument as a single data type
Private Sub setupConnectCOM()
'Open COM and send measure command - this part works correctly
'first, check if serial port is open
If mySerialPort.IsOpen Then 'send measure command
mySerialPort.Write(CMD) 'the instrument will generally take 15.1 sec to perform a measurement before sending the result back
Else
'if serial port is not open, set it up, then open, then send command
'Setup COM --this part works correctly
With mySerialPort
.PortName = "COM3"
.BaudRate = 1200
.DataBits = 7
.Parity = Parity.None
.StopBits = StopBits.Two
.Handshake = Handshake.None
.ReadTimeout = 16000
End With
Try
mySerialPort.Open()
Catch ex As Exception
System.Windows.Forms.MessageBox.Show(ex.Message)
Exit Sub 'exit sub if the connection fails
End Try
Threading.Thread.Sleep(200) 'wait 0.2 sec for port to open
mySerialPort.Write(CMD) 'send measure command after serial port is open
End If
measureNo = 1
lblResult.Label = "Measuring"
End Sub
Private Sub Measure2x_COM_Load(ByVal sender As System.Object, ByVal e As RibbonUIEventArgs) Handles MyBase.Load
AddHandler mySerialPort.DataReceived, AddressOf mySerialPort_DataReceived
End Sub
Private Sub mySerialPort_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)
'Handles serial port data received events
UpdateFormDeligate1 = New UpdateFormDeligate(AddressOf UpdateDisplay)
'Read data as it comes back from serial port
'I had to do this in two steps because it, for some reason needs to read
'the +/- symbol as a Byte, then needs to read the ASCII measurement number
'the third part concatenates the data and converts it to a single type
'part 1 - read +/- symbol
Dim comBuffer As Byte()
Dim n As Integer = mySerialPort.BytesToRead 'find number of bytes in buff
comBuffer = New Byte(n - 1) {} 're-dimension storage buffer (n - 1)
mySerialPort.Read(comBuffer, 0, n) 'read data from the buffer
'part 2 - read ASCII measurement number
Dim comBuffer2 As String
comBuffer2 = mySerialPort.ReadTo(vbCr)
'part 3 - concatenate read data and convert to single type
Dim txtReading As String = Nothing
txtReading = System.Text.ASCIIEncoding.ASCII.GetString(comBuffer) & CStr(CInt(comBuffer2) / 10)
sngReading = CSng(txtReading)
'Call the update form deligate
'Visual Studio slightly changed this from the example on Microsoft's website that used a Windows Form
'I tried the code in a windows form and I get the same results
Me.Invoke(UpdateFormDeligate1) 'call the deligate
End Sub
Private Sub Invoke(updateFormDeligate1 As UpdateFormDeligate)
lblResult.Label = sngReading 'set the Result label in the ribbon to equal the received data value
'now place the data received in the active cell in the worksheet
Dim myApp As Excel.Application = Globals.ThisAddIn.Application
Dim currentCell = myApp.ActiveCell
currentCell.Value = sngReading
'advance cell to the next cell
Dim newCell = currentCell
newCell = myApp.ActiveCell.Offset(1, 0)
newCell.Select()
currentCell = newCell
'check if this was the first reading from the instrument
'if it was the first reading, then send a second read command
If measureNo = 1 Then
measureNo = 2 'make sure to change measurement number to 2 to avoid infinite loop
mySerialPort.Write(CMD) 'send command to measure to instrument
End If
End Sub
'the usage of this section changed from the Microsoft Windows Form example
'in function, the mySerialPort_DataREceived(), Invoke(), and UpdateDisplay() functions do appear to be
'working with the same results and same hangups
Private Sub UpdateDisplay()
End Sub
Private Sub btnMeasure_Click(sender As Object, e As RibbonControlEventArgs) Handles btnMeasure.Click
setupConnectCOM() 'connect to COM and send first measure command
End Sub
End Class

Customer Display OR Pole Display

I do also want to know how can I Display Text on Pole Display.
I write the code with VB.net 2008.
Sample Code that I write is :
If SerialPort1.IsOpen = False Then SerialPort1.Open()
SerialPort1.Write("\r\n" & RichTextBox1.Text & vbCr, 0, RichTextBox1.TextLength)
System.Threading.Thread.Sleep(1000)
If SerialPort1.IsOpen = True Then SerialPort1.Close()
I got no errors but can't display on Pole Display.
Please help me.
Sorry,
Forgot to Say. I do setup the Serial port Like This:
SerialPort1.BaudRate = 1200
SerialPort1.Parity = IO.Ports.Parity.None
SerialPort1.StopBits = 1
SerialPort1.DataBits = 7
But It doesn't work. :(
sp = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
sp.Open();
// to clear the display
sp.Write(Convert.ToString((char)12));
// first line goes here
sp.WriteLine("Total : " + textBox1.Text + " RM" );
// 2nd line goes here
sp.WriteLine((char)13 + "Tendered:" + textBox2.Text + " RM");
sp.Close();
sp.Dispose();
sp = null;
Dim sp As SerialPort = New SerialPort("COM15", 9600, Parity.None, 8, StopBits.One)
sp.Open()
sp.Write(Convert.ToString(ChrW(12)))
sp.WriteLine("WELCOME HERE")
sp.WriteLine(ChrW(13) & "Total Amount:1200")
sp.Close()
sp.Dispose()
sp = Nothing
You need to setup the serial port - i.e. the baud rate, number of bits and number of stop bits. Read the display poles manual to get these settings.
edit
Before you write any code use a terminal program like windows hyper-terminal to confirm:
That your hardware is working.
if you are using the correct com port
if you are using the correct baud rate
If you need flow control (XON/XOF) or is it via hardware (RTS/CTS)
What commands you can send to the display- i.e. to clear the display & to move the top line
if the display pole dip switches are set-up correctly