Created
April 5, 2021 08:05
-
-
Save hodzanassredin/7cdb602cb392d9496a5bdb34901157c5 to your computer and use it in GitHub Desktop.
reading sensor data from air master 2 air quality monitor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#r "nuget: FSharp.Charting, 2.1.0" | |
#r "nuget: System.Windows.Forms, 4.0.0" | |
#r "System.Windows.Forms.DataVisualization" | |
#r "nuget: FSharp.Control.Reactive, 5.0.2" | |
open System | |
open FSharp.Control.Reactive | |
open FSharp.Charting | |
open System.IO.Ports | |
type Sensors = { | |
time: int64; | |
pm25: double; | |
pm10: double; | |
hcho: double; | |
tvoc: double; | |
co2: double; | |
temp: double; | |
humidity: double; | |
} | |
let event1 = new Event<Sensors>() | |
let port = new SerialPort("COM3", 19200, Parity.None, 8, StopBits.One); | |
port.Open() | |
let read (buff:byte[]) pos = double(buff.[pos]) * 255.0 + double(buff.[pos+1]) | |
let hexCodes = "55 CD 47 00 00 00 00 00 00 01 69 0D 0A".Split(' ') |> Seq.ofArray | |
let reqArr = hexCodes|>Seq.map(fun x-> Byte.Parse(x, System.Globalization.NumberStyles.HexNumber))|> Seq.toArray | |
let sendReq () = | |
printfn "Sending req" | |
port.Write(reqArr, 0, reqArr.Length) |> ignore | |
let timer = new System.Timers.Timer(5000.0) | |
timer.Elapsed.Add (fun _ -> sendReq() ) | |
//timer.AutoReset = false | |
timer.Start() | |
let buff : byte[] = Array.zeroCreate 40 | |
let rec readPort pos = | |
let expectedCount = buff.Length - pos | |
let count = port.Read(buff, pos, expectedCount) | |
//printfn "Recieved expected %d real %d" expectedCount count | |
if count = expectedCount then () | |
else readPort (pos + count) | |
let port_DataReceived (sender : obj) (e : SerialDataReceivedEventArgs) = | |
readPort 0 | |
printfn "Recieved packet" | |
let status = { | |
time = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); | |
pm25 = read buff 1; | |
pm10 = read buff 3; | |
hcho = (read buff 5) / 1000.0; | |
tvoc = (read buff 7) /1000.0; | |
co2 = (read buff 9); | |
temp = (read buff 11) / 100.0; | |
humidity = (read buff 13) / 100.0; | |
} | |
event1.Trigger(status) | |
//timer.Start() | |
port.DataReceived.AddHandler <| new SerialDataReceivedEventHandler(port_DataReceived); | |
let ev = event1.Publish |> Observable.map (fun x-> x) | |
ev.Subscribe(fun x-> printfn "status %A" x) | |
let c = LiveChart.FastLineIncremental(ev |> Observable.map (fun x-> (x.time, x.co2)), Name="co2").WithXAxis(Enabled=true).WithYAxis(Enabled=true, Min = 400.0, Max = 1100.0) | |
c.ShowChart() | |
let c2 = LiveChart.FastLineIncremental(ev|> Observable.map (fun x-> (x.time, x.humidity)),Name="humidity").WithXAxis(Enabled=true).WithYAxis(Enabled=true) | |
c2.ShowChart() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment