public int Send(byte[] buffer, int offset, int data_length, BacnetAddress address, bool wait_for_transmission, int timeout) { int hdr_offset = 0; for (int i = 0; i < 6; i++) { buffer[hdr_offset++] = address.adr[i]; } // write the source mac address bytes for (int i = 0; i < 6; i++) { buffer[hdr_offset++] = _deviceMac[i]; } // the next 2 bytes are used for the packet length buffer[hdr_offset++] = (byte)(((data_length + 3) & 0xFF00) >> 8); buffer[hdr_offset++] = (byte)((data_length + 3) & 0xFF); // DSAP and SSAP buffer[hdr_offset++] = 0x82; buffer[hdr_offset++] = 0x82; // LLC control field buffer[hdr_offset] = 0x03; lock (_device) { _device.SendPacket(buffer, data_length + HeaderLength); } return(data_length + HeaderLength); }
public TrendLogDisplay(BacnetClient comm, BacnetAddress adr, BacnetObjectId object_id) { InitializeComponent(); this.comm = comm; this.adr = adr; this.object_id = object_id; }
/*****************************************************************************************************/ static void handler_OnSubscribeCOV(BacnetClient sender, BacnetAddress adr, byte invoke_id, uint subscriberProcessIdentifier, BacnetObjectId monitoredObjectIdentifier, bool cancellationRequest, bool issueConfirmedNotifications, uint lifetime, BacnetMaxSegments max_segments) { lock (device) { BaCSharpObject bacobj = device.FindBacnetObject(monitoredObjectIdentifier); if (bacobj != null) { //create Subscription sub = SubscriptionManager.HandleSubscriptionRequest(sender, adr, invoke_id, subscriberProcessIdentifier, monitoredObjectIdentifier, (uint)BacnetPropertyIds.PROP_ALL, cancellationRequest, issueConfirmedNotifications, lifetime, 0); //send confirm sender.SimpleAckResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_SUBSCRIBE_COV, invoke_id); //also send first values if (!cancellationRequest) { System.Threading.ThreadPool.QueueUserWorkItem((o) => { IList <BacnetPropertyValue> values; if (bacobj.ReadPropertyAll(sender, adr, out values)) { sender.Notify(adr, sub.subscriberProcessIdentifier, deviceId, sub.monitoredObjectIdentifier, (uint)sub.GetTimeRemaining(), sub.issueConfirmedNotifications, values); } }, null); } } else { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_SUBSCRIBE_COV, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_OTHER); } } }
public static LightSceneEntity GetConfLightingScene(int?deviceID) { LightSceneEntity lightSceneEntity = new LightSceneEntity(); var bacnetDeviceFromDB = lutronEntities.BACnetDevices .Where(x => x.device_id == deviceID && x.object_instance == (int?)LutronObjectType.Lighting_Scene) .Select(x => x).FirstOrDefault(); IList <BacnetValue> bacnetValueList; BacnetAddress bacnetAddress; bacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, bacnetDeviceFromDB.network_id); bacnetAddress.RoutedSource = new BacnetAddress(BacnetAddressTypes.IP, bacnetDeviceFromDB.routed_source, (ushort)bacnetDeviceFromDB.routed_net); if (bacNetClient == null) { bacNetClient = BackNetClientInit.NewBackNetClient(); } bacNetClient.ReadPropertyRequest(bacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_MULTI_STATE_VALUE, (uint)LutronObjectType.Lighting_Scene), BacnetPropertyIds.PROP_PRESENT_VALUE, out bacnetValueList); if (bacnetValueList != null && bacnetValueList.Count > 0) { lightSceneEntity.Value = Convert.ToString(bacnetValueList.FirstOrDefault().Value); } lightSceneEntity.DeviceID = (Int32)deviceID; return(lightSceneEntity); }
public int Send(byte[] buffer, int offset, int data_length, BacnetAddress address, bool wait_for_transmission, int timeout) { if (m_TS == -1) { throw new Exception("Source address must be set up before sending messages"); } //add to queue BacnetNpduControls function = NPDU.DecodeFunction(buffer, offset); BacnetMstpFrameTypes frame_type = (function & BacnetNpduControls.ExpectingReply) == BacnetNpduControls.ExpectingReply ? BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_EXPECTING_REPLY : BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_NOT_EXPECTING_REPLY; byte[] copy = new byte[data_length + MSTP.MSTP_HEADER_LENGTH + 2]; Array.Copy(buffer, offset, copy, MSTP.MSTP_HEADER_LENGTH, data_length); MessageFrame f = new MessageFrame(frame_type, address.adr[0], copy, data_length); lock (m_send_queue) m_send_queue.AddLast(f); if (m_reply == null) { m_reply = f; m_reply_mutex.Set(); } //wait for message to be sent if (wait_for_transmission) { if (!f.send_mutex.WaitOne(timeout)) { return(-ETIMEDOUT); } } return(data_length); }
/*****************************************************************************************************/ static void handler_OnWritePropertyRequest(BacnetClient sender, BacnetAddress adr, byte invoke_id, BacnetObjectId object_id, BacnetPropertyValue value, BacnetMaxSegments max_segments) { lock (device) { BaCSharpObject bacobj = device.FindBacnetObject(object_id); if (bacobj != null) { ErrorCodes error = bacobj.WritePropertyValue(sender, adr, value, true); if (error == ErrorCodes.Good) { sender.SimpleAckResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROPERTY, invoke_id); } else { BacnetErrorCodes bacEr = BacnetErrorCodes.ERROR_CODE_OTHER; if (error == ErrorCodes.WriteAccessDenied) { bacEr = BacnetErrorCodes.ERROR_CODE_WRITE_ACCESS_DENIED; } if (error == ErrorCodes.OutOfRange) { bacEr = BacnetErrorCodes.ERROR_CODE_VALUE_OUT_OF_RANGE; } sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROPERTY, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, bacEr); } } else { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_READ_PROPERTY, invoke_id, BacnetErrorClasses.ERROR_CLASS_OBJECT, BacnetErrorCodes.ERROR_CODE_UNKNOWN_OBJECT); } } }
void handler_OnDeleteObjectRequest(BacnetClient sender, BacnetAddress adr, byte invoke_id, BacnetObjectId object_id, BacnetMaxSegments max_segments) { //check if exists; if doesn't send error Unknown_Object if (device.FindBacnetObject(object_id) == null) { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_CREATE_OBJECT, invoke_id, BacnetErrorClasses.ERROR_CLASS_OBJECT, BacnetErrorCodes.ERROR_CODE_UNKNOWN_OBJECT); return; } // check if objecttype is allowed to be deleted, like for example Device switch() for adding more types which cant be deleted // Device not removable, no need to check switch (object_id.type) { case BacnetObjectTypes.OBJECT_ACCESS_DOOR: // just to shows how to do sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_CREATE_OBJECT, invoke_id, BacnetErrorClasses.ERROR_CLASS_OBJECT, BacnetErrorCodes.ERROR_CODE_OBJECT_DELETION_NOT_PERMITTED); return; default: break; } //remove from device and send ACK normally there should be no error!!!!!!! if (device.RemoveBacnetObject(object_id) == true) { sender.SimpleAckResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_DELETE_OBJECT, invoke_id); } else { Console.WriteLine("unknown Error while deleting object!"); } return; }
public int Send(byte[] buffer, int offset, int data_length, BacnetAddress address, bool wait_for_transmission, int timeout) { BacnetPtpFrameTypes frame_type = BacnetPtpFrameTypes.FRAME_TYPE_DATA0; if (m_sequence_counter) { frame_type = BacnetPtpFrameTypes.FRAME_TYPE_DATA1; } m_sequence_counter = !m_sequence_counter; //add header int full_length = PTP.Encode(buffer, offset - PTP.PTP_HEADER_LENGTH, frame_type, data_length); //wait for send allowed if (!m_may_send.WaitOne(timeout)) { return(-BacnetMstpProtocolTransport.ETIMEDOUT); } //debug if (StateLogging) { Trace.WriteLine(" " + frame_type, null); } //send SendWithXonXoff(buffer, offset - HeaderLength, full_length); return(data_length); }
private void m_comm_OnSimpleAck(BacnetClient sender, BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service, byte invoke_id, byte[] data, int data_offset, int data_length) { if (invoke_id == m_wait_invoke_id) { ((System.Threading.ManualResetEvent)AsyncWaitHandle).Set(); } }
public bool ReadPropertyAll(BacnetClient sender, BacnetAddress adr, out IList <BacnetPropertyValue> values) { if (AllMyProperties == null) { AllMyProperties = new List <BacnetPropertyReference>(); MethodInfo[] allmethod = this.GetType().GetMethods(); // all the methods in this class foreach (MethodInfo m in allmethod) { uint PropId = BacnetMethodNametoId(m.Name); // looking for all with a 'Bacnet name' if (PropId < (uint)BacnetPropertyIds.MAX_BACNET_PROPERTY_ID) { BacnetPropertyReference propref = new BacnetPropertyReference(PropId, System.IO.BACnet.Serialize.ASN1.BACNET_ARRAY_ALL); // could be get_ and get2_, only one is required if (!AllMyProperties.Contains(propref)) { AllMyProperties.Add(propref); } } } } return(ReadPropertyMultiple(sender, adr, AllMyProperties, out values)); }
private void m_comm_OnError(BacnetClient sender, BacnetAddress adr, BacnetPduTypes type, BacnetConfirmedServices service, byte invoke_id, BacnetErrorClasses error_class, BacnetErrorCodes error_code, byte[] buffer, int offset, int length) { if (invoke_id == m_wait_invoke_id) { Error = new Exception("Error from device: " + error_class + " - " + error_code); } }
/*****************************************************************************************************/ static void handler_OnReadPropertyRequest(BacnetClient sender, BacnetAddress adr, byte invoke_id, BacnetObjectId object_id, BacnetPropertyReference property, BacnetMaxSegments max_segments) { lock (device) { BaCSharpObject bacobj = device.FindBacnetObject(object_id); if (bacobj != null) { IList <BacnetValue> value; ErrorCodes error = bacobj.ReadPropertyValue(sender, adr, property, out value); if (error == ErrorCodes.Good) { sender.ReadPropertyResponse(adr, invoke_id, sender.GetSegmentBuffer(max_segments), object_id, property, value); } else if (error == ErrorCodes.IndexNotExist) { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_READ_PROPERTY, invoke_id, BacnetErrorClasses.ERROR_CLASS_PROPERTY, BacnetErrorCodes.ERROR_CODE_INVALID_ARRAY_INDEX); } else { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_READ_PROPERTY, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_UNKNOWN_PROPERTY); } } else { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_READ_PROPERTY, invoke_id, BacnetErrorClasses.ERROR_CLASS_OBJECT, BacnetErrorCodes.ERROR_CODE_UNKNOWN_OBJECT); } } }
private void handler_OnReadPropertyRequest(BacnetClient sender, BacnetAddress adr, byte invoke_id, BacnetObjectId object_id, BacnetPropertyReference property, BacnetMaxSegments max_segments) { lock (m_storage) { _logger.LogInformation($"Read property request for {property.ToString()} of {object_id.ToString()} from {adr.ToString()}."); try { IList <BacnetValue> value; DeviceStorage.ErrorCodes code = m_storage.ReadProperty(object_id, (BacnetPropertyIds)property.propertyIdentifier, property.propertyArrayIndex, out value); if (code == DeviceStorage.ErrorCodes.Good) { sender.ReadPropertyResponse(adr, invoke_id, sender.GetSegmentBuffer(max_segments), object_id, property, value); } else { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_READ_PROPERTY, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_OTHER); } } catch (Exception) { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_READ_PROPERTY, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_OTHER); } } }
public BVLCV6(BacnetIpV6UdpProtocolTransport Transport, int VMAC) { MyTransport = Transport; BroadcastAdd = MyTransport.GetBroadcastAddress(); if (VMAC == -1) { RandomVmac = true; new Random().NextBytes(this.VMAC); this.VMAC[0] = (byte)((this.VMAC[0] & 0x7F) | 0x40); // ensure 01xxxxxx on the High byte // Open with default interface specified, cannot send it or // it will generate an uncheckable continuous local loopback if (!MyTransport.LocalEndPoint.ToString().Contains("[::]")) { SendAddressResolutionRequest(this.VMAC); } else { RandomVmac = false; // back to false avoiding loop back } } else // Device Id is the Vmac Id { this.VMAC[0] = (byte)((VMAC >> 16) & 0x3F); // ensure the 2 high bits are 0 on the High byte this.VMAC[1] = (byte)((VMAC >> 8) & 0xFF); this.VMAC[2] = (byte)(VMAC & 0xFF); // unicity is guaranteed by the end user ! } }
/// <summary> /// Toggle Lighting State /// </summary> /// <param name="fiDeviceID"></param> /// <param name="fbToggleStatus"></param> private void ToggleLutronLight(int fiDeviceID, bool fbToggleStatus) { using (var loESDLutronEntities = new ESDLutronEntities()) { var loBACnetDeviceDetail = loESDLutronEntities.BACnetDevices .Where(x => x.device_id == fiDeviceID && x.object_instance == (int?)LutronObjectType.Lighting_State) .Select(x => x).FirstOrDefault(); if (loBACnetDeviceDetail != null && loBACnetDeviceDetail.object_instance != null) { BacnetAddress loBacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.network_id); loBacnetAddress.RoutedSource = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.routed_source, (ushort)loBACnetDeviceDetail.routed_net); IList <BacnetValue> loBacnetValueList; moBacnetClient.ReadPropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_BINARY_VALUE, (uint)loBACnetDeviceDetail.object_instance), BacnetPropertyIds.PROP_PRESENT_VALUE, out loBacnetValueList); BacnetValue loBacnetNewValue = new BacnetValue(BacnetApplicationTags.BACNET_APPLICATION_TAG_ENUMERATED, fbToggleStatus == true ? 1 : 0); BacnetValue[] loWriteValue = { loBacnetNewValue }; moBacnetClient.WritePropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_BINARY_VALUE, (uint)loBACnetDeviceDetail.object_instance), BacnetPropertyIds.PROP_PRESENT_VALUE, loWriteValue); //BacnetValue[] loNewBacnetValue = { new BacnetValue(Convert.ToSingle(111)) }; ////bacnet_client.WritePropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_BINARY_VALUE, (uint)loBACnetDeviceDetail.object_instance), BacnetPropertyIds.PROP_ACTION, loNewBacnetValue); ////bacnet_client.WritePropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_INPUT, 0), BacnetPropertyIds.PROP_PRESENT_VALUE, loNewBacnetValue); //bacnet_client.WritePropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_INPUT, 0), BacnetPropertyIds.PROP_PRESENT_VALUE, loNewBacnetValue); } } //bool ret = WriteScalarValue(1, new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_VALUE, 2), BacnetPropertyIds.PROP_PRESENT_VALUE, loNewValue); }
private static void OnDeviceCommunicationControl(BacnetClient sender, BacnetAddress adr, byte invoke_id, uint time_duration, uint enable_disable, string password, BacnetMaxSegments max_segments) { switch (enable_disable) { case 0: Trace.TraceInformation("Enable communication? Sure!"); sender.SimpleAckResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_DEVICE_COMMUNICATION_CONTROL, invoke_id); break; case 1: Trace.TraceInformation("Disable communication? ... smile and wave (ignored)"); sender.SimpleAckResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_DEVICE_COMMUNICATION_CONTROL, invoke_id); break; case 2: Trace.TraceWarning("Disable initiation? I don't think so!"); sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_DEVICE_COMMUNICATION_CONTROL, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_OTHER); break; default: Trace.TraceError("Now, what is this device_communication code: " + enable_disable + "!!!!"); sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_DEVICE_COMMUNICATION_CONTROL, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_OTHER); break; } }
private static void OnSubscribeCOV(BacnetClient sender, BacnetAddress adr, byte invoke_id, uint subscriberProcessIdentifier, BacnetObjectId monitoredObjectIdentifier, bool cancellationRequest, bool issueConfirmedNotifications, uint lifetime, BacnetMaxSegments max_segments) { lock (m_lockObject) { try { //create Subscription sub = HandleSubscriptionRequest(sender, adr, invoke_id, subscriberProcessIdentifier, monitoredObjectIdentifier, (uint)BacnetPropertyIds.PROP_ALL, cancellationRequest, issueConfirmedNotifications, lifetime, 0); //send confirm sender.SimpleAckResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_SUBSCRIBE_COV, invoke_id); //also send first values if (!cancellationRequest) { System.Threading.ThreadPool.QueueUserWorkItem((o) => { IList <BacnetPropertyValue> values; if (m_storage.ReadPropertyAll(sub.monitoredObjectIdentifier, out values)) { if (!sender.Notify(adr, sub.subscriberProcessIdentifier, m_storage.DeviceId, sub.monitoredObjectIdentifier, (uint)sub.GetTimeRemaining(), sub.issueConfirmedNotifications, values)) { Trace.TraceError("Couldn't send notify"); } } }, null); } } catch (Exception) { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_SUBSCRIBE_COV, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_OTHER); } } }
/// <summary> /// Get current light state for device /// </summary> /// <param name="fiDeviceID"></param> /// <returns></returns> private bool GetLutronLightState(Int32 fiDeviceID) { IList <BacnetValue> loBacnetValueList; using (var loESDLutronEntities = new ESDLutronEntities()) { var loBACnetDeviceDetail = loESDLutronEntities.BACnetDevices .Where(x => x.device_id == fiDeviceID && x.object_type.ToUpper() == LutronFloorObjectType.Lighting_State) .Select(x => x).FirstOrDefault(); BacnetAddress loBacnetAddress; loBacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.network_id); loBacnetAddress.RoutedSource = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.routed_source, (ushort)loBACnetDeviceDetail.routed_net); moBacnetClient.ReadPropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_BINARY_VALUE, (uint)loBACnetDeviceDetail.object_instance), BacnetPropertyIds.PROP_PRESENT_VALUE, out loBacnetValueList); } if (loBacnetValueList != null && loBacnetValueList.Count > 0) { return(Convert.ToBoolean(Convert.ToInt32(loBacnetValueList[0].Value))); } else { return(false); } }
/*****************************************************************************************************/ /* This is the objective of this sample ! */ /*****************************************************************************************************/ static void handler_OnEventNotify(BacnetClient sender, BacnetAddress adr, byte invoke_id, BacnetEventNotificationData EventData, bool need_confirm) { string val; // if event enrollment dispaly which datapoint is being watched if (EventData.eventObjectIdentifier.type == BacnetObjectTypes.OBJECT_EVENT_ENROLLMENT) { IList <BacnetValue> values; sender.ReadPropertyRequest(adr, EventData.eventObjectIdentifier, BacnetPropertyIds.PROP_OBJECT_PROPERTY_REFERENCE, out values); BacnetDeviceObjectPropertyReference obj = (BacnetDeviceObjectPropertyReference)values[0].Value; val = adr.ToString() + ":" + EventData.initiatingObjectIdentifier.type + ":" + EventData.initiatingObjectIdentifier.instance + ":" + EventData.eventObjectIdentifier.type + ":" + EventData.eventObjectIdentifier.instance + " object Type : " + obj.objectIdentifier.type + " object Instance :" + obj.objectIdentifier.instance + " object Property :" + obj.propertyIdentifier; } else { val = adr.ToString() + ":" + EventData.initiatingObjectIdentifier.type + ":" + EventData.initiatingObjectIdentifier.instance + ":" + EventData.eventObjectIdentifier.type + ":" + EventData.eventObjectIdentifier.instance; } if (need_confirm) { sender.SimpleAckResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_EVENT_NOTIFICATION, invoke_id); } // Just to show how Acknowledgement can be programmed. Never Ack an alarm like this without tested the source, the reason, ... and normally with a human action if (EventData.ackRequired) { sender.AlarmAcknowledgement(adr, EventData.eventObjectIdentifier, EventData.toState, "Alarmlistener", EventData.timeStamp, new BacnetGenericTime(DateTime.Now, BacnetTimestampTags.TIME_STAMP_DATETIME)); } Console.WriteLine(val + " " + EventData.fromState + " to " + EventData.toState + " " + EventData.notifyType.ToString()); }
private void Device_TextChanged(object sender, EventArgs e) { adr = null; try { deviceid = Convert.ToUInt16(Device.Text); if (DeviceAddrOK != null) { DeviceAddrOK(this, true); // it's a deviceId } } catch { try { adr = new BacnetAddress(BacnetAddressTypes.IP, Device.Text); if (DeviceAddrOK != null) { DeviceAddrOK(this, true); // it's a xxx.xxx.xxx.xxx:xxx } } catch { if (DeviceAddrOK != null) { DeviceAddrOK(this, false); } } } }
/*****************************************************************************************************/ static void handler_OnWritePropertyRequest(BacnetClient sender, BacnetAddress adr, byte invoke_id, BacnetObjectId object_id, BacnetPropertyValue value, BacnetMaxSegments max_segments) { // only OBJECT_ANALOG_VALUE:0.PROP_PRESENT_VALUE could be write in this sample code if ((object_id.type != BacnetObjectTypes.OBJECT_ANALOG_VALUE) || (object_id.instance != 0) || ((BacnetPropertyIds)value.property.propertyIdentifier != BacnetPropertyIds.PROP_PRESENT_VALUE)) { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROPERTY, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_WRITE_ACCESS_DENIED); return; } lock (m_storage) { try { DeviceStorage.ErrorCodes code = m_storage.WriteCommandableProperty(object_id, (BacnetPropertyIds)value.property.propertyIdentifier, value.value[0], value.priority); if (code == DeviceStorage.ErrorCodes.NotForMe) { code = m_storage.WriteProperty(object_id, (BacnetPropertyIds)value.property.propertyIdentifier, value.property.propertyArrayIndex, value.value); } if (code == DeviceStorage.ErrorCodes.Good) { sender.SimpleAckResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROPERTY, invoke_id); } else { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROPERTY, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_OTHER); } } catch (Exception) { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROPERTY, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_OTHER); } } }
/*****************************************************************************************************/ static void handler_OnReadPropertyMultipleRequest(BacnetClient sender, BacnetAddress adr, byte invoke_id, IList <BacnetReadAccessSpecification> properties, BacnetMaxSegments max_segments) { lock (m_storage) { try { IList <BacnetPropertyValue> value; List <BacnetReadAccessResult> values = new List <BacnetReadAccessResult>(); foreach (BacnetReadAccessSpecification p in properties) { if (p.propertyReferences.Count == 1 && p.propertyReferences[0].propertyIdentifier == (uint)BacnetPropertyIds.PROP_ALL) { if (!m_storage.ReadPropertyAll(p.objectIdentifier, out value)) { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_READ_PROP_MULTIPLE, invoke_id, BacnetErrorClasses.ERROR_CLASS_OBJECT, BacnetErrorCodes.ERROR_CODE_UNKNOWN_OBJECT); return; } } else { m_storage.ReadPropertyMultiple(p.objectIdentifier, p.propertyReferences, out value); } values.Add(new BacnetReadAccessResult(p.objectIdentifier, value)); } sender.ReadPropertyMultipleResponse(adr, invoke_id, sender.GetSegmentBuffer(max_segments), values); } catch (Exception) { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_READ_PROP_MULTIPLE, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_OTHER); } } }
private void m_comm_OnAbort(BacnetClient sender, BacnetAddress adr, BacnetPduTypes type, byte invoke_id, byte reason, byte[] buffer, int offset, int length) { if (invoke_id == m_wait_invoke_id) { Error = new Exception("Abort from device: " + reason); } }
public static void Convert(BacnetAddress addr, out IPEndPoint ep) { long ip_address = BitConverter.ToUInt32(addr.adr, 0); ushort port = (ushort)((addr.adr[4] << 8) | (addr.adr[5] << 0)); ep = new IPEndPoint(ip_address, port); }
private static void OnWritePropertyRequest(BacnetClient sender, BacnetAddress adr, byte invoke_id, BacnetObjectId object_id, BacnetPropertyValue value, BacnetMaxSegments max_segments) { lock (m_lockObject) { try { // Modif FC DeviceStorage.ErrorCodes code = m_storage.WriteCommandableProperty(object_id, (BacnetPropertyIds)value.property.propertyIdentifier, value.value[0], value.priority); if (code == DeviceStorage.ErrorCodes.NotForMe) { code = m_storage.WriteProperty(object_id, (BacnetPropertyIds)value.property.propertyIdentifier, value.property.propertyArrayIndex, value.value); } if (code == DeviceStorage.ErrorCodes.Good) { sender.SimpleAckResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROPERTY, invoke_id); } else if (code == DeviceStorage.ErrorCodes.WriteAccessDenied) { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROPERTY, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_WRITE_ACCESS_DENIED); } else { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROPERTY, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_OTHER); } } catch (Exception) { sender.ErrorResponse(adr, BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROPERTY, invoke_id, BacnetErrorClasses.ERROR_CLASS_DEVICE, BacnetErrorCodes.ERROR_CODE_OTHER); } } }
public int Send(byte[] buffer, int offset, int data_length, BacnetAddress address, bool wait_for_transmission, int timeout) { if (m_exclusive_conn == null) { return(0); } //add header int full_length = data_length + HeaderLength; bvlc.Encode(buffer, offset - BVLC.BVLC_HEADER_LENGTH, address.net == 0xFFFF ? BacnetBvlcFunctions.BVLC_ORIGINAL_BROADCAST_NPDU : BacnetBvlcFunctions.BVLC_ORIGINAL_UNICAST_NPDU, full_length); //create end point IPEndPoint ep; Convert(address, out ep); try { //send return(m_exclusive_conn.Send(buffer, full_length, ep)); //broadcasts are transported from our local unicast socket also } catch { return(0); } }
private static void Handler_OnIam(BacnetClient sender, BacnetAddress adr, uint deviceId, uint maxAPDU, BacnetSegmentations segmentation, ushort vendorId) { if (devicesList == null) { devicesList = new List <BacDevice>(); } lock (devicesList) { if (devicesList.Any(x => x.DeviceId == deviceId)) { return; } int index = 0; for (; index < devicesList.Count; index++) { if (devicesList[index].DeviceId > deviceId) { break; } } devicesList.Insert(index, new BacDevice(adr, deviceId)); LogHelper.Log(@"Detect Device: " + deviceId); } }
/// <summary> /// Gets available device and create global list /// </summary> /// <param name="bacNetClient">Passes bacNetClient detail</param> /// <param name="bacNetAddress">Passes Address</param> /// <param name="deviceId">Passes device id.</param> /// <param name="maxPLoad">Passes maxpayload.</param> /// <param name="segmentation"></param> /// <param name="vendorId"></param> public static void Handler_OmIam(BacnetClient bacNetClient, BacnetAddress bacNetAddress, uint deviceId, uint maxPLoad, BacnetSegmentations segmentation, ushort vendorId) { if (bacNetDeviceModel != null) { //// OnIam get current device and add into list to process bunch of device in DBs lock (bacNetDeviceModel.BACnetDeviceList) { if (!bacNetDeviceModel.BACnetDeviceList.Any(x => x.DeviceId == deviceId)) { //// Not already in the list bacNetDeviceModel.BACnetDeviceList.Add(new BackNetDeviceEntity { BacNetAddress = bacNetAddress, DeviceId = deviceId, InstanceId = 0 }); //// add it } } if (bacNetDeviceModel.BACnetDeviceList.Count == 48) { bacNetClient.OnIam -= new BacnetClient.IamHandler(BacNetService.Handler_OmIam); bacNetClient.OnWhoIs -= new BacnetClient.WhoIsHandler(BacNetService.handler_OnWhoIs); BacNetService.AddBackNetDeviceDetail(); } } }
static void handler_OnWhoHas(BacnetClient sender, BacnetAddress adr, int low_limit, int high_limit, BacnetObjectId ObjId, string ObjName) { if (low_limit != -1 && deviceId < low_limit) { return; } else if (high_limit != -1 && deviceId > high_limit) { return; } BaCSharpObject o; if (ObjName == null) { o = device.FindBacnetObject(ObjId); } else { o = device.FindBacnetObject(ObjName); } if (o != null) { sender.IHave(device.m_PROP_OBJECT_IDENTIFIER, ObjId, o.m_PROP_OBJECT_NAME); } }
/// <summary> /// Get current lightlign level from simulator will be between 1 to 100 /// </summary> /// <param name="fiDeviceID"></param> /// <returns></returns> private string GetLutronLightLevel(Int32 fiDeviceID) { IList <BacnetValue> loBacnetValueList; using (var loESDLutronEntities = new ESDLutronEntities()) { var loBACnetDeviceDetail = loESDLutronEntities.BACnetDevices .Where(x => x.device_id == fiDeviceID && x.object_instance == (int?)LutronObjectType.Lighting_Level) .Select(x => x).FirstOrDefault(); BacnetAddress loBacnetAddress; loBacnetAddress = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.network_id); loBacnetAddress.RoutedSource = new BacnetAddress(BacnetAddressTypes.IP, loBACnetDeviceDetail.routed_source, (ushort)loBACnetDeviceDetail.routed_net); moBacnetClient.ReadPropertyRequest(loBacnetAddress, new BacnetObjectId(BacnetObjectTypes.OBJECT_ANALOG_VALUE, (uint)loBACnetDeviceDetail.object_instance), BacnetPropertyIds.PROP_PRESENT_VALUE, out loBacnetValueList); } if (loBacnetValueList != null && loBacnetValueList.Count > 0) { return(loBacnetValueList[0].Value.ToString()); } else { return(string.Empty); } }
public BacnetAsyncResult(BacnetClient comm, BacnetAddress adr, byte invoke_id, byte[] transmit_buffer, int transmit_length, bool wait_for_transmit, int transmit_timeout) { m_transmit_timeout = transmit_timeout; m_adr = adr; m_wait_for_transmit = wait_for_transmit; m_transmit_buffer = transmit_buffer; m_transmit_length = transmit_length; AsyncWaitHandle = new System.Threading.ManualResetEvent(false); m_comm = comm; m_wait_invoke_id = invoke_id; m_comm.OnComplexAck += new BacnetClient.ComplexAckHandler(m_comm_OnComplexAck); m_comm.OnError += new BacnetClient.ErrorHandler(m_comm_OnError); m_comm.OnAbort += new BacnetClient.AbortHandler(m_comm_OnAbort); m_comm.OnSimpleAck += new BacnetClient.SimpleAckHandler(m_comm_OnSimpleAck); m_comm.OnSegment += new BacnetClient.SegmentHandler(m_comm_OnSegment); }
private void OnIam(BacnetClient sender, BacnetAddress adr, uint deviceId, uint maxApdu, BacnetSegmentations segmentation, ushort vendorId) { lock (_devicesList) { Logger.Debug($"OnIam(): DeviceId = {deviceId}"); // Device already registred ? if (_devicesList.Any(bn => bn.GetAdd(deviceId) != null)) { return; // Yes } // Not already in the list _devicesList.Add(new BacNode(adr, deviceId)); // add it Initialized = true; if (deviceId == Settings.Default.BacnetMasterId) { _starTaskCompletionSource.TrySetResult(true); } } }
//*********************************************************************** public IAsyncResult BeginRemoveListElementRequest(BacnetAddress adr, BacnetObjectId object_id,BacnetPropertyReference reference, IList<BacnetValue> value_list, bool wait_for_transmit, byte invoke_id = 0) { Trace.WriteLine("Sending RemoveListElementRequest ... ", null); if (invoke_id == 0) invoke_id = unchecked(m_invoke_id++); EncodeBuffer b = GetEncodeBuffer(m_client.HeaderLength); NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage, adr.RoutedSource, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, 0); APDU.EncodeConfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_CONFIRMED_SERVICE_REQUEST | (m_max_segments != BacnetMaxSegments.MAX_SEG0 ? BacnetPduTypes.SEGMENTED_RESPONSE_ACCEPTED : 0), BacnetConfirmedServices.SERVICE_CONFIRMED_REMOVE_LIST_ELEMENT, m_max_segments, m_client.MaxAdpuLength, invoke_id, 0, 0); Services.EncodeAddListElement(b, object_id,(uint) reference.propertyIdentifier,(uint) reference.propertyArrayIndex,value_list); //send BacnetAsyncResult ret = new BacnetAsyncResult(this, adr, invoke_id, b.buffer, b.offset - m_client.HeaderLength, wait_for_transmit, m_transmit_timeout); ret.Resend(); return ret; }
public IAsyncResult BeginWriteFileRequest(BacnetAddress adr, BacnetObjectId object_id, int position, int count, byte[] file_buffer, bool wait_for_transmit, byte invoke_id = 0) { Trace.WriteLine("Sending AtomicWriteFileRequest ... ", null); if (invoke_id == 0) invoke_id = unchecked(m_invoke_id++); EncodeBuffer b = GetEncodeBuffer(m_client.HeaderLength); NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage, adr.RoutedSource, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, 0); APDU.EncodeConfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_CONFIRMED_SERVICE_REQUEST | (m_max_segments != BacnetMaxSegments.MAX_SEG0 ? BacnetPduTypes.SEGMENTED_RESPONSE_ACCEPTED : 0), BacnetConfirmedServices.SERVICE_CONFIRMED_ATOMIC_WRITE_FILE, m_max_segments, m_client.MaxAdpuLength, invoke_id, 0, 0); Services.EncodeAtomicWriteFile(b, true, object_id, position, 1, new byte[][] { file_buffer }, new int[] { count }); //send BacnetAsyncResult ret = new BacnetAsyncResult(this, adr, invoke_id, b.buffer, b.offset - m_client.HeaderLength, wait_for_transmit, m_transmit_timeout); ret.Resend(); return ret; }
public IAsyncResult BeginSubscribePropertyRequest(BacnetAddress adr, BacnetObjectId object_id, BacnetPropertyReference monitored_property, uint subscribe_id, bool cancel, bool issue_confirmed_notifications, bool wait_for_transmit, byte invoke_id = 0) { Trace.WriteLine("Sending SubscribePropertyRequest ... ", null); if (invoke_id == 0) invoke_id = unchecked(m_invoke_id++); EncodeBuffer b = GetEncodeBuffer(m_client.HeaderLength); NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage, adr.RoutedSource, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, 0); APDU.EncodeConfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_CONFIRMED_SERVICE_REQUEST | (m_max_segments != BacnetMaxSegments.MAX_SEG0 ? BacnetPduTypes.SEGMENTED_RESPONSE_ACCEPTED : 0), BacnetConfirmedServices.SERVICE_CONFIRMED_SUBSCRIBE_COV_PROPERTY, m_max_segments, m_client.MaxAdpuLength, invoke_id, 0, 0); Services.EncodeSubscribeProperty(b, subscribe_id, object_id, cancel, issue_confirmed_notifications, 0, monitored_property, false, 0f); //send BacnetAsyncResult ret = new BacnetAsyncResult(this, adr, invoke_id, b.buffer, b.offset - m_client.HeaderLength, wait_for_transmit, m_transmit_timeout); ret.Resend(); return ret; }
public IAsyncResult BeginWritePropertyRequest(BacnetAddress adr, BacnetObjectId object_id, BacnetPropertyIds property_id, IEnumerable<BacnetValue> value_list, bool wait_for_transmit, byte invoke_id = 0) { Trace.WriteLine("Sending WritePropertyRequest ... ", null); if (invoke_id == 0) invoke_id = unchecked(m_invoke_id++); EncodeBuffer b = GetEncodeBuffer(m_client.HeaderLength); NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage, adr.RoutedSource, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, 0); APDU.EncodeConfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_CONFIRMED_SERVICE_REQUEST | (m_max_segments != BacnetMaxSegments.MAX_SEG0 ? BacnetPduTypes.SEGMENTED_RESPONSE_ACCEPTED : 0), BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROPERTY, m_max_segments, m_client.MaxAdpuLength, invoke_id, 0, 0); Services.EncodeWriteProperty(b, object_id, (uint)property_id, ASN1.BACNET_ARRAY_ALL, m_writepriority, value_list); //send BacnetAsyncResult ret = new BacnetAsyncResult(this, adr, invoke_id, b.buffer, b.offset - m_client.HeaderLength, wait_for_transmit, m_transmit_timeout); ret.Resend(); return ret; }
public IAsyncResult BeginWritePropertyMultipleRequest(BacnetAddress adr, ICollection<BacnetReadAccessResult> value_list, bool wait_for_transmit, byte invoke_id = 0) { Trace.WriteLine("Sending WritePropertyMultipleRequest ... ", null); if (invoke_id == 0) invoke_id = unchecked(m_invoke_id++); EncodeBuffer b = GetEncodeBuffer(m_client.HeaderLength); //BacnetNpduControls.PriorityNormalMessage NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage | BacnetNpduControls.ExpectingReply, adr.RoutedSource, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, 0); APDU.EncodeConfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_CONFIRMED_SERVICE_REQUEST | (m_max_segments != BacnetMaxSegments.MAX_SEG0 ? BacnetPduTypes.SEGMENTED_RESPONSE_ACCEPTED : 0), BacnetConfirmedServices.SERVICE_CONFIRMED_WRITE_PROP_MULTIPLE, m_max_segments, m_client.MaxAdpuLength, invoke_id, 0, 0); Services.EncodeWriteObjectMultiple(b, value_list); //send BacnetAsyncResult ret = new BacnetAsyncResult(this, adr, invoke_id, b.buffer, b.offset - m_client.HeaderLength, wait_for_transmit, m_transmit_timeout); ret.Resend(); return ret; }
//*************************************************************************************************** public bool DeleteObjectRequest(BacnetAddress adr, BacnetObjectId object_id, byte invoke_id = 0) { using (BacnetAsyncResult result = (BacnetAsyncResult)BeginDeleteObjectRequest(adr, object_id, true, invoke_id)) { for (int r = 0; r < m_retries; r++) { if (result.WaitForDone(m_timeout)) { Exception ex; EndDeleteObjectRequest(result, out ex); if (ex != null) throw ex; else return true; } result.Resend(); } } return false; }
//************************************************************* public bool AddListElementRequest(BacnetAddress adr, BacnetObjectId object_id,BacnetPropertyReference reference, IList<BacnetValue> value_list, byte invoke_id = 0) { using (BacnetAsyncResult result = (BacnetAsyncResult)BeginAddListElementRequest(adr, object_id,reference,value_list, true, invoke_id)) { for (int r = 0; r < m_retries; r++) { if (result.WaitForDone(m_timeout)) { Exception ex; EndAddListElementRequest(result, out ex); if (ex != null) throw ex; else return true; } result.Resend(); } } //values = null; return false; }
public int Send(byte[] buffer, int offset, int data_length, BacnetAddress address, bool wait_for_transmission, int timeout) { int hdr_offset = 0; for (int i = 0; i < 6; i++) buffer[hdr_offset++] = address.adr[i]; // write the source mac address bytes for (int i = 0; i < 6; i++) buffer[hdr_offset++] = _deviceMac[i]; // the next 2 bytes are used for the packet length buffer[hdr_offset++] = (byte)(((data_length + 3) & 0xFF00) >> 8); buffer[hdr_offset++] = (byte)((data_length + 3) & 0xFF); // DSAP and SSAP buffer[hdr_offset++] = 0x82; buffer[hdr_offset++] = 0x82; // LLC control field buffer[hdr_offset] = 0x03; lock (_device) { _device.SendPacket(buffer, data_length + HeaderLength); } return data_length + HeaderLength; }
public bool DeviceCommunicationControlRequest(BacnetAddress adr, uint timeDuration, uint enable_disable, string password, byte invoke_id = 0) { using (BacnetAsyncResult result = (BacnetAsyncResult)BeginDeviceCommunicationControlRequest(adr, timeDuration, enable_disable, password, true, invoke_id)) { for (int r = 0; r < m_retries; r++) { if (result.WaitForDone(m_timeout)) { Exception ex; EndDeviceCommunicationControlRequest(result, out ex); if (ex != null) return false; else return true; } result.Resend(); } } return false; }
void OnPacketArrival(RawCapture packet) { // don't process any packet too short to not be valid if (packet.Data.Length <= 17) return; byte[] buffer = packet.Data; int offset = 0; int length; byte dsap, ssap, control; // Got frames send by me, not for me, not broadcast byte[] dest = Mac(buffer, offset); if (!_isOutboundPacket(dest, 0) && (dest[0] != 255)) return; offset += 6; // source address BacnetAddress Bac_source = new BacnetAddress(BacnetAddressTypes.Ethernet, 0, Mac(buffer, offset)); offset += 6; // len length = buffer[offset] * 256 + buffer[offset + 1]; offset += 2; // 3 bytes LLC hearder dsap = buffer[offset++]; ssap = buffer[offset++]; control = buffer[offset++]; length -= 3; // Bacnet content length eq. ethernet lenght minus LLC header length // don't process non-BACnet packets if (dsap != 0x82 || ssap != 0x82 || control != 0x03) return; if (MessageRecieved != null) MessageRecieved(this, buffer, HeaderLength, length, Bac_source); }
// Fc public IAsyncResult BeginReadRangeRequest(BacnetAddress adr, BacnetObjectId object_id, uint idxBegin, uint Quantity, bool wait_for_transmit, byte invoke_id = 0) { Trace.WriteLine("Sending ReadRangeRequest ... ", null); if (invoke_id == 0) invoke_id = unchecked(m_invoke_id++); //encode EncodeBuffer b = GetEncodeBuffer(m_client.HeaderLength); NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage, adr.RoutedSource, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, 0); APDU.EncodeConfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_CONFIRMED_SERVICE_REQUEST | (m_max_segments != BacnetMaxSegments.MAX_SEG0 ? BacnetPduTypes.SEGMENTED_RESPONSE_ACCEPTED : 0), BacnetConfirmedServices.SERVICE_CONFIRMED_READ_RANGE, m_max_segments, m_client.MaxAdpuLength, invoke_id, 0, 0); Services.EncodeReadRange(b, object_id, (uint)BacnetPropertyIds.PROP_LOG_BUFFER, ASN1.BACNET_ARRAY_ALL, BacnetReadRangeRequestTypes.RR_BY_POSITION, idxBegin, DateTime.Now, (int)Quantity); //send BacnetAsyncResult ret = new BacnetAsyncResult(this, adr, invoke_id, b.buffer, b.offset - m_client.HeaderLength, wait_for_transmit, m_transmit_timeout); ret.Resend(); return ret; }
public int Send(byte[] buffer, int offset, int data_length, BacnetAddress address, bool wait_for_transmission, int timeout) { if (m_exclusive_conn == null) return 0; //add header int full_length = data_length + HeaderLength; bvlc.Encode(buffer, offset - BVLC.BVLC_HEADER_LENGTH, address.net == 0xFFFF ? BacnetBvlcFunctions.BVLC_ORIGINAL_BROADCAST_NPDU : BacnetBvlcFunctions.BVLC_ORIGINAL_UNICAST_NPDU, full_length); //create end point System.Net.IPEndPoint ep; Convert(address, out ep); try { //send return m_exclusive_conn.Send(buffer, full_length, ep); //broadcasts are transported from our local unicast socket also } catch { return 0; } }
public IAsyncResult BeginReinitializeRequest(BacnetAddress adr, BacnetReinitializedStates state, string password, bool wait_for_transmit, byte invoke_id = 0) { Trace.WriteLine("Sending ReinitializeRequest ... ", null); if (invoke_id == 0) invoke_id = unchecked(m_invoke_id++); EncodeBuffer b = GetEncodeBuffer(m_client.HeaderLength); NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage, adr.RoutedSource, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, 0); APDU.EncodeConfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_CONFIRMED_SERVICE_REQUEST | (m_max_segments != BacnetMaxSegments.MAX_SEG0 ? BacnetPduTypes.SEGMENTED_RESPONSE_ACCEPTED : 0), BacnetConfirmedServices.SERVICE_CONFIRMED_REINITIALIZE_DEVICE, m_max_segments, m_client.MaxAdpuLength, invoke_id, 0, 0); Services.EncodeReinitializeDevice(b, state, password); //send BacnetAsyncResult ret = new BacnetAsyncResult(this, adr, invoke_id, b.buffer, b.offset - m_client.HeaderLength, wait_for_transmit, m_transmit_timeout); ret.Resend(); return ret; }
//********************************************************************************* // By Christopher Günter public bool CreateObjectRequest(BacnetAddress adr, BacnetObjectId object_id, ICollection<BacnetPropertyValue> value_list, byte invoke_id = 0) { using (BacnetAsyncResult result = (BacnetAsyncResult)BeginCreateObjectRequest(adr, object_id, value_list, true, invoke_id)) { for (int r = 0; r < m_retries; r++) { if (result.WaitForDone(m_timeout)) { Exception ex; EndCreateObjectRequest(result, out ex); if (ex != null) throw ex; else return true; } result.Resend(); } } value_list = null; return false; }
private StateChanges WaitForReply() { BacnetMstpFrameTypes frame_type; byte destination_address; byte source_address; int msg_length; //fetch message GetMessageStatus status = GetNextMessage(T_REPLY_TIMEOUT, out frame_type, out destination_address, out source_address, out msg_length); if (status == GetMessageStatus.Good) { try { if (destination_address == (byte)m_TS && (frame_type == BacnetMstpFrameTypes.FRAME_TYPE_TEST_RESPONSE || frame_type == BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_NOT_EXPECTING_REPLY)) { //signal upper layer if (MessageRecieved != null && frame_type != BacnetMstpFrameTypes.FRAME_TYPE_TEST_RESPONSE) { BacnetAddress remote_address = new BacnetAddress(BacnetAddressTypes.MSTP, 0, new byte[] { source_address }); try { MessageRecieved(this, m_local_buffer, MSTP.MSTP_HEADER_LENGTH, msg_length, remote_address); } catch (Exception ex) { Trace.TraceError("Exception in MessageRecieved event: " + ex.Message); } } /* ReceivedReply */ return StateChanges.ReceivedReply; } else if (frame_type == BacnetMstpFrameTypes.FRAME_TYPE_REPLY_POSTPONED) { /* ReceivedPostpone */ return StateChanges.ReceivedPostpone; } else { /* ReceivedUnexpectedFrame */ return StateChanges.ReceivedUnexpectedFrame; } } finally { RemoveCurrentMessage(msg_length); } } else if (status == GetMessageStatus.Timeout) { /* ReplyTimeout */ m_frame_count = m_max_info_frames; return StateChanges.ReplyTimeOut; } else { /* InvalidFrame */ return StateChanges.InvalidFrame; } }
// Fc public IAsyncResult BeginRawEncodedDecodedPropertyConfirmedRequest(BacnetAddress adr, BacnetObjectId object_id, BacnetPropertyIds property_id, BacnetConfirmedServices service_id, byte[] InOutBuffer, bool wait_for_transmit, byte invoke_id = 0) { Trace.WriteLine("Sending RawEncodedRequest ... ", null); if (invoke_id == 0) invoke_id = unchecked(m_invoke_id++); EncodeBuffer b = GetEncodeBuffer(m_client.HeaderLength); NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage | BacnetNpduControls.ExpectingReply, adr.RoutedSource, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, 0); APDU.EncodeConfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_CONFIRMED_SERVICE_REQUEST | (m_max_segments != BacnetMaxSegments.MAX_SEG0 ? BacnetPduTypes.SEGMENTED_RESPONSE_ACCEPTED : 0), service_id , m_max_segments, m_client.MaxAdpuLength, invoke_id, 0, 0); ASN1.encode_context_object_id(b, 0, object_id.type, object_id.instance); ASN1.encode_context_enumerated(b, 1, (byte)property_id); // No content encoding to do if (InOutBuffer!=null) b.Add(InOutBuffer, InOutBuffer.Length); //send BacnetAsyncResult ret = new BacnetAsyncResult(this, adr, invoke_id, b.buffer, b.offset - m_client.HeaderLength, wait_for_transmit, m_transmit_timeout); ret.Resend(); return ret; }
public BacNode(BacnetAddress adr, uint deviceId) { _adr = adr; _deviceId = deviceId; }
public int Send(byte[] buffer, int offset, int data_length, BacnetAddress address, bool wait_for_transmission, int timeout) { BacnetPtpFrameTypes frame_type = BacnetPtpFrameTypes.FRAME_TYPE_DATA0; if (m_sequence_counter) frame_type = BacnetPtpFrameTypes.FRAME_TYPE_DATA1; m_sequence_counter = !m_sequence_counter; //add header int full_length = PTP.Encode(buffer, offset - PTP.PTP_HEADER_LENGTH, frame_type, data_length); //wait for send allowed if (!m_may_send.WaitOne(timeout)) return -BacnetMstpProtocolTransport.ETIMEDOUT; //debug if (StateLogging) Trace.WriteLine(" " + frame_type, null); //send SendWithXonXoff(buffer, offset - HeaderLength, full_length); return data_length; }
public static void Convert(System.Net.IPEndPoint ep, out BacnetAddress addr) { byte[] tmp1 = ep.Address.GetAddressBytes(); byte[] tmp2 = BitConverter.GetBytes((ushort)ep.Port); Array.Reverse(tmp2); Array.Resize<byte>(ref tmp1, tmp1.Length + tmp2.Length); Array.Copy(tmp2, 0, tmp1, tmp1.Length - tmp2.Length, tmp2.Length); addr = new BacnetAddress(BacnetAddressTypes.IP, 0, tmp1); }
private StateChanges Idle() { int no_token_timeout = T_NO_TOKEN + 10 * m_TS; BacnetMstpFrameTypes frame_type; byte destination_address; byte source_address; int msg_length; while (m_port != null) { //get message GetMessageStatus status = GetNextMessage(no_token_timeout, out frame_type, out destination_address, out source_address, out msg_length); if (status == GetMessageStatus.Good) { try { if (destination_address == m_TS || destination_address == 0xFF) { switch (frame_type) { case BacnetMstpFrameTypes.FRAME_TYPE_POLL_FOR_MASTER: if (destination_address == 0xFF) QueueFrame(BacnetMstpFrameTypes.FRAME_TYPE_REPLY_TO_POLL_FOR_MASTER, source_address); else { //respond to PFM SendFrame(BacnetMstpFrameTypes.FRAME_TYPE_REPLY_TO_POLL_FOR_MASTER, source_address); } break; case BacnetMstpFrameTypes.FRAME_TYPE_TOKEN: if (destination_address != 0xFF) { m_frame_count = 0; m_sole_master = false; return StateChanges.ReceivedToken; } break; case BacnetMstpFrameTypes.FRAME_TYPE_TEST_REQUEST: if (destination_address == 0xFF) QueueFrame(BacnetMstpFrameTypes.FRAME_TYPE_TEST_RESPONSE, source_address); else { //respond to test SendFrame(BacnetMstpFrameTypes.FRAME_TYPE_TEST_RESPONSE, source_address); } break; case BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_NOT_EXPECTING_REPLY: case BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_EXPECTING_REPLY: //signal upper layer if (MessageRecieved != null) { BacnetAddress remote_address = new BacnetAddress(BacnetAddressTypes.MSTP, 0, new byte[] { source_address }); try { MessageRecieved(this, m_local_buffer, MSTP.MSTP_HEADER_LENGTH, msg_length, remote_address); } catch (Exception ex) { Trace.TraceError("Exception in MessageRecieved event: " + ex.Message); } } if (frame_type == BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_EXPECTING_REPLY) { m_reply_source = source_address; m_reply = null; m_reply_mutex.Reset(); return StateChanges.ReceivedDataNeedingReply; } break; } } } finally { RemoveCurrentMessage(msg_length); } } else if (status == GetMessageStatus.Timeout) { /* GenerateToken */ m_PS = (byte)((m_TS + 1) % (m_max_master + 1)); m_NS = (byte)m_TS; m_token_count = 0; return StateChanges.GenerateToken; } else if (status == GetMessageStatus.ConnectionClose) { Trace.WriteLine("No connection", null); } else if (status == GetMessageStatus.ConnectionError) { Trace.WriteLine("Connection Error", null); } else { Trace.WriteLine("Garbage", null); } } return StateChanges.Reset; }
public static void Convert(BacnetAddress addr, out System.Net.IPEndPoint ep) { long ip_address = BitConverter.ToUInt32(addr.adr, 0); ushort port = (ushort)((addr.adr[4] << 8) | (addr.adr[5] << 0)); ep = new System.Net.IPEndPoint(ip_address, (int)port); }
public BacNode(BacnetAddress adr, uint device_id) { this.adr = adr; this.device_id = device_id; }
public int Send(byte[] buffer, int offset, int data_length, BacnetAddress address, bool wait_for_transmission, int timeout) { if (m_TS == -1) throw new Exception("Source address must be set up before sending messages"); //add to queue BacnetNpduControls function = NPDU.DecodeFunction(buffer, offset); BacnetMstpFrameTypes frame_type = (function & BacnetNpduControls.ExpectingReply) == BacnetNpduControls.ExpectingReply ? BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_EXPECTING_REPLY : BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_NOT_EXPECTING_REPLY; byte[] copy = new byte[data_length + MSTP.MSTP_HEADER_LENGTH + 2]; Array.Copy(buffer, offset, copy, MSTP.MSTP_HEADER_LENGTH, data_length); MessageFrame f = new MessageFrame(frame_type, address.adr[0], copy, data_length); m_send_queue.AddLast(f); if (m_reply == null) { m_reply = f; m_reply_mutex.Set(); } //wait for message to be sent if (wait_for_transmission) if (!f.send_mutex.WaitOne(timeout)) return -ETIMEDOUT; return data_length; }
public IAsyncResult BeginConfirmedNotify(BacnetAddress adr, uint subscriberProcessIdentifier, uint initiatingDeviceIdentifier, BacnetObjectId monitoredObjectIdentifier, uint timeRemaining, IList<BacnetPropertyValue> values, bool wait_for_transmit, byte invoke_id = 0) { Trace.WriteLine("Sending Notify (confirmed) ... ", null); if (invoke_id == 0) invoke_id = unchecked(m_invoke_id++); EncodeBuffer b = GetEncodeBuffer(m_client.HeaderLength); NPDU.Encode(b, BacnetNpduControls.PriorityNormalMessage, adr.RoutedSource, null, DEFAULT_HOP_COUNT, BacnetNetworkMessageTypes.NETWORK_MESSAGE_WHO_IS_ROUTER_TO_NETWORK, 0); APDU.EncodeConfirmedServiceRequest(b, BacnetPduTypes.PDU_TYPE_CONFIRMED_SERVICE_REQUEST | (m_max_segments != BacnetMaxSegments.MAX_SEG0 ? BacnetPduTypes.SEGMENTED_RESPONSE_ACCEPTED : 0), BacnetConfirmedServices.SERVICE_CONFIRMED_COV_NOTIFICATION, m_max_segments, m_client.MaxAdpuLength, invoke_id, 0, 0); Services.EncodeCOVNotifyConfirmed(b, subscriberProcessIdentifier, initiatingDeviceIdentifier, monitoredObjectIdentifier, timeRemaining, values); //send BacnetAsyncResult ret = new BacnetAsyncResult(this, adr, invoke_id, b.buffer, b.offset - m_client.HeaderLength, wait_for_transmit, m_transmit_timeout); ret.Resend(); return ret; }
/*****************************************************************************************************/ static void handler_OnIam(BacnetClient sender, BacnetAddress adr, uint device_id, uint max_apdu, BacnetSegmentations segmentation, ushort vendor_id) { lock (DevicesList) { // Device already registred ? foreach (BacNode bn in DevicesList) if (bn.getAdd(device_id) != null) return; // Yes // Not already in the list DevicesList.Add(new BacNode(adr, device_id)); // add it } }
public void Set(BacnetAddress adr, byte invoke_id, byte sequence_number, byte window_size) { lock (m_lockObject) { this.adr = adr; this.invoke_id = invoke_id; this.sequence_number = sequence_number; this.window_size = window_size; m_wait.Set(); } }
private void SendComplexAck(BacnetAddress adr, byte invoke_id, Segmentation segmentation, BacnetConfirmedServices service, Action<EncodeBuffer> apdu_content_encode) { Trace.WriteLine("Sending " + System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(service.ToString().ToLower()) + " ... ", null); //encode EncodeBuffer buffer; if (EncodeSegment(adr, invoke_id, segmentation, service, out buffer, apdu_content_encode)) { //client doesn't support segments if (segmentation == null) { Trace.TraceInformation("Segmenation denied"); ErrorResponse(adr, service, invoke_id, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_APDU_TOO_LONG); buffer.result = EncodeResult.Good; //don't continue the segmentation return; } //first segment? validate max segments if (segmentation.sequence_number == 0) //only validate first segment { if (segmentation.max_segments != 0xFF && segmentation.buffer.offset > (segmentation.max_segments * (GetMaxApdu() - 5))) //5 is adpu header { Trace.TraceInformation("Too much segmenation"); ErrorResponse(adr, service, invoke_id, BacnetErrorClasses.ERROR_CLASS_SERVICES, BacnetErrorCodes.ERROR_CODE_ABORT_APDU_TOO_LONG); buffer.result = EncodeResult.Good; //don't continue the segmentation return; } else Trace.WriteLine("Segmentation required", null); } //increment before ack can do so (race condition) unchecked { segmentation.sequence_number++; }; } //send m_client.Send(buffer.buffer, m_client.HeaderLength, buffer.GetLength() - m_client.HeaderLength, adr, false, 0); }
public bool Wait(BacnetAddress adr, byte invoke_id, int timeout) { System.Threading.Monitor.Enter(m_lockObject); while (!adr.Equals(this.adr) || this.invoke_id != invoke_id) { m_wait.Reset(); System.Threading.Monitor.Exit(m_lockObject); if (!m_wait.WaitOne(timeout)) return false; System.Threading.Monitor.Enter(m_lockObject); } System.Threading.Monitor.Exit(m_lockObject); this.adr = null; return true; }