Add serial data received event handler to f# serial port reader












1















I am having simple read write instructions in f# to communicate between serial ports:



        async {
do! port.AsyncWriteLineAsByte messange
let! response = port.AsyncReadLineAsByte()

return response
}


Where response is byte and method is simple as that:



    member this.AsyncReadLineAsByte() : Async<byte> =
async {

let buffer_ref = ref (Array.zeroCreate<byte> this.ReadBufferSize)
let buffer = !buffer_ref

let! read_bytes = this.BaseStream.AsyncRead(buffer, 0, this.ReadBufferSize)

return buffer
}


And well it works, it sends and recives messages, there is one but in all this.
Reading responses shold be on event of some sort. I am new to F# but i tried something like:



    async {

let data_recived_event = port.AsyncReadLineAsByte()

do! port.AsyncWriteLineAsByte messange

port.DataReceived.AddHandler(data_recived_event) // it says SerialDataReciveHandler is what he expects

let! response = ???

return response
}


But no luck, documentation is rather, for f# it just specify prototype and method construction not a practical usage. I need a event and a way to return that value , is there a way?



EDIT:



Ive been able to add event as serial port namespace has DataReceived.AddHandler event subscription.



So now it looks:



        async {

let data_recived() =
async{
let! buffer = port.AsyncReadLineAsByte()
printfn "Response from event %A" buffer
// return buffer
} |> fun response -> Async.RunSynchronously(response)

port.DataReceived.AddHandler(fun _ _ -> data_recived())

do! port.AsyncWriteLineAsByte messange
let! response = port.AsyncReadLineAsByte()

return response
}


And it works, problem is still how to return such a value from event, if I do something like:



            let data_recived() =
async{
let! buffer = port.AsyncReadLineAsByte()

printfn "Response from event %A" buffer
return buffer
} |> fun response -> Async.RunSynchronously(response)

port.DataReceived.AddHandler(fun _ _ -> response = data_recived())


Is says it expects uint and get bool










share|improve this question





























    1















    I am having simple read write instructions in f# to communicate between serial ports:



            async {
    do! port.AsyncWriteLineAsByte messange
    let! response = port.AsyncReadLineAsByte()

    return response
    }


    Where response is byte and method is simple as that:



        member this.AsyncReadLineAsByte() : Async<byte> =
    async {

    let buffer_ref = ref (Array.zeroCreate<byte> this.ReadBufferSize)
    let buffer = !buffer_ref

    let! read_bytes = this.BaseStream.AsyncRead(buffer, 0, this.ReadBufferSize)

    return buffer
    }


    And well it works, it sends and recives messages, there is one but in all this.
    Reading responses shold be on event of some sort. I am new to F# but i tried something like:



        async {

    let data_recived_event = port.AsyncReadLineAsByte()

    do! port.AsyncWriteLineAsByte messange

    port.DataReceived.AddHandler(data_recived_event) // it says SerialDataReciveHandler is what he expects

    let! response = ???

    return response
    }


    But no luck, documentation is rather, for f# it just specify prototype and method construction not a practical usage. I need a event and a way to return that value , is there a way?



    EDIT:



    Ive been able to add event as serial port namespace has DataReceived.AddHandler event subscription.



    So now it looks:



            async {

    let data_recived() =
    async{
    let! buffer = port.AsyncReadLineAsByte()
    printfn "Response from event %A" buffer
    // return buffer
    } |> fun response -> Async.RunSynchronously(response)

    port.DataReceived.AddHandler(fun _ _ -> data_recived())

    do! port.AsyncWriteLineAsByte messange
    let! response = port.AsyncReadLineAsByte()

    return response
    }


    And it works, problem is still how to return such a value from event, if I do something like:



                let data_recived() =
    async{
    let! buffer = port.AsyncReadLineAsByte()

    printfn "Response from event %A" buffer
    return buffer
    } |> fun response -> Async.RunSynchronously(response)

    port.DataReceived.AddHandler(fun _ _ -> response = data_recived())


    Is says it expects uint and get bool










    share|improve this question



























      1












      1








      1








      I am having simple read write instructions in f# to communicate between serial ports:



              async {
      do! port.AsyncWriteLineAsByte messange
      let! response = port.AsyncReadLineAsByte()

      return response
      }


      Where response is byte and method is simple as that:



          member this.AsyncReadLineAsByte() : Async<byte> =
      async {

      let buffer_ref = ref (Array.zeroCreate<byte> this.ReadBufferSize)
      let buffer = !buffer_ref

      let! read_bytes = this.BaseStream.AsyncRead(buffer, 0, this.ReadBufferSize)

      return buffer
      }


      And well it works, it sends and recives messages, there is one but in all this.
      Reading responses shold be on event of some sort. I am new to F# but i tried something like:



          async {

      let data_recived_event = port.AsyncReadLineAsByte()

      do! port.AsyncWriteLineAsByte messange

      port.DataReceived.AddHandler(data_recived_event) // it says SerialDataReciveHandler is what he expects

      let! response = ???

      return response
      }


      But no luck, documentation is rather, for f# it just specify prototype and method construction not a practical usage. I need a event and a way to return that value , is there a way?



      EDIT:



      Ive been able to add event as serial port namespace has DataReceived.AddHandler event subscription.



      So now it looks:



              async {

      let data_recived() =
      async{
      let! buffer = port.AsyncReadLineAsByte()
      printfn "Response from event %A" buffer
      // return buffer
      } |> fun response -> Async.RunSynchronously(response)

      port.DataReceived.AddHandler(fun _ _ -> data_recived())

      do! port.AsyncWriteLineAsByte messange
      let! response = port.AsyncReadLineAsByte()

      return response
      }


      And it works, problem is still how to return such a value from event, if I do something like:



                  let data_recived() =
      async{
      let! buffer = port.AsyncReadLineAsByte()

      printfn "Response from event %A" buffer
      return buffer
      } |> fun response -> Async.RunSynchronously(response)

      port.DataReceived.AddHandler(fun _ _ -> response = data_recived())


      Is says it expects uint and get bool










      share|improve this question
















      I am having simple read write instructions in f# to communicate between serial ports:



              async {
      do! port.AsyncWriteLineAsByte messange
      let! response = port.AsyncReadLineAsByte()

      return response
      }


      Where response is byte and method is simple as that:



          member this.AsyncReadLineAsByte() : Async<byte> =
      async {

      let buffer_ref = ref (Array.zeroCreate<byte> this.ReadBufferSize)
      let buffer = !buffer_ref

      let! read_bytes = this.BaseStream.AsyncRead(buffer, 0, this.ReadBufferSize)

      return buffer
      }


      And well it works, it sends and recives messages, there is one but in all this.
      Reading responses shold be on event of some sort. I am new to F# but i tried something like:



          async {

      let data_recived_event = port.AsyncReadLineAsByte()

      do! port.AsyncWriteLineAsByte messange

      port.DataReceived.AddHandler(data_recived_event) // it says SerialDataReciveHandler is what he expects

      let! response = ???

      return response
      }


      But no luck, documentation is rather, for f# it just specify prototype and method construction not a practical usage. I need a event and a way to return that value , is there a way?



      EDIT:



      Ive been able to add event as serial port namespace has DataReceived.AddHandler event subscription.



      So now it looks:



              async {

      let data_recived() =
      async{
      let! buffer = port.AsyncReadLineAsByte()
      printfn "Response from event %A" buffer
      // return buffer
      } |> fun response -> Async.RunSynchronously(response)

      port.DataReceived.AddHandler(fun _ _ -> data_recived())

      do! port.AsyncWriteLineAsByte messange
      let! response = port.AsyncReadLineAsByte()

      return response
      }


      And it works, problem is still how to return such a value from event, if I do something like:



                  let data_recived() =
      async{
      let! buffer = port.AsyncReadLineAsByte()

      printfn "Response from event %A" buffer
      return buffer
      } |> fun response -> Async.RunSynchronously(response)

      port.DataReceived.AddHandler(fun _ _ -> response = data_recived())


      Is says it expects uint and get bool







      f#






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 13 '18 at 15:36







      Wojciech Szabowicz

















      asked Nov 13 '18 at 13:49









      Wojciech SzabowiczWojciech Szabowicz

      766929




      766929
























          1 Answer
          1






          active

          oldest

          votes


















          2














          I'm not an expert on how serial ports work, but you can wait for an event inside async workflow using the Async.AwaitEvent operation. So, you could write something like this:



          let writeAndRead () = async {
          let port = new SerialPort("COM1")
          port.Write("TEST")
          let mutable finished = false
          while not finished do
          let! e = port.DataReceived |> Async.AwaitEvent
          let data = port.ReadExisting()
          printfn "GOT: %A" data
          finished <- data.Contains("EOF") }


          The only caveat here is that the DataReceived event might be triggered concurrently, while you are processing the received data in the body of the loop - and then you will miss the event. I'm not sure how serial ports work and whether this can actually happen, but it could lead to problems.



          To address that, you could use the BlockingQueueAgent type from F# Async Extras. This would let you implement a queue of notifications - so the DataReceived handler would add notifications to the queue and you would then read them from the queue in the loop. I have not actually tested this, but I think something like this should work:



          let writeAndRead () = async {
          let queue = BlockingQueueAgent<_>(Int32.MaxValue)
          let port = new SerialPort("COM1")
          port.DataReceived.Add(fun e -> queue.Add(e))
          port.Write("TEST")
          let mutable finished = false
          while not finished do
          let! e = queue.AsyncGet()
          let data = port.ReadExisting()
          finished <- data.Contains("EOF") }


          EDIT: Moved the queue event handler setup before writing any data to the port.






          share|improve this answer


























          • Both let! e = queue.AsyncGet() and let! e = port.DataReceived |> Async.AwaitEvent are just stuck and wait even if event is received

            – Wojciech Szabowicz
            Nov 15 '18 at 9:34











          • @WojciechSzabowicz I did an edit and moved the DataRecieved handler setup before the line that writes to the port. That could have been the cause why an event was missed. With the change, I think the events should all be recorded correctly - and none of them can be lost.

            – Tomas Petricek
            Nov 15 '18 at 10:45











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53282489%2fadd-serial-data-received-event-handler-to-f-serial-port-reader%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          I'm not an expert on how serial ports work, but you can wait for an event inside async workflow using the Async.AwaitEvent operation. So, you could write something like this:



          let writeAndRead () = async {
          let port = new SerialPort("COM1")
          port.Write("TEST")
          let mutable finished = false
          while not finished do
          let! e = port.DataReceived |> Async.AwaitEvent
          let data = port.ReadExisting()
          printfn "GOT: %A" data
          finished <- data.Contains("EOF") }


          The only caveat here is that the DataReceived event might be triggered concurrently, while you are processing the received data in the body of the loop - and then you will miss the event. I'm not sure how serial ports work and whether this can actually happen, but it could lead to problems.



          To address that, you could use the BlockingQueueAgent type from F# Async Extras. This would let you implement a queue of notifications - so the DataReceived handler would add notifications to the queue and you would then read them from the queue in the loop. I have not actually tested this, but I think something like this should work:



          let writeAndRead () = async {
          let queue = BlockingQueueAgent<_>(Int32.MaxValue)
          let port = new SerialPort("COM1")
          port.DataReceived.Add(fun e -> queue.Add(e))
          port.Write("TEST")
          let mutable finished = false
          while not finished do
          let! e = queue.AsyncGet()
          let data = port.ReadExisting()
          finished <- data.Contains("EOF") }


          EDIT: Moved the queue event handler setup before writing any data to the port.






          share|improve this answer


























          • Both let! e = queue.AsyncGet() and let! e = port.DataReceived |> Async.AwaitEvent are just stuck and wait even if event is received

            – Wojciech Szabowicz
            Nov 15 '18 at 9:34











          • @WojciechSzabowicz I did an edit and moved the DataRecieved handler setup before the line that writes to the port. That could have been the cause why an event was missed. With the change, I think the events should all be recorded correctly - and none of them can be lost.

            – Tomas Petricek
            Nov 15 '18 at 10:45
















          2














          I'm not an expert on how serial ports work, but you can wait for an event inside async workflow using the Async.AwaitEvent operation. So, you could write something like this:



          let writeAndRead () = async {
          let port = new SerialPort("COM1")
          port.Write("TEST")
          let mutable finished = false
          while not finished do
          let! e = port.DataReceived |> Async.AwaitEvent
          let data = port.ReadExisting()
          printfn "GOT: %A" data
          finished <- data.Contains("EOF") }


          The only caveat here is that the DataReceived event might be triggered concurrently, while you are processing the received data in the body of the loop - and then you will miss the event. I'm not sure how serial ports work and whether this can actually happen, but it could lead to problems.



          To address that, you could use the BlockingQueueAgent type from F# Async Extras. This would let you implement a queue of notifications - so the DataReceived handler would add notifications to the queue and you would then read them from the queue in the loop. I have not actually tested this, but I think something like this should work:



          let writeAndRead () = async {
          let queue = BlockingQueueAgent<_>(Int32.MaxValue)
          let port = new SerialPort("COM1")
          port.DataReceived.Add(fun e -> queue.Add(e))
          port.Write("TEST")
          let mutable finished = false
          while not finished do
          let! e = queue.AsyncGet()
          let data = port.ReadExisting()
          finished <- data.Contains("EOF") }


          EDIT: Moved the queue event handler setup before writing any data to the port.






          share|improve this answer


























          • Both let! e = queue.AsyncGet() and let! e = port.DataReceived |> Async.AwaitEvent are just stuck and wait even if event is received

            – Wojciech Szabowicz
            Nov 15 '18 at 9:34











          • @WojciechSzabowicz I did an edit and moved the DataRecieved handler setup before the line that writes to the port. That could have been the cause why an event was missed. With the change, I think the events should all be recorded correctly - and none of them can be lost.

            – Tomas Petricek
            Nov 15 '18 at 10:45














          2












          2








          2







          I'm not an expert on how serial ports work, but you can wait for an event inside async workflow using the Async.AwaitEvent operation. So, you could write something like this:



          let writeAndRead () = async {
          let port = new SerialPort("COM1")
          port.Write("TEST")
          let mutable finished = false
          while not finished do
          let! e = port.DataReceived |> Async.AwaitEvent
          let data = port.ReadExisting()
          printfn "GOT: %A" data
          finished <- data.Contains("EOF") }


          The only caveat here is that the DataReceived event might be triggered concurrently, while you are processing the received data in the body of the loop - and then you will miss the event. I'm not sure how serial ports work and whether this can actually happen, but it could lead to problems.



          To address that, you could use the BlockingQueueAgent type from F# Async Extras. This would let you implement a queue of notifications - so the DataReceived handler would add notifications to the queue and you would then read them from the queue in the loop. I have not actually tested this, but I think something like this should work:



          let writeAndRead () = async {
          let queue = BlockingQueueAgent<_>(Int32.MaxValue)
          let port = new SerialPort("COM1")
          port.DataReceived.Add(fun e -> queue.Add(e))
          port.Write("TEST")
          let mutable finished = false
          while not finished do
          let! e = queue.AsyncGet()
          let data = port.ReadExisting()
          finished <- data.Contains("EOF") }


          EDIT: Moved the queue event handler setup before writing any data to the port.






          share|improve this answer















          I'm not an expert on how serial ports work, but you can wait for an event inside async workflow using the Async.AwaitEvent operation. So, you could write something like this:



          let writeAndRead () = async {
          let port = new SerialPort("COM1")
          port.Write("TEST")
          let mutable finished = false
          while not finished do
          let! e = port.DataReceived |> Async.AwaitEvent
          let data = port.ReadExisting()
          printfn "GOT: %A" data
          finished <- data.Contains("EOF") }


          The only caveat here is that the DataReceived event might be triggered concurrently, while you are processing the received data in the body of the loop - and then you will miss the event. I'm not sure how serial ports work and whether this can actually happen, but it could lead to problems.



          To address that, you could use the BlockingQueueAgent type from F# Async Extras. This would let you implement a queue of notifications - so the DataReceived handler would add notifications to the queue and you would then read them from the queue in the loop. I have not actually tested this, but I think something like this should work:



          let writeAndRead () = async {
          let queue = BlockingQueueAgent<_>(Int32.MaxValue)
          let port = new SerialPort("COM1")
          port.DataReceived.Add(fun e -> queue.Add(e))
          port.Write("TEST")
          let mutable finished = false
          while not finished do
          let! e = queue.AsyncGet()
          let data = port.ReadExisting()
          finished <- data.Contains("EOF") }


          EDIT: Moved the queue event handler setup before writing any data to the port.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 15 '18 at 10:44

























          answered Nov 13 '18 at 14:08









          Tomas PetricekTomas Petricek

          199k13290464




          199k13290464













          • Both let! e = queue.AsyncGet() and let! e = port.DataReceived |> Async.AwaitEvent are just stuck and wait even if event is received

            – Wojciech Szabowicz
            Nov 15 '18 at 9:34











          • @WojciechSzabowicz I did an edit and moved the DataRecieved handler setup before the line that writes to the port. That could have been the cause why an event was missed. With the change, I think the events should all be recorded correctly - and none of them can be lost.

            – Tomas Petricek
            Nov 15 '18 at 10:45



















          • Both let! e = queue.AsyncGet() and let! e = port.DataReceived |> Async.AwaitEvent are just stuck and wait even if event is received

            – Wojciech Szabowicz
            Nov 15 '18 at 9:34











          • @WojciechSzabowicz I did an edit and moved the DataRecieved handler setup before the line that writes to the port. That could have been the cause why an event was missed. With the change, I think the events should all be recorded correctly - and none of them can be lost.

            – Tomas Petricek
            Nov 15 '18 at 10:45

















          Both let! e = queue.AsyncGet() and let! e = port.DataReceived |> Async.AwaitEvent are just stuck and wait even if event is received

          – Wojciech Szabowicz
          Nov 15 '18 at 9:34





          Both let! e = queue.AsyncGet() and let! e = port.DataReceived |> Async.AwaitEvent are just stuck and wait even if event is received

          – Wojciech Szabowicz
          Nov 15 '18 at 9:34













          @WojciechSzabowicz I did an edit and moved the DataRecieved handler setup before the line that writes to the port. That could have been the cause why an event was missed. With the change, I think the events should all be recorded correctly - and none of them can be lost.

          – Tomas Petricek
          Nov 15 '18 at 10:45





          @WojciechSzabowicz I did an edit and moved the DataRecieved handler setup before the line that writes to the port. That could have been the cause why an event was missed. With the change, I think the events should all be recorded correctly - and none of them can be lost.

          – Tomas Petricek
          Nov 15 '18 at 10:45


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53282489%2fadd-serial-data-received-event-handler-to-f-serial-port-reader%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Full-time equivalent

          さくらももこ

          13 indicted, 8 arrested in Calif. drug cartel investigation