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 23 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
121 changes: 121 additions & 0 deletions example/readProperty/readProperty.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
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
destination := bacnet.NewAddress(0, nil, "127.0.0.6:47809", &netType)
SammyOina marked this conversation as resolved.
Show resolved Hide resolved
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.MaxSegments(encoding.NoSegmentation),
InvokeID: 0,
}

apduBytes, err := apdu.Encode()
if err != nil {
log.Fatal(err)
}

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

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

blvc, err := bacnet.NewBVLC(transport.IP)
if err != nil {
log.Fatal(err)
}
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 {
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, err := apdu.Decode(response, headerLength+npduLen)
if err != nil {
log.Fatal(err)
}
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)
}
}
125 changes: 125 additions & 0 deletions example/whoIs/whois.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
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"
)

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()

netType := encoding.IPV4
broads := bacnet.NewAddress(0xFFFF, nil, "127.0.0.255:47809", &netType)
SammyOina marked this conversation as resolved.
Show resolved Hide resolved

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, err := apdu.Encode()
if err != nil {
log.Fatal(err)
}

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

blvc, err := bacnet.NewBVLC(transport.IP)
if err != nil {
log.Fatal(err)
}
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 {
log.Fatal("Error resolving remote address:", err)
}

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

// Create a UDP connectionBACnetAddress
conn, err := net.DialUDP("udp", localAddr, remoteAddr)
if err != nil {
log.Fatal("Error creating UDP connection:", err)
}
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, err := apdu.Decode(response, headerLength+npduLen)
if err != nil {
log.Fatal(err)
}
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.
65 changes: 65 additions & 0 deletions internal/bitarray.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package internal

import "errors"

var (
errBitArrayLen = errors.New("bit array length must be 8 to convert to byte")
errOutOfBounds = errors.New("index is out of the range for the bitarray")
)

// BitArray defines an array of bits.
type BitArray struct {
bits []bool
}

// Creates a new bit array for the provided length.
func NewBitArray(length int) *BitArray {
return &BitArray{
bits: make([]bool, length),
}
}

// Set sets the value of the bit array at the given index and value.
func (ba *BitArray) Set(index int, value bool) error {
if index >= 0 && index < len(ba.bits) {
ba.bits[index] = value
return nil
}
return errOutOfBounds
}

// Get returns the the value of the bit array at the given index.
func (ba *BitArray) Get(index int) (bool, error) {
if index >= 0 && index < len(ba.bits) {
return ba.bits[index], nil
}
return false, errOutOfBounds
}

// ToByte converts bitarray to byte value.
// TODO return byte array.
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
}

// NewBitArrayFromByte creates a new bit array from the given byte.
// TODO check length of incoming byte.
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