Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

NOISSUE - Add Read Property and WHOIS support #1

Open
wants to merge 24 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 116 additions & 0 deletions example/readProperty/readProperty.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package main

import (
"fmt"
"log"
"net"
"time"

"github.com/absmach/bacnet/pkg/bacnet"
"github.com/absmach/bacnet/pkg/encoding"
"github.com/absmach/bacnet/pkg/transport"
)

func main() {
netType := encoding.IPV4
/*deviceID := bacnet.ObjectIdentifier{
Type: encoding.AnalogInput,
Instance: 101,
}*/
destination := bacnet.NewBACnetAddress(0, nil, "127.0.0.6:47809", &netType)
npdu := bacnet.NewNPDU(destination, nil, nil, nil)
npdu.Control.SetDataExpectingReply(true)
npdu.Control.SetNetworkPriority(bacnet.NormalMessage)

npduBytes, err := npdu.Encode()
if err != nil {
log.Fatal(err)
}

apdu := bacnet.APDU{
PduType: bacnet.PDUTypeConfirmedServiceRequest,
ServiceChoice: byte(bacnet.ReadProperty),
SegmentedResponseAccepted: false,
MaxSegmentsAccepted: bacnet.BacnetMaxSegments(encoding.NoSegmentation),
//MaxApduLengthAccepted: bacnet.MaxAPDU1476,
InvokeID: 0,
}

req := bacnet.ReadPropertyRequest{
PropertyIdentifier: encoding.PresentValue,
ObjectIdentifier: &bacnet.ObjectIdentifier{Type: encoding.AnalogInput, Instance: 10},
}

mes := append(npduBytes, apdu.Encode()...)
mes = append(mes, req.Encode()...)

blvc := bacnet.NewBVLC(transport.IP)
blvcBytes := blvc.Encode(bacnet.BVLCOriginalBroadcastNPDU, uint16(len(mes)+4))
message := append(blvcBytes, mes...)

// Define the BACnet broadcast address (255.255.255.255:47808)
remoteAddr, err := net.ResolveUDPAddr("udp", "127.0.0.6:47809")
SammyOina marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
fmt.Println("Error resolving remote address:", err)
return
}

localAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
if err != nil {
fmt.Println("Error: ", err)
return
}

// Create a UDP connectionBACnetAddress
conn, err := net.DialUDP("udp", localAddr, remoteAddr)
if err != nil {
fmt.Println("Error creating UDP connection:", err)
return
}
defer conn.Close()

// Send the WhoIsRequest packet
_, err = conn.Write(message)
if err != nil {
log.Fatal("Error sending WhoIsRequest:", err)
}

// Wait for responses
buffer := make([]byte, 1500)
conn.SetReadDeadline(time.Now().Add(5 * time.Second)) // Set a timeout for responses

for {
//conn.ReadFromUDPAddrPort()
n, _, err := conn.ReadFromUDP(buffer)
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
// Timeout reached, no more responses
log.Println("No more responses received.")
break
}
log.Println("Error reading response:", err)
break
}

// Process the response (you'll need to parse BACnet responses here)
response := buffer[:n]
blvc := bacnet.BVLC{BVLLTypeBACnetIP: 0x81}
SammyOina marked this conversation as resolved.
Show resolved Hide resolved
headerLength, function, msgLength, err := blvc.Decode(response, 0)
if err != nil {
log.Fatal(err)
}
fmt.Printf("headerLength %v BVLCfunction %v msgLen %v\n", headerLength, function, msgLength)
fmt.Println("blvc", blvc)
npdu := bacnet.NPDU{Version: 1}
npduLen := npdu.Decode(response, headerLength)
fmt.Println("npdu", npdu)
apdu := bacnet.APDU{}
apduLen := apdu.Decode(response, headerLength+npduLen)
fmt.Println("apdu", apdu)
readPropACK := bacnet.ReadPropertyACK{}
if _, err = readPropACK.Decode(response, headerLength+npduLen+apduLen-2, len(response)); err != nil {
log.Fatal(err)
}
fmt.Println("readprop", readPropACK)
}
}
123 changes: 123 additions & 0 deletions example/whoIs/whois.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
package main

import (
"fmt"
"log"
"net"
"time"

"github.com/absmach/bacnet/pkg/bacnet"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The package name seems odd. bacnet/pkg/bacnet. Why not move bacnet to the root of the project as this repository is bacnet package

"github.com/absmach/bacnet/pkg/encoding"
"github.com/absmach/bacnet/pkg/transport"
"github.com/absmach/bacnet/pkg/transport/udp"
)

func main() {

var highLimit, lowLimit uint32 = 4000000, 0
SammyOina marked this conversation as resolved.
Show resolved Hide resolved
req := bacnet.WhoIs{
HighLimit: &highLimit,
LowLimit: &lowLimit,
}
whoisBytes := req.Encode()

broads, err := udp.GetBroadcastAddress("127.0.0.6", 47809)
if err != nil {
log.Fatalf("failed to encode npdu with error %v", err)
}
netType := encoding.IPV4
broads = *bacnet.NewBACnetAddress(0xFFFF, nil, "127.0.0.255:47809", &netType)

npdu := bacnet.NewNPDU(&broads, nil, nil, nil)
npdu.Control.SetNetworkPriority(bacnet.NormalMessage)
npduBytes, err := npdu.Encode()
if err != nil {
log.Fatalf("failed to encode npdu with error %v", err)
}

apdu := bacnet.APDU{
PduType: bacnet.PDUTypeUnconfirmedServiceRequest,
ServiceChoice: byte(bacnet.ServiceChoiceWhoIs),
}

apduBytes := apdu.Encode()

mes := append(npduBytes, apduBytes...)
mes = append(mes, whoisBytes...)

blvc := bacnet.NewBVLC(transport.IP)
blvcBytes := blvc.Encode(bacnet.BVLCOriginalBroadcastNPDU, uint16(len(mes)+4))
message := append(blvcBytes, mes...)

// Define the BACnet broadcast address (255.255.255.255:47808)
remoteAddr, err := net.ResolveUDPAddr("udp", "127.0.0.6:47809")
SammyOina marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
fmt.Println("Error resolving remote address:", err)
return
}

localAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
if err != nil {
fmt.Println("Error: ", err)
return
}

// Create a UDP connectionBACnetAddress
conn, err := net.DialUDP("udp", localAddr, remoteAddr)
if err != nil {
fmt.Println("Error creating UDP connection:", err)
return
}
defer conn.Close()

// Send the WhoIsRequest packet
_, err = conn.Write(message)
if err != nil {
log.Fatal("Error sending WhoIsRequest:", err)
}

// Wait for responses
buffer := make([]byte, 1500)
SammyOina marked this conversation as resolved.
Show resolved Hide resolved
conn.SetReadDeadline(time.Now().Add(5 * time.Second)) // Set a timeout for responses
SammyOina marked this conversation as resolved.
Show resolved Hide resolved

for {
n, _, err := conn.ReadFromUDP(buffer)
if err != nil {
if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
// Timeout reached, no more responses
log.Println("No more responses received.")
break
}
log.Println("Error reading response:", err)
break
}

// Process the response (you'll need to parse BACnet responses here)
response := buffer[:n]
log.Printf("Received response: %X\n", response)
blvc := bacnet.BVLC{BVLLTypeBACnetIP: 0x81}
SammyOina marked this conversation as resolved.
Show resolved Hide resolved
headerLength, function, msgLength, err := blvc.Decode(response, 0)
if err != nil {
log.Fatal(err)
}
fmt.Println(response)
fmt.Printf("headerLength %v BVLCfunction %v msgLen %v\n", headerLength, function, msgLength)
fmt.Println("blvc", blvc)
fmt.Println(response[headerLength:])
npdu := bacnet.NPDU{Version: 1}
npduLen := npdu.Decode(response, headerLength)
fmt.Println("npdu", npdu)
fmt.Println(response[headerLength+npduLen:])
apdu := bacnet.APDU{}
apduLen := apdu.Decode(response, headerLength+npduLen)
fmt.Println("apdu", apdu)
fmt.Println(response[headerLength+npduLen+apduLen:])
iam := bacnet.IAmRequest{}
iamLen, err := iam.Decode(response, headerLength+npduLen+apduLen)
if err != nil {
log.Fatal(err)
}
fmt.Println("iam", iam)
fmt.Println(response[headerLength+npduLen+apduLen+iamLen:])
}
}
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/absmach/bacnet

go 1.21.0
Empty file added go.sum
Empty file.
52 changes: 52 additions & 0 deletions internal/bitarray.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package internal

import "errors"

var errBitArrayLen = errors.New("bit array length must be 8 to convert to byte")

type BitArray struct {
bits []bool
}

func NewBitArray(length int) *BitArray {
return &BitArray{
bits: make([]bool, length),
}
}

func (ba *BitArray) Set(index int, value bool) {
if index >= 0 && index < len(ba.bits) {
ba.bits[index] = value
}
}

func (ba *BitArray) Get(index int) bool {
if index >= 0 && index < len(ba.bits) {
return ba.bits[index]
}
return false
}

func (ba *BitArray) ToByte() (byte, error) {
// Ensure the length of the bit array is 8 to convert to a byte.
if len(ba.bits) != 8 {
return 0, errBitArrayLen
}

var byteValue byte
for j := 0; j < 8; j++ {
SammyOina marked this conversation as resolved.
Show resolved Hide resolved
if ba.bits[j] {
byteValue |= 1 << uint(7-j)
}
}

return byteValue, nil
}

func NewBitArrayFromByte(byteValue byte) *BitArray {
bitArray := NewBitArray(8)
for j := 0; j < 8; j++ {
bitArray.Set(j, byteValue&(1<<uint(7-j)) != 0)
}
return bitArray
}
Loading