[Serialization] Design and Implementation of the C # communication (Serial Port and network) framework-4. design of the device driver manager,

Source: Internet
Author: User
Tags driver manager

[Serialization] Design and Implementation of the C # communication (Serial Port and network) framework-4. design of the device driver manager,

Contents

Chapter 4 design of the device driver manager... 2

4.1 interface definition... 2

4.2 device container... 7

4.3 generate device ID .. 7

4.4 mutex on device container operations... 8

4.5 get the device list... 8

4.6 Special Use of device counters... 8

4.7 summary... 10

 

Chapter 4 design of the device driver Manager

The device driver Manager manages the driver interfaces of IRunDevice devices and is an important component of the framework. No matter how the device driver manager is designed and in what form it exists, it must exist in concept. The designed device driver manager is crucial to the stable operation of the Framework Platform.

Before introducing the device driver manager, let's briefly introduce the IIOController, which is mainly responsible for scheduling IO and device and driving device operation, detailed introduction is made in chapter 1 serial port and network I/O design. That is to say, an IO controller may correspond to multiple device drivers (plug-ins ).

In the early days, each IO controller had a device driver manager. When the Framework Platform is started, the corresponding device driver is allocated to the corresponding IO manager according to the communication parameters of the device driver. When the IO parameter changes, the event is triggered, move the device driver from the current IO controller to another IO controller.

From the business point of view, there is no problem in doing so, and the operation is always stable. However, in terms of modularity and scalability, It is not ideal. If a device driver cannot be directly or quickly called elsewhere, it is necessary to traverse the IO controller and then match the corresponding device driver, and the operation is troublesome and inefficient.

During the restructuring of the Framework Platform, the problem was reconsidered and the associated problems were resolved together. The device driver manager in each IO controller is integrated, and a device driver manager is used to coordinate the Framework Platform.

The technology involved in this section is not difficult and easy to understand, but some details need to be paid attention to during the design process. These problems may affect the stability of the Framework Platform.

4.1 Interface Definition

Define an interface (IDeviceManager <TKey, TValue>) to determine the functions required by the device driver manager, add devices, delete devices, obtain devices and lists, and perform other functions. The interface code is as follows:

Public interface IDeviceManager <TKey, TValue>: IEnumerable <TValue> where TValue: IRunDevice {// <summary> // ID of the new device, and it is unique /// </summary> /// <returns> </returns> string BuildDeviceID (); /// <summary> /// Add a device /// </summary> /// <param name = "key"> </param> /// <param name = "val"> </param> void AddDevice (TKey key, TValue val ); /// <summary> /// Delete the device /// </summary> /// <param name = "key"> </param> void RemoveDevice (TKey key ); /// <summary> /// remove all devices /// </summary> void RemoveAllDevice (); /// <summary> /// obtain the value set /// </summary> /// <returns> </returns> List <TValue> GetValues (); /// <summary> /// get the keyword set /// </summary> /// <returns> </returns> List <TKey> GetKeys (); /// <summary> /// obtain the device ID and name /// </summary> /// <returns> </returns> Dictionary <int, string> GetDeviceIDAndName (); /// <summary> /// get the high-priority running device /// </summary> /// <param name = "vals"> </param> // <returns> </returns> TValue GetPriorityDevice (TValue [] vals ); /// <summary> /// obtain a single device /// </summary> /// <param name = "key"> </param> /// <returns> </returns> TValue GetDevice (TKey key ); /// <summary> /// obtain the device array /// </summary> /// <param name = "para"> IP address or serial port number </param> // /<param name = "ioType"> communication type </param> // <returns> </returns> TValue [] GetDevices (string para, communicationType ioType ); /// <summary> /// obtain the network device of the specified IP address and working mode. /// </summary> /// <param name = "remoteIP"> </param> /// <param name = "workMode"> </param> /// <returns> </returns> TValue [] GetDevices (string remoteIP, workMode workMode ); /// <summary> /// obtain the network device in the specified working mode // </summary> /// <param name = "workMode"> </param> // /<returns> </returns> TValue [] GetDevices (WorkMode workMode ); /// <summary> /// get the device array /// </summary> /// <param name = "ioType"> </param> /// <returns> </returns> TValue [] GetDevices (CommunicationType ioType ); /// <summary> /// obtain the device by device type /// </summary> /// <param name = "devType"> </param> // <returns> </returns> TValue [] GetDevices (Device. deviceType devType ); /// <summary> /// determine whether the device exists /// </summary> /// <param name = "key"> </param> // <returns> </returns> bool ContainDevice (TKey key ); /// <summary> /// based on input parameters, determine whether the device includes /// </summary> /// <param name = "para"> IP address or serial port number </param> /// <param name = "ioType"> device communication type </param> /// <returns> </returns> bool ContainDevice (string para, communicationType ioType ); /// <summary> /// set the user level /// </summary> /// <param name = "userlevel"> </param> void SetUserLevel (UserLevel userlevel); /// <summary> /// set whether to register /// </summary> /// <param name = "isreg"> </param> void SetIsRegLicense (bool isreg); /// <summary> /// obtain the number of available devices /// </summary> int Count {get ;} /// <summary> /// obtain the counter value of the device /// </summary> /// <param name = "key"> </param> /// <returns> </returns> int GetCounter (TKey key ); /// <summary> /// set the counter value /// </summary> /// <param name = "key"> </param> /// <param name = "val"> </param> void SetCounter (TKey key, int val );}

4.2 device container

The device driver manager encapsulates Dictionary <Key, Value>. The Key is the ID of the device driver, and the Value is the interface of the IRunDevice device driver. The device driver manager must be applied across threads. Therefore, the thread synchronization lock must be applied to the Dictionary operation.

At that time. NET Framework 2.0 Framework, without the ConcurrentDictionary (Of TKey, TValue) dictionary class, all public and protected members Of this class are thread-safe and use atomic operations, it is suitable for simultaneous use between multiple threads. During Reconstruction, you can use the ConcurrentDictionary class to replace the Dictionary class. Because all operations of the ConcurrentDictionary use the Monitor thread synchronization class, you do not need to encapsulate it yourself.

Do not paste the source code of the ConcurrentDictionary class. For details, refer to MSDN.

4.3 generate a device ID

Search for the largest device ID in the device driver manager and Add 1 to it. This code is very simple,

As follows:

public string BuildDeviceID(){       if(_dic.Count>0)       {          int maxID=_dic.Max(d => d.Value.DeviceParameter.DeviceID);          return (++maxID);       }       else       {              return 0;       }}

To add a device driver, you need to generate a device ID. Generally, You need to manually add a device driver. Therefore, you do not need to apply a thread synchronization lock to this device.

4.4 mutual exclusion of device container operations

All components of the framework platform must share the device driver manager, so cross-thread applications are involved.

If the set changes, exceptions may occur. For example, when the Framework Platform is started, the I/O controller is started, and the I/O controller extracts the list of devices from the device driver manager. However, the device driver may not be loaded yet, A conflict may occur when a new device driver is added to Device Driver Management.

Therefore, thread synchronization locks are added when devices are added, deleted, and the device list is obtained, for example, lock (_ SyncLock ).

4.5 obtain the device list

There are multiple GetDevices constructors that meet different application scenarios.

See "4.1 Interface Definition ".

In addition, the GetPriorityDevice function for devices with high priority is described in the previous section.

4.6 Special Use of device counters

The interface definition includes SetCounter and GetCounter functions for communication.

The application scenario is as follows: in the concurrent and automatic communication mode, the device driver is always in the normal communication mode, but suddenly the line is interrupted or the data cannot be received due to other reasons, the device driver cannot receive data, detect the communication status, and change the corresponding data information. That is to say, the actual situation has changed, but the device driver cannot respond.

To prevent this situation, the device driver obtains the counter of the Current Device Driver through the GetCounter function each time it sends data, and operates on the counter (variable) + 1, use the SetCounter function to write the counter (variable) to the device driver manager. When exceptions receive data, execute the same process, but execute-1. If data is always sent but no data is received, the counters of the current device driver will be accumulated. If the value is greater than or equal to a specific value, the current device will be driven through RunIODevice (new byte [] {}), the entire device processing process will be executed, and the second-developed code block will be called, to change the status and data of such application scenarios. The Code is as follows:

Int counter = DeviceManager. getInstance (). getCounter (dev. deviceParameter. deviceID. toString (); int sendNum = SessionSocketManager. getInstance (). send (dev. deviceParameter. NET. remoteIP, data); if (sendNum = data. length & sendNum! = 0) {DeviceMonitorLog. writeLog (dev. deviceParameter. deviceName, "Send request data"); Interlocked. increment (ref counter);} else {Interlocked. increment (ref counter); DeviceMonitorLog. writeLog (dev. deviceParameter. deviceName, "failed to send data");} dev. showMonitorIOData (data, "send"); if (counter> = 3) {try {dev. runIODevice (new byte [] {});} catch (Exception ex) {DeviceMonitorLog. writeLog (dev. deviceParameter. deviceName, ex. message); GeneralLog. writeLog (ex);} Interlocked. exchange (ref counter, 0);} DeviceManager. getInstance (). setCounter (dev. deviceParameter. deviceID. toString (), counter );

The Interlocked class is used to send and receive data in different threads and perform the plus 1 and minus 1 operations on the counter (variable, variables shared by multiple threads provide atomic operations to prevent exceptions or data corruption that may occur during parallel operations on multiple processors.

Conclusion 4.7

After this transformation, you can not only reference the device in the IO controller, but also use it in other components. If you encounter a similar situation, you want to use the ConcurrentDictionary class.

 

Author: Wei Xiaozhi

Email: 504547114@qq.com

QQ: 504547114

. NET Development Technology Alliance: 54256083

Document Download: http://pan.baidu.com/s/1pJ7lZWf

Http://www.bmpj.net

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.