Sub Process_Globals
Public Serial1 As Serial
Private rfid As MFRC522
Private bc As ByteConverter
Dim d1 As D1Pins
Dim credit,deduct,balance As Double
Dim authenticated,updated As Boolean
Dim card_type As Byte
Dim astream As AsyncStreams
Dim mode As Int
'RST->D4
'SDA(SS)->D3
'MOSI->D7
'MISO->D6
'SCK->D5
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
Log("AppStart")
rfid.Initialize(d1.D3, d1.D4, "rfid_CardPresent")
astream.Initialize(Serial1.Stream, "astream_newdata", Null)
rfid.LogVersion
updated=False
mode=0
End Sub
Sub rfid_CardPresent (uid() As Byte, CardType As Byte )
GlobalStore.Put(0,uid)
card_type=CardType
Select mode
Case 0
Log("UID: ", bc.HexFromBytes(uid))
Log("Type: ", CardType, ", Is it Mifare: ", rfid.IsMifare)
Dim txt As String
If rfid.IsMifare Then
authenticated=card_authenticate(12)
If authenticated Then
txt=card_read(12)
Log(txt)
'astream.Write(bc.StringToBytes(txt))
credit=txt
End If
Else
Log("Failed to read")
End If
Case 1
Log("UID: ", bc.HexFromBytes(uid))
If rfid.IsMifare Then
card_authenticate(12)
Dim balance_txt As String
balance_txt=balance
Log(balance_txt)
card_write(12,balance_txt)
mode=0
Else
Log("Failed to read")
End If
End Select
End Sub
Sub card_read(sector As Int) As String
Dim msg As String
Dim buffer(18) As Byte
If rfid.MifareRead(sector, buffer) > 0 Then 'buffer size must be 18 bytes or more
Dim read_buffer(8) As Byte
For i=0 To 7
read_buffer(i)=buffer(i)
Next
msg=bc.stringFromBytes(read_buffer)
Else
msg=""
End If
Return msg
End Sub
Sub card_write(sector As Int,msg As String)
Dim buffer(18) As Byte
msg=JoinStrings(Array As String(msg," "))
'Log(msg)
buffer=bc.stringToBytes(msg)
Log("Write:", rfid.MifareWrite(sector, buffer))
End Sub
Sub card_authenticate(sector As Int) As Boolean
If rfid.MifareAuthenticate(sector) = False Then
Log("Failed to authenticate")
authenticated=False
Else
authenticated=True
End If
Return authenticated
End Sub
Sub astream_newdata (Buffer() As Byte)
Dim msg As String
msg=bc.stringFromBytes(Buffer)
Log(msg)
deduct=msg
balance=credit-deduct
mode=1
rfid_CardPresent(GlobalStore.Slot0,card_type)
End Sub