Sign in to follow this  
Followers 0
rharwood

need help with file writes

10 posts in this topic

can anyone let me know what I am doing wrong with the file writes??? the serial data is displaying to the screen ok so I know it is capturing the data properly, but if there is a large dump from the serial port the file writing does not seem to keep up. I will get the first 3 lines and the last to lines in the log file. But on the screen it captures everything.

this example is a very simple terminal
;Version 1
;changes-

#Include <Excel.au3>
#include <GUIConstants.au3>
#include 'CommMG.au3';or if you save the commMg.dll in the @scripdir use ;#include @ScriptDir & '\commg.dll'
#include <GuiEdit.au3>
#include <GuiComboBox.au3>
#include <windowsconstants.au3>
#include <buttonconstants.au3>
#include <GuiRichEdit.au3>

Opt("WINTITLEMATCHMODE", 3)
OnAutoItExitRegister("alldone")
HotKeySet("{ESC}", "alldone")
$excellocation=''
$filename='' ;used for file picker
$result = '';used for any returned error message setting port
Const $settitle = "VIRTUAL PRINT- set Port", $maintitle = "Virtual Print"
$setflow = 2;default to no flow control
Dim $FlowType[3] = ["XOnXoff", "Hardware (RTS, CTS)", "NONE"]

#Region main program

#Region ### START Koda GUI section ### Form=d:\my documents\miscdelphi\commg\ExampleComm.kxf
$Form2 = GUICreate("Virtual Print", 473, 349, 339, 333, BitOR($WS_MAXIMIZEBOX, $WS_MINIMIZEBOX, $WS_SIZEBOX, $WS_THICKFRAME, $WS_SYSMENU, $WS_CAPTION, $WS_OVERLAPPEDWINDOW, $WS_TILEDWINDOW, $WS_POPUP, $WS_POPUPWINDOW, $WS_GROUP, $WS_TABSTOP, $WS_BORDER, $WS_CLIPSIBLINGS))
$Edit1 = GUICtrlCreateEdit("", 10, 25, 449, 223, BitOR($ES_AUTOVSCROLL, $ES_AUTOHSCROLL, $ES_READONLY, $ES_WANTRETURN, $WS_HSCROLL, $WS_VSCROLL))
$BtnSend = GUICtrlCreateButton("Send", 380, 273, 53, 30, $BS_FLAT)
$Input1 = GUICtrlCreateInput("", 18, 279, 361, 21)
$Checkbox1 = GUICtrlCreateCheckbox("Add LF to incomming CR", 340, 4,150, 17)
$Checkbox2 = GUICtrlCreateCheckbox("Log to file", 105, 4,100, 17)
$Checkbox3 = GUICtrlCreateCheckbox("Enable Sounds", 205, 4,100, 17)
$Checkbox4 = GUICtrlCreateCheckbox("Auto update", 18, 260,100, 17)
GUICtrlSetState($Checkbox1, $GUI_CHECKED)
GUICtrlSetState($Checkbox2, $GUI_UNCHECKED)
GUICtrlSetState($Checkbox3, $GUI_UNCHECKED)
GUICtrlSetResizing(-1, $GUI_DOCKAUTO)
$BtnSetPort = GUICtrlCreateButton("Set Port", 16, 312, 73, 30, $BS_FLAT)
$BtnSilence = GUICtrlCreateButton("Silence Alarms", 150, 312, 73, 30, $BS_FLAT)
$Label21 = GUICtrlCreateLabel("Received text", 34, 6, 70, 17)
$Label31 = GUICtrlCreateLabel("commg.dll version unknown", 272, 328, 135, 17)
GUICtrlSetColor(-1, 0x008080)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###
WinSetTitle($Form2, "", $maintitle )
$excellocation=_Find("excel.exe")

While setport(0) = -1
    If MsgBox(4, 'Port not set', 'Do you want to quite the program?') = 6 Then Exit
WEnd






;GUISwitch($Form2)
ConsoleWrite("stage 1" & @CRLF)
GUICtrlSetData($Label31, 'using ' & _CommGetVersion(1))
ConsoleWrite("stage 2" & @CRLF)
Events()
GUICtrlSetBkColor($Edit1, 0x000000)     ;black
GUICtrlSetColor($Edit1, 0xffffff)   ; white
GUICtrlSetState($Edit1, $GUI_FOCUS)

While 1

    ;gets characters received returning when one of these conditions is met:
    ;receive @CR, received 20 characters or 200ms has elapsed
    $instr = _CommGetLine()
    
if GUICtrlRead($Checkbox2) = $GUI_CHECKED Then 
        $hnd = FileOpen ("Virtualprintlog.txt", 1)
    endif

    If $instr <> '' Then;if we got something
        
;******************************************START EXCEL UPDATE **************************************
;***************************************************************************************************
if GUICtrlRead($Checkbox4) = $GUI_CHECKED Then 
    
$address=StringMid ( $instr, 1 , 7); pluck the address field

;$FileName="C:\fireutils\est3labelfile.csv"     ; Change this to the path/name of your Excel sheet
;$filename = $infilename

If @error Then
    MsgBox(4096,"","No File(s) chosen")
Else
    $filename = StringReplace($filename, "|", @CRLF)
    ;MsgBox(4096,"","You chose " & $filename)
EndIf

if not FileExists($FileName) then   ; Just a check to be sure..
    Msgbox (0,"Excel Data Test","Error: Can't find file " & $FileName)
    Exit
endif


$oExcelDoc = ObjGet($FileName)  ; Get an Excel Object from an existing filename
;$oExcelDoc.Visible = 1 
If (not @error) and IsObj($oExcelDoc) then          ; Check again if everything went well
                                                    ; NOTE: $oExcelDoc is a "Workbook Object", not Excel itself!    
    $oDocument=$oExcelDoc.Worksheets(1) 
    ; We use the 'Default' worksheet
    $counter = 1
    while(_ExcelReadCell($oExcelDoc, $counter, 4) <> "")
        $counter = $counter + 1
    wend
    ;MsgBox(0, "", "The Cell Value is: " & @CRLF & $counter - 1, 2)
    For $i = 1 To $counter - 1 ;Loop
    $sCellValue = _ExcelReadCell($oExcelDoc, $i, 4)
    $sCell2value =  _ExcelReadCell($oExcelDoc, $i, 5)
    if $sCellValue == $address and $sCell2value == "" Then
    _ExcelWriteCell($oExcelDoc, "P", $i, 5)
    $oExcelDoc.Windows(1).Visible = True
    $oExcelDoc.saved=1              ; Prevent questions from excel to save the file
    ;$oExcelDoc.close       
    ;MsgBox(0, "", "update complete", 2)
    EndIf
Next

    
Else
    Msgbox (0,"Excel Data Test","Error: Could not open "& $FileName & " as an Excel Object.")
Endif
endif
;********************************************* End Excel  ****************************************************
;*************************************************************************************************************


        If GUICtrlRead($Checkbox1) = $GUI_CHECKED Then $instr = StringReplace($instr,@CR,@CRLF)
        
        Select
        Case    StringInStr($instr, 'ALARM')
                ; process alarm condition
                GUICtrlSetColor($Edit1, 0xff0000)   ; Red
                    if GUICtrlRead($Checkbox3) = $GUI_CHECKED Then 
                    SoundPlay("c:\fireutils\sounds\Whopfast.wav")
                    EndIf
                if GUICtrlRead($Checkbox2) = $GUI_CHECKED Then 
                    FileWrite($hnd,$instr)
                    FileFlush($hnd)
                    EndIf
                GUICtrlSetData($Edit1, $instr,1)
                
                ;SoundPlay(@WindowsDir & "\media\Whopfast.wav"); Alert user to alarm condtion can be silenced by button
                
          Case StringInStr($instr, 'Trouble')     ;; <<-- beware the case, could be important
              ;; process Trouble condition
                GUICtrlSetColor($Edit1, 0xffff00)   ; yellow
                if GUICtrlRead($Checkbox2) = $GUI_CHECKED Then 
                    FileWrite($hnd,$instr)
                    FileFlush($hnd)
                    EndIf   
                if GUICtrlRead($Checkbox3) = $GUI_CHECKED Then 
                    Beep(500, 100)
                EndIf
                GUICtrlSetData($Edit1, $instr,1)
                
                ;SoundPlay(@WindowsDir & "\media\tada.wav",1); set this to an alert tone
                ;Beep(500, 100)

          Case StringInStr($instr, 'SUPERVISORY')
              ;; process supervisory condition
                GUICtrlSetColor($Edit1, 0xffff00)   ; yellow
                if GUICtrlRead($Checkbox2) = $GUI_CHECKED Then 
                    FileWrite($hnd,$instr)
                    FileFlush($hnd)
                    EndIf   
                if GUICtrlRead($Checkbox3) = $GUI_CHECKED Then 
                    Beep(500, 100)
                EndIf
                GUICtrlSetData($Edit1, $instr,1)
                
                
                
          Case StringInStr($instr, 'Restored')
              ;; process restored  condition
                GUICtrlSetColor($Edit1, 0x7FFF00)   ; Green
                if GUICtrlRead($Checkbox2) = $GUI_CHECKED Then 
                    FileWrite($hnd,$instr)
                    FileFlush($hnd)
                EndIf
                if GUICtrlRead($Checkbox3) = $GUI_CHECKED Then 
                    Beep(500, 100)
                EndIf
                GUICtrlSetData($Edit1, $instr,1) 
                
             
            Case Else
            GUICtrlSetColor($Edit1, 0xffffff); set text to white for all normal display
            if GUICtrlRead($Checkbox2) = $GUI_CHECKED Then 
                    FileWrite($hnd,$instr)
                    FileFlush($hnd)
                EndIf
                if GUICtrlRead($Checkbox3) = $GUI_CHECKED Then 
                ; no sound here will drive user nuts if sound on every input.
                EndIf
            GUICtrlSetData($Edit1, $instr,1)
            
            
      EndSelect 
      
        
        
        
    EndIf

WEnd
FileClose($hnd)
$oExcelDoc.saved=1  
$oExcelDoc.close        
$oExcelDoc=0

Alldone()


Func port11()
    ;MsgBox(0,'now set to channel',_CommSwitch(2))
    _commSwitch(2)
    $s2 = "1 2 3 4";_CommGetString()
    ConsoleWrite("comm1 gets " & $s2 & @CRLF)
    _CommSendString($s2)
    _CommSwitch(1)

EndFunc   ;==>port11

#EndRegion main program
Func Events()
    Opt("GUIOnEventMode", 1)
    GUISetOnEvent($GUI_EVENT_CLOSE, "justgo")
    GUICtrlSetOnEvent($BtnSend, "SendEvent")
    GUICtrlSetOnEvent($BtnSetPort, "SetPortEvent")
    GUICtrlSetOnEvent($BtnSilence, "Silence")
    GUICtrlSetOnEvent($Checkbox4, "pick")
EndFunc   ;==>Events

Func SetPortEvent()
    setport();needed because a parameter is optional for setport so we can't use "setport" for the event
    GUICtrlSetState($Edit1, $GUI_FOCUS)
EndFunc   ;==>SetPortEvent
Func pick()
 $filename = FileOpenDialog("File picker", "c:\fireutils", "All (*.csv)|", 1 + 4 )
 ShellExecute($excellocation,  $FileName)
 
EndFunc   ;==>pick afile
Func justgo()
    Exit
EndFunc   ;==>justgo

Func SendEvent();send the text in the inputand append CR
    _CommSendstring(GUICtrlRead($Input1) & @CR)
    GUICtrlSetData($Input1, '');clear the input
    ;GUICtrlSetState($edit1,$GUI_FOCUS);sets the caret back in the terminal screen
EndFunc   ;==>SendEvent
Func Silence();stop the sound from alarms etc
    SoundPlay("")
    
EndFunc   ;==>silence

Func AllDone()
    ;MsgBox(0,'will close ports','')
    _Commcloseport()
    ;MsgBox(0,'port closed','')
    Exit
EndFunc   ;==>AllDone
Func _Find ($s, $d = @HomeDrive)
   If StringRight ($d, 1) <> "\" Then $d &= "\"
   Local $h = FileFindFirstFile ($d & "*")
   If $h = -1 Then Return 0
   while 1
      $t = FileFindNextFile ($h)
      If $t = $s Then Return $d & $t
      $t = $d & $t
      If @Error Then Return 0 * FileClose ($h)
      If StringInStr (FileGetAttrib ($t), "D") Then
         $tmp = _Find ($s, $t)
         If $tmp <> "0" Then Return $tmp
         ContinueLoop
      EndIf
   WEnd
   FileClose ($h)
   Return 0
EndFunc ; ==> _Find
Func _FindAll ($s, $d = @HomeDrive)
   If Not IsDeclared ("sRet") Then
      Static $sRet = ""
   EndIf
   If StringRight ($d, 1) <> "\" Then $d &= "\"
   Local $h = FileFindFirstFile ($d & "*")
   If $h = -1 Then Return ""
   while 1
      $t = FileFindNextFile ($h)
      If @Error Then ExitLoop
      If $t = $s Then $sRet &= @CRLF & $d & $t
      $t = $d & $t
      If StringInStr (FileGetAttrib ($t), "D") Then $tmp = _FindAll ($s, $t)
   WEnd
   FileClose ($h)
   Return $sRet
EndFunc ; ==> _FindAll
; Function SetPort($mode=1)
; Creates a form for the port settings
;Parameter $mode sets the return value depending on whether the port was set
;Returns  0 if $mode <> 1
;          -1 If` the port not set and $mode is 1
Func SetPort($mode = 1);if $mode = 1 then returns -1 if settings not made

    Opt("GUIOnEventMode", 0);keep events for $Form2, use GuiGetMsg for $Form3

    #Region ### START Koda GUI section ### Form=d:\my documents\miscdelphi\commg\examplecommsetport.kxf
    $Form3 = GUICreate("virtual Print - set Port", 422, 279, 329, 268, BitOR($WS_MINIMIZEBOX, $WS_CAPTION, $WS_POPUP, $WS_GROUP, $WS_BORDER, $WS_CLIPSIBLINGS, $DS_MODALFRAME), BitOR($WS_EX_TOPMOST, $WS_EX_WINDOWEDGE))
    $Group1 = GUICtrlCreateGroup("Set COM Port", 18, 8, 288, 252)
    $CmboPortsAvailable = GUICtrlCreateCombo("", 127, 28, 145, 25)
    $CmBoBaud = GUICtrlCreateCombo("9600", 127, 66, 145, 25, BitOR($CBS_DROPDOWN, $CBS_AUTOHSCROLL, $CBS_SORT, $WS_VSCROLL))
    GUICtrlSetData(-1, "10400|110|115200|1200|128000|14400|150|15625|1800|19200|2000|2400|256000|28800|3600|38400|4800|50|56000|57600|600|7200|75")
    $CmBoStop = GUICtrlCreateCombo("1", 127, 141, 145, 25)
    GUICtrlSetData(-1, "1|2|1.5")
    $CmBoParity = GUICtrlCreateCombo("none", 127, 178, 145, 25)
    GUICtrlSetData(-1, "odd|even|none")
    $Label2 = GUICtrlCreateLabel("Port", 94, 32, 23, 17)
    $Label3 = GUICtrlCreateLabel("baud", 89, 70, 28, 17)
    $Label4 = GUICtrlCreateLabel("No. Stop bits", 52, 145, 65, 17)
    $Label5 = GUICtrlCreateLabel("parity", 88, 182, 29, 17)
    $CmboDataBits = GUICtrlCreateCombo("8", 127, 103, 145, 25)
    GUICtrlSetData(-1, "7|8")
    $Label7 = GUICtrlCreateLabel("No. of Data Bits", 38, 107, 79, 17)
    $ComboFlow = GUICtrlCreateCombo("NONE", 127, 216, 145, 25)
    GUICtrlSetData(-1, "NONE|XOnXOff|Hardware (RTS, CTS)")
    $Label1 = GUICtrlCreateLabel("flow control", 59, 220, 58, 17)
    GUICtrlCreateGroup("", -99, -99, 1, 1)
    $BtnApply = GUICtrlCreateButton("Apply", 315, 95, 75, 35, $BS_FLAT)
    GUICtrlSetFont(-1, 12, 400, 0, "MS Sans Serif")
    $BtnCancel = GUICtrlCreateButton("Cancel", 316, 147, 76, 35, $BS_FLAT)
    GUICtrlSetFont(-1, 12, 400, 0, "MS Sans Serif")
    GUISetState(@SW_SHOW)
    #EndRegion ### END Koda GUI section ###


    WinSetTitle($Form3, "", $settitle);ensure a change to Koda design doesn't stop script working
    $mainxy = WinGetPos($Form2)
    WinMove($Form3, "", $mainxy[0] + 20, $mainxy[1] + 20)
    ;$set = _CommSetport(1,$result,9600,8,0,1,0)
    ;help
    ;send /rcv
    ;
    $portlist = _CommListPorts(0);find the available COM ports and write them into the ports combo
    If @error = 1 Then
        MsgBox(0, 'trouble getting portlist', 'Program will terminate!')
        Exit
    EndIf


    For $pl = 1 To $portlist[0]
        GUICtrlSetData($CmboPortsAvailable, $portlist[$pl]);_CommListPorts())
    Next
    GUICtrlSetData($CmboPortsAvailable, $portlist[1]);show the first port found
    GUICtrlSetData($ComboFlow, $FlowType[$setflow])
    _GUICtrlComboBox_SetMinVisible($CmBoBaud, 10);restrict the length of the drop-down list

    $retval = 0

    While 1
        $msg = GUIGetMsg()
        If $msg = $BtnCancel Then
            If Not $mode Then $retval = -1
            ExitLoop
        EndIf


        If $msg = $BtnApply Then
            Local $sportSetError
            $comboflowsel = GUICtrlRead($ComboFlow)
            For $n = 0 To 2
                If $comboflowsel = $FlowType[$n] Then
                    $setflow = $n
                    ConsoleWrite("flow = " & $setflow & @CRLF)
                    ExitLoop
                EndIf

            Next
            $setport = StringReplace(GUICtrlRead($CmboPortsAvailable), 'COM', '')
            _CommSetPort($setport, $sportSetError, GUICtrlRead($CmBoBaud), GUICtrlRead($CmboDataBits), GUICtrlRead($CmBoParity), GUICtrlRead($CmBoStop), $setflow)
            if $sportSetError = '' Then
            MsgBox(262144, 'Connected ','to COM' & $setport)
            Else
            MsgBox(262144, 'Setport error = ', $sportSetError)
            EndIf
            $mode = 1;
            ExitLoop
        EndIf

        ;stop user switching back to $form2
        If WinActive($maintitle) Then
            ConsoleWrite('main is active' & @CRLF)
            If WinActivate($settitle) = 0 Then MsgBox(0, 'not found', $settitle)
        EndIf


    WEnd
    GUIDelete($Form3)
    WinActivate($maintitle)
    Events()
    Return $retval


EndFunc   ;==>SetPort

Share this post


Link to post
Share on other sites



I am not setup to test this script so I cannot just debug, however it looks like you are using COM (OLE) to write to Excel. The COM Object for Excel could be encountering an error, try installing an error handler like this:

Global $g_eventerror = 0  ; to be checked to know if com error occurs. Must be reset after handling.

$oMyError = ObjEvent("AutoIt.Error","MyErrFunc") ; Install a custom error handler






; This is my custom error handler 
Func MyErrFunc() 
   $HexNumber=hex($oMyError.number,8) 
   Msgbox(0,"","We intercepted a COM Error !" & @CRLF & _
                "Number is: " & $HexNumber & @CRLF & _
                "Windescription is: " & $oMyError.windescription & @CRLF& "Error was on line: " & $oMyError.scriptline) 

   $g_eventerror = 1 ; something to check for when this function returns 
Endfunc

[sup]Psibernetic[/sup]My Creations:X-HideSecuracy

Share this post


Link to post
Share on other sites

@rharwood: Take a close look at what you are doing inside While/WEnd loops and see if your really want to be repeating those operations over-and-over-again. For example, you re-attach to the Excel object repeatedly, but only close it once after exiting the loop. Same thing with opening Virtualprintlog.txt every loop, but only closing it after the loop exits.

I might be wrong the bad formatting makes the code too hard to read very closely. Run some Tidy on it!

:D


Valuater's AutoIt 1-2-3, Class... Is now in Session!For those who want somebody to write the script for them: RentACoder"Any technology distinguishable from magic is insufficiently advanced." -- Geek's corollary to Clarke's law

Share this post


Link to post
Share on other sites

Thx psaltyds, does Tidy come with autoit or is it a add on

Share this post


Link to post
Share on other sites

@rharwood

A bit off-topic but it might be wise to correct some of your comments. If they are incorrect then they might not help you understand your script.

This part for example

;gets characters received returning when one of these conditions is met:
 ;receive @CR, received 20 characters or 200ms has elapsed
 $instr = _CommGetLine()

should be

;get characters returning when @CR received (@CR is included in the return!)
 $instr = _CommGetLine();_CommGetLine([$endChar=@CR,$maxchar = 0, $maxtime = 0)

Serial port communications UDF Includes functions for binary transmission and reception.printing UDF Useful for graphs, forms, labels, reports etc.Add User Call Tips to SciTE for functions in UDFs not included with AutoIt and for your own scripts.Functions with parameters in OnEvent mode and for Hot Keys One function replaces GuiSetOnEvent, GuiCtrlSetOnEvent and HotKeySet.UDF IsConnected2 for notification of status of connected state of many urls or IPs, without slowing the script.

Share this post


Link to post
Share on other sites

Sorry about comments most are from the scripts that I used to build this from, I am bad at commenting , I usually go back when I get the thing working and comment at that time. Also to the person that mentioned the tidy thing to me the problem seems to have been that I was running the scitelite I now have the full version,,, Wow what a difference. Thanks for the heads up on that.

On the multiple file opens, if I move the file open for the log file to a function called from a event will this help and if so do I need to use global variable declarations then. I am guessing that variables in the function are local to that function only.

Share this post


Link to post
Share on other sites

ok here is rewritten script with Tidy done and commented any suggestions on improvements. BTW is there anyway to have the help button display the version info in the script automatically.

#NoTrayIcon
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_outfile=virtualprint2.exe
#AutoIt3Wrapper_Res_Comment=cleaned up file
#AutoIt3Wrapper_Res_Description=Virtual printer and parser
#AutoIt3Wrapper_Res_Fileversion=2.0.0.1
#AutoIt3Wrapper_Res_Fileversion_AutoIncrement=p
#AutoIt3Wrapper_Res_LegalCopyright=Robert Harwood 2010
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
;this example is a very simple terminal
;Version 1
;changes-
#include <Excel.au3>
#include <GUIConstants.au3>
#include 'CommMG.au3';or if you save the commMg.dll in the @scripdir use ;#include @ScriptDir & '\commg.dll'
#include <GuiEdit.au3>
#include <GuiComboBox.au3>
#include <windowsconstants.au3>
#include <buttonconstants.au3>
#include <GuiRichEdit.au3>

Opt("WINTITLEMATCHMODE", 3)
OnAutoItExitRegister("alldone")
HotKeySet("{ESC}", "alldone")
global $oExcelDoc = '' ;use for excel funtion and parsing routine
global $hnd ='';used for logging file
global $counter ='';used in excel function and parsing routine
Global $address = '';used in excel function and parsing routine
Global $excellocation = '';used to store location of excel executable
Global $filename = '' ;used for file picker
$result = '';used for any returned error message setting port
Const $settitle = "VIRTUAL PRINT- set Port", $maintitle = "Virtual Print"
$setflow = 2;default to no flow control
Dim $FlowType[3] = ["XOnXoff", "Hardware (RTS, CTS)", "NONE"]

#Region main program

#Region ### START Koda GUI section ### Form=d:\my documents\miscdelphi\commg\ExampleComm.kxf
$Form2 = GUICreate("Virtual Print", 473, 349, 339, 333, BitOR($WS_MAXIMIZEBOX, $WS_MINIMIZEBOX, $WS_SIZEBOX, $WS_THICKFRAME, $WS_SYSMENU, $WS_CAPTION, $WS_OVERLAPPEDWINDOW, $WS_TILEDWINDOW, $WS_POPUP, $WS_POPUPWINDOW, $WS_GROUP, $WS_TABSTOP, $WS_BORDER, $WS_CLIPSIBLINGS))
$Edit1 = GUICtrlCreateEdit("", 10, 25, 449, 223, BitOR($ES_AUTOVSCROLL, $ES_AUTOHSCROLL, $ES_READONLY, $ES_WANTRETURN, $WS_HSCROLL, $WS_VSCROLL))
$BtnSend = GUICtrlCreateButton("Send", 380, 273, 53, 30, $BS_FLAT)
$Input1 = GUICtrlCreateInput("", 18, 279, 361, 21)
$Checkbox1 = GUICtrlCreateCheckbox("Add LF to incomming CR", 340, 4, 150, 17)
$Checkbox2 = GUICtrlCreateCheckbox("Log to file", 105, 4, 100, 17)
$Checkbox3 = GUICtrlCreateCheckbox("Enable Sounds", 205, 4, 100, 17)
$Checkbox4 = GUICtrlCreateCheckbox("Auto update", 18, 260, 100, 17)
GUICtrlSetState($Checkbox1, $GUI_CHECKED)
GUICtrlSetState($Checkbox2, $GUI_UNCHECKED)
GUICtrlSetState($Checkbox3, $GUI_UNCHECKED)
GUICtrlSetResizing(-1, $GUI_DOCKAUTO)
$BtnSetPort = GUICtrlCreateButton("Set Port", 16, 312, 73, 30, $BS_FLAT)
$BtnSilence = GUICtrlCreateButton("Silence Alarms", 150, 312, 73, 30, $BS_FLAT)
$Label21 = GUICtrlCreateLabel("Received text", 34, 6, 70, 17)
$Label31 = GUICtrlCreateLabel("commg.dll version unknown", 272, 328, 135, 17)
GUICtrlSetColor(-1, 0x008080)
GUISetState(@SW_SHOW)
#EndRegion ### END Koda GUI section ###
WinSetTitle($Form2, "", $maintitle)
;MsgBox(64, "Notice", "Wait until comm dialog appears before proceding", 15)
;$excellocation = _Find(@ProgramsDir & "excel.exe")

While SetPort(0) = -1
    If MsgBox(4, 'Port not set', 'Do you want to quite the program?') = 6 Then Exit
WEnd






;GUISwitch($Form2)
ConsoleWrite("stage 1" & @CRLF)
GUICtrlSetData($Label31, 'using ' & _CommGetVersion(1))
ConsoleWrite("stage 2" & @CRLF)
Events()
GUICtrlSetBkColor($Edit1, 0x000000) ;black
GUICtrlSetColor($Edit1, 0xffffff) ; white
GUICtrlSetState($Edit1, $GUI_FOCUS)

While 1

    ;get characters returning when @CR received (@CR is included in the return!)
    $instr = _CommGetLine();_CommGetLine([$endChar=@CR,$maxchar = 0, $maxtime = 0)



    If $instr <> '' Then ;if we got something from serial port

        ;******************************************START EXCEL UPDATE **************************************
        ;***************************************************************************************************
        If GUICtrlRead($Checkbox4) = $GUI_CHECKED Then ;If the autoupdate checkbos is checked


            ;IF this works in function remove between ***
            ;****************************************************************************************************
            ;$oExcelDoc = ObjGet($filename) ; Get an Excel Object from an existing filename
            ;$oExcelDoc.Visible = 1
            ;If (Not @error) And IsObj($oExcelDoc) Then ; Check again if everything went well
            ; NOTE: $oExcelDoc is a "Workbook Object", not Excel itself!
            ;$oDocument = $oExcelDoc.Worksheets(1)
            ; We use the 'Default' worksheet
            ;$counter = 1
            ;while (_ExcelReadCell($oExcelDoc, $counter, 4) <> "")
            ;   $counter = $counter + 1
            ;WEnd
            ;MsgBox(0, "", "The Cell Value is: " & @CRLF & $counter - 1, 2)
            ;*******************************************************************************************
            For $i = 1 To $counter - 1 ;Loop
                $sCellValue = _ExcelReadCell($oExcelDoc, $i, 4)
                $sCell2value = _ExcelReadCell($oExcelDoc, $i, 5)
                If $sCellValue == $address And $sCell2value == "" Then
                    _ExcelWriteCell($oExcelDoc, "P", $i, 8)
                    _ExcelWriteCell($oExcelDoc, "P", $i, 11)
                    $oExcelDoc.Windows(1).Visible = True
                    $oExcelDoc.saved = 1 ; Prevent questions from excel to save the file
                    ;$oExcelDoc.close
                    ;MsgBox(0, "", "update complete", 2)
                EndIf
            Next

            ;****************************************************************************************************************
            ;Else
            ;MsgBox(0, "Excel Data Test", "Error: Could not open " & $filename & " as an Excel Object.")
            ;EndIf
            ;****************************************************************************************************************
        EndIf
        ;********************************************* End Excel  ****************************************************
        ;*************************************************************************************************************


        If GUICtrlRead($Checkbox1) = $GUI_CHECKED Then $instr = StringReplace($instr, @CR, @CRLF); see if we want crlf


        ;*****************This section does the stream parsing for colour codes based on data returned and if logging
        ;****************is required log the data to a file
        Select
            Case StringInStr($instr, 'ALARM') ;Watch for this string in serial data
                ; process alarm condition
                GUICtrlSetColor($Edit1, 0xff0000) ; Red
                If GUICtrlRead($Checkbox3) = $GUI_CHECKED Then ;if sound is enabled
                    SoundPlay("c:\fireutils\sounds\Whopfast.wav") ; Alert user to alarm condtion can be silenced by button
                EndIf
                If GUICtrlRead($Checkbox2) = $GUI_CHECKED Then ;if file logging on
                    FileWrite($hnd, $instr)
                    FileFlush($hnd)
                EndIf
                GUICtrlSetData($Edit1, $instr, 1) ;send data to screen



            Case StringInStr($instr, 'Trouble') ;Watch for this string in serial data
                ;; process Trouble condition
                GUICtrlSetColor($Edit1, 0xffff00) ; yellow
                If GUICtrlRead($Checkbox2) = $GUI_CHECKED Then ;if file logging on
                    FileWrite($hnd, $instr)
                    FileFlush($hnd)
                EndIf
                If GUICtrlRead($Checkbox3) = $GUI_CHECKED Then ;if sound is enabled
                    Beep(500, 100)
                EndIf
                GUICtrlSetData($Edit1, $instr, 1) ;send data to screen



            Case StringInStr($instr, 'SUPERVISORY') ;same as above
                ;; process supervisory condition
                GUICtrlSetColor($Edit1, 0xffff00) ; yellow
                If GUICtrlRead($Checkbox2) = $GUI_CHECKED Then
                    FileWrite($hnd, $instr)
                    FileFlush($hnd)
                EndIf
                If GUICtrlRead($Checkbox3) = $GUI_CHECKED Then
                    Beep(500, 100)
                EndIf
                GUICtrlSetData($Edit1, $instr, 1)



            Case StringInStr($instr, 'Restored') ;same as above
                ;; process restored  condition
                GUICtrlSetColor($Edit1, 0x7FFF00) ; Green
                If GUICtrlRead($Checkbox2) = $GUI_CHECKED Then
                    FileWrite($hnd, $instr)
                    FileFlush($hnd)
                EndIf
                If GUICtrlRead($Checkbox3) = $GUI_CHECKED Then
                    Beep(500, 100)
                EndIf
                GUICtrlSetData($Edit1, $instr, 1)


            Case Else
                GUICtrlSetColor($Edit1, 0xffffff) ; set text to white for all normal display
                If GUICtrlRead($Checkbox2) = $GUI_CHECKED Then ;Check for logging
                    FileWrite($hnd, $instr)
                    FileFlush($hnd)
                EndIf

                GUICtrlSetData($Edit1, $instr, 1) ;send data to screen


        EndSelect




    EndIf
WEnd
; ********************************When we are done close things off ***************************************
If GUICtrlRead($Checkbox2) = $GUI_CHECKED Then
    FileClose($hnd)
EndIf
If GUICtrlRead($Checkbox4) = $GUI_CHECKED Then
    $oExcelDoc.saved = 1
    $oExcelDoc.close
    $oExcelDoc = 0
EndIf
AllDone()


Func port11()  ; no ideas what this does was part of comm example script
    ;MsgBox(0,'now set to channel',_CommSwitch(2))
    _commSwitch(2)
    $s2 = "1 2 3 4";_CommGetString()
    ConsoleWrite("comm1 gets " & $s2 & @CRLF)
    _CommSendString($s2)
    _CommSwitch(1)

EndFunc   ;==>port11
#EndRegion main program

Func Events()
    Opt("GUIOnEventMode", 1)
    GUISetOnEvent($GUI_EVENT_CLOSE, "justgo")
    GUICtrlSetOnEvent($BtnSend, "SendEvent")
    GUICtrlSetOnEvent($BtnSetPort, "SetPortEvent")
    GUICtrlSetOnEvent($BtnSilence, "Silence")
    GUICtrlSetOnEvent($Checkbox4, "AutoUpdate")
    GUICtrlSetOnEvent($Checkbox2, "Logfile")
EndFunc   ;==>Events

Func SetPortEvent()
    SetPort();needed because a parameter is optional for setport so we can't use "setport" for the event
    GUICtrlSetState($Edit1, $GUI_FOCUS)
EndFunc   ;==>SetPortEvent
Func AutoUpdate();*******************This is for the auto updating of an excel file from the data coming in on the serial port
    If GUICtrlRead($Checkbox4) = $GUI_CHECKED Then; if we turn on the autoupdate function

        $filename = FileOpenDialog("File picker", "c:\fireutils", "All (*.csv)|", 1 + 4); pick the spreadsheet to use
        If @error Then
            MsgBox(4096, "", "No File(s) chosen")
        Else
            $filename = StringReplace($filename, "|", @CRLF)
            ;MsgBox(4096,"","You chose " & $filename)
        EndIf

        If Not FileExists($filename) Then                       ; Just a check to be sure..
            MsgBox(0, "Excel Data Test", "Error: Can't find file " & $filename)
            Exit
        EndIf
        ShellExecute($excellocation, $filename)                 ; open the spreadsheet for viewing

        $oExcelDoc = ObjGet($filename)                          ; Get an Excel Object from an existing filename
        ;$oExcelDoc.Visible = 1
        If (Not @error) And IsObj($oExcelDoc) Then              ; Check again if everything went well
                                                                ; NOTE: $oExcelDoc is a "Workbook Object", not Excel itself!
            $oDocument = $oExcelDoc.Worksheets(1)               ; We use the 'Default' worksheet
                                                                ;may change if we go to another spreadsheet
            $counter = 1
            while (_ExcelReadCell($oExcelDoc, $counter, 4) <> ""); get the number of devices in the sheet so that we
                $counter = $counter + 1                         ;know what the top end is when we parse
            WEnd
        Else
            MsgBox(0, "Excel Data Test", "Error: Could not open " & $filename & " as an Excel Object.")
        EndIf
    EndIf

EndFunc   ;==>pick

Func Logfile();*******************This function turns on and off file logging
    If GUICtrlRead($Checkbox2) = $GUI_UNCHECKED Then
    FileClose($hnd)
    ConsoleWrite("close log file" & @CRLF)
    endif
    If GUICtrlRead($Checkbox2) = $GUI_CHECKED Then
        ConsoleWrite("open log file" & @CRLF)
        $hnd = FileOpen("Virtualprintlog.txt", 1)
    EndIf
EndFunc   ;==>logfile

Func justgo()
    Exit
EndFunc   ;==>justgo

Func SendEvent()                                        ;send the text in the input and append CR
    _CommSendstring(GUICtrlRead($Input1) & @CR)
    GUICtrlSetData($Input1, '')                         ;clear the input
    ;GUICtrlSetState($edit1,$GUI_FOCUS);sets the caret back in the terminal screen
EndFunc   ;==>SendEvent

Func Silence()                                          ;stop the sound from alarms etc
    SoundPlay("")

EndFunc   ;==>Silence

Func AllDone()
    ;MsgBox(0,'will close ports','')
    _Commcloseport()
    ;MsgBox(0,'port closed','')
    Exit
EndFunc   ;==>AllDone

Func _Find($s, $d = @HomeDrive)                         ;only way I could find to locate the excel. exe file
    If StringRight($d, 1) <> "\" Then $d &= "\"
    Local $h = FileFindFirstFile($d & "*")
    If $h = -1 Then Return 0
    While 1
        $t = FileFindNextFile($h)
        If $t = $s Then Return $d & $t
        $t = $d & $t
        If @error Then Return 0 * FileClose($h)
        If StringInStr(FileGetAttrib($t), "D") Then
            $tmp = _Find($s, $t)
            If $tmp <> "0" Then Return $tmp
            ContinueLoop
        EndIf
    WEnd
    FileClose($h)
    Return 0
EndFunc   ;==>_Find
Func _FindAll($s, $d = @HomeDrive)
    If Not IsDeclared("sRet") Then
        Static $sRet = ""
    EndIf
    If StringRight($d, 1) <> "\" Then $d &= "\"
    Local $h = FileFindFirstFile($d & "*")
    If $h = -1 Then Return ""
    While 1
        $t = FileFindNextFile($h)
        If @error Then ExitLoop
        If $t = $s Then $sRet &= @CRLF & $d & $t
        $t = $d & $t
        If StringInStr(FileGetAttrib($t), "D") Then $tmp = _FindAll($s, $t)
    WEnd
    FileClose($h)
    Return $sRet
EndFunc   ;==>_FindAll

; Function SetPort($mode=1)
; Creates a form for the port settings
;Parameter $mode sets the return value depending on whether the port was set
;Returns  0 if $mode <> 1
;          -1 If` the port not set and $mode is 1

Func SetPort($mode = 1)                             ;if $mode = 1 then returns -1 if settings not made

    Opt("GUIOnEventMode", 0)                        ;keep events for $Form2, use GuiGetMsg for $Form3

    #Region ### START Koda GUI section ### Form=d:\my documents\miscdelphi\commg\examplecommsetport.kxf
    $Form3 = GUICreate("virtual Print - set Port", 422, 279, 329, 268, BitOR($WS_MINIMIZEBOX, $WS_CAPTION, $WS_POPUP, $WS_GROUP, $WS_BORDER, $WS_CLIPSIBLINGS, $DS_MODALFRAME), BitOR($WS_EX_TOPMOST, $WS_EX_WINDOWEDGE))
    $Group1 = GUICtrlCreateGroup("Set COM Port", 18, 8, 288, 252)
    $CmboPortsAvailable = GUICtrlCreateCombo("", 127, 28, 145, 25)
    $CmBoBaud = GUICtrlCreateCombo("9600", 127, 66, 145, 25, BitOR($CBS_DROPDOWN, $CBS_AUTOHSCROLL, $CBS_SORT, $WS_VSCROLL))
    GUICtrlSetData(-1, "10400|110|115200|1200|128000|14400|150|15625|1800|19200|2000|2400|256000|28800|3600|38400|4800|50|56000|57600|600|7200|75")
    $CmBoStop = GUICtrlCreateCombo("1", 127, 141, 145, 25)
    GUICtrlSetData(-1, "1|2|1.5")
    $CmBoParity = GUICtrlCreateCombo("none", 127, 178, 145, 25)
    GUICtrlSetData(-1, "odd|even|none")
    $Label2 = GUICtrlCreateLabel("Port", 94, 32, 23, 17)
    $Label3 = GUICtrlCreateLabel("baud", 89, 70, 28, 17)
    $Label4 = GUICtrlCreateLabel("No. Stop bits", 52, 145, 65, 17)
    $Label5 = GUICtrlCreateLabel("parity", 88, 182, 29, 17)
    $CmboDataBits = GUICtrlCreateCombo("8", 127, 103, 145, 25)
    GUICtrlSetData(-1, "7|8")
    $Label7 = GUICtrlCreateLabel("No. of Data Bits", 38, 107, 79, 17)
    $ComboFlow = GUICtrlCreateCombo("NONE", 127, 216, 145, 25)
    GUICtrlSetData(-1, "NONE|XOnXOff|Hardware (RTS, CTS)")
    $Label1 = GUICtrlCreateLabel("flow control", 59, 220, 58, 17)
    GUICtrlCreateGroup("", -99, -99, 1, 1)
    $BtnApply = GUICtrlCreateButton("Apply", 315, 95, 75, 35, $BS_FLAT)
    GUICtrlSetFont(-1, 12, 400, 0, "MS Sans Serif")
    $BtnCancel = GUICtrlCreateButton("Cancel", 316, 147, 76, 35, $BS_FLAT)
    GUICtrlSetFont(-1, 12, 400, 0, "MS Sans Serif")
    GUISetState(@SW_SHOW)
    #EndRegion ### END Koda GUI section ###


    WinSetTitle($Form3, "", $settitle)                  ;ensure a change to Koda design doesn't stop script working
    $mainxy = WinGetPos($Form2)
    WinMove($Form3, "", $mainxy[0] + 20, $mainxy[1] + 20)

    $portlist = _CommListPorts(0);find the available COM ports and write them into the ports combo
    If @error = 1 Then
        MsgBox(0, 'trouble getting portlist', 'Program will terminate!')
        Exit
    EndIf


    For $pl = 1 To $portlist[0]
        GUICtrlSetData($CmboPortsAvailable, $portlist[$pl])         ;_CommListPorts())
    Next
    GUICtrlSetData($CmboPortsAvailable, $portlist[1])               ;show the first port found
    GUICtrlSetData($ComboFlow, $FlowType[$setflow])
    _GUICtrlComboBox_SetMinVisible($CmBoBaud, 10)                   ;restrict the length of the drop-down list

    $retval = 0

    While 1
        $msg = GUIGetMsg()
        If $msg = $BtnCancel Then
            If Not $mode Then $retval = -1
            ExitLoop
        EndIf


        If $msg = $BtnApply Then
            Local $sportSetError
            $comboflowsel = GUICtrlRead($ComboFlow)
            For $n = 0 To 2
                If $comboflowsel = $FlowType[$n] Then
                    $setflow = $n
                    ConsoleWrite("flow = " & $setflow & @CRLF)
                    ExitLoop
                EndIf

            Next
            $setport = StringReplace(GUICtrlRead($CmboPortsAvailable), 'COM', '')
            _CommSetPort($setport, $sportSetError, GUICtrlRead($CmBoBaud), GUICtrlRead($CmboDataBits), GUICtrlRead($CmBoParity), GUICtrlRead($CmBoStop), $setflow)
            If $sportSetError = '' Then
                MsgBox(262144, 'Connected ', 'to COM' & $setport)
            Else
                MsgBox(262144, 'Setport error = ', $sportSetError)
            EndIf
            $mode = 1;
            ExitLoop
        EndIf

        ;stop user switching back to $form2
        If WinActive($maintitle) Then
            ConsoleWrite('main is active' & @CRLF)
            If WinActivate($settitle) = 0 Then MsgBox(0, 'not found', $settitle)
        EndIf


    WEnd
    GUIDelete($Form3)
    WinActivate($maintitle)
    Events()
    Return $retval


EndFunc   ;==>SetPort

Share this post


Link to post
Share on other sites

#9 ·  Posted (edited)

Opt("GUIOnEventMode", 0)                        ;keep events for $Form2, use GuiGetMsg for $Form3
That GuiOnEventMode is global to the script. You can't have one GUI in message loop and the other in event mode at the same time.

If the behavior is acceptable to you, then you can change the mode dynamically during script execution, but the event mode GUI won't respond while in GuiGetMsg mode, and GuiGetMsg() always returns 0 (no message) while in event mode.

:D

PS: I didn't see a help button in your GUI, but the file version set by #AutoIt3Wrapper_Res_Fileversion can be retrieved by FileGetVersion(@ScriptFullPath).

Edited by PsaltyDS

Valuater's AutoIt 1-2-3, Class... Is now in Session!For those who want somebody to write the script for them: RentACoder"Any technology distinguishable from magic is insufficiently advanced." -- Geek's corollary to Clarke's law

Share this post


Link to post
Share on other sites

That part of the code was written by who ever wrote the commg.dll as a example, and I just reused it as it did 98% of what I needed it to do.I think that when that form is running you can't do anything else, i seem to remember reading that somewhere, not sure where though. The only time that form is used is before the main form starts so hopefully it will not be a problem. Thanks for the tip on getfilever, I will put that in right away. It will save me updating it manually all the time.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0