百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
O

OpenProtocolInterpreter

> 编程语言
开源

将来自 Open Protocol 的丑陋的 ASCII 包转换为对象

182 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

将来自 Open Protocol 的丑陋的 ASCII 包转换为对象

OpenProtocol communication utility

  1. What is Open Protocol at all?
  2. What is OpenProtocolInterpreter?
  3. Get it on NuGet
  4. How does it work?
  5. Usage examples
    • Parsing a package
    • Packing a MID
    • Replies and acknowledges
  6. Anatomy of a MID
    • Data field attributes
    • Available attributes
    • Revisions
  7. Advanced section
    • MIDs identifying customization
    • Extra data (MID 0006, 0008 and 0009)
    • MIDs overriding
    • Adding MIDs that are not in documentation
    • How it was built?
    • Advanced example
  8. Tips
  9. Supported frameworks
  10. Contribute to the project
  11. Sponsor the project
  12. Still unavailable mids

What is Open Protocol at all?

Open Protocol, as the name says, it's a protocol to communicate with Atlas Copco Tightening Controllers or whatever that implement that protocol. Most common Tightening Controllers from Atlas Copco company are PowerFocus4000 and PowerMacs.

Although, some other companies adhered to use the same protocol.

What is OpenProtocolInterpreter?

OpenProtocolInterpreter is a library that converts the ugly string that came from Open Protocol packages, which is commonly called MID, to an object. "Substringing" packages is such a boring thing to do, so let OpenProtocolIntepreter do it for you!

If you're curious, just take a look at their documentation.

Get it on NuGet!

Install-Package OpenProtocolInterpreter

How does it work?

It's simple, you give us your byte[] or string package and we deliver you an object, simple as that!

For example, let's imagine you received the following string package:

csharp
string package = "00240005001         0018";

It's MID 5, so OpenProtocolIntepreter will return a Mid0005 class for you with all his datafields and the package entire translated to an object.

Let's see some examples of usage

Parsing a package

MidInterpreter starts empty: you must tell it which MIDs it should know about before parsing anything. UseAllMessages() is the "give me everything" shortcut — see MIDs identifying customization to narrow it down.

csharp
var interpreter = new MidInterpreter().UseAllMessages();

var midPackage = "00260004001         001802";
var myMid04 = interpreter.Parse(midPackage);

//MID 0004 is an error mid which contains which MID failed and its error code
int myFailedMid = myMid04.FailedMid;    // 18
Error errorCode = myMid04.ErrorCode;    // Error.ParameterSetIdNotPresent

Everything a MID carries is a plain, settable property, so you can read it straight away. byte[] packages are accepted by the very same overloads:

csharp
byte[] rawPackage = socket.Receive();
var mid = interpreter.Parse(rawPackage);        // returns Mid, use it when you don't know what is coming
var mid04 = interpreter.Parse(rawPackage);

Use Parse(package) when you don't know which MID will arrive and Parse(package) when you do. The generic overload throws InvalidCastException when the package turns out to be another MID.

Packing a MID

It can generate an object from a string, but can it make it to the other way?? FOR SURE!

csharp
var jobUploadRequest = new Mid0032(revision: 2) { JobId = 1 };
var package = jobUploadRequest.Pack();
//Generated package => 00240032002         0001

var bytes = jobUploadRequest.PackBytes();       // same content, encoded with Mid.DefaultEncoding (ASCII)
var terminated = jobUploadRequest.PackWithNul(); // appends the NUL character some controllers expect

The header length is recalculated for you on every Pack(), based on the revision in Header.Revision. Every MID exposes a parameterless constructor (revision 1) and a Mid(Header header) constructor; the ones that have more than one documented revision also expose Mid(int revision).

Replies and acknowledges

MIDs advertise their relationships through marker interfaces, so it might help you to remember which MID answers which or even give a shortcut for you:

csharp
Mid0062 ack = new Mid0061(2).GetAcknowledge();  // IAcknowledgeable, keeps the source revision
Mid0033 reply = new Mid0032(2).GetReply();      // IAnswerableBy

Anatomy of a MID

Data field attributes

A MID has each property is decorated with a data field attribute describing where that value lives inside the package. Which also represents the string index/position of the package accordingly with Open Protocol documentation. E.g.:

…

Every attribute accepts:

Member Meaning
revision Revision this definition belongs to.
field Data field id/sequence/index inside the revision.
Index Offset of the value inside the package, counted from the start of the package (the header takes the first 20 chars).
Size Length of the value. Fixed automatically by some attributes that has fixed size (booleans, timestamps).
HasPrefix true when the package carries the two digit field id right before the value.
PaddingChar Char used to pad the value to its full size when packing.
PaddingOrientation Defines if char filling RightPadded or LeftPadded

Parsing and packing both flow through the same definitions: on Parse the slice is read, converted and written back into the property; on Pack the property value is read, converted and written into the package.

Available attributes

Attribute Property type Notes
BooleanDataFieldDefinition bool Size forced to 1
StringDataFieldDefinition string Defaultly right padded with ' '
Int32DataFieldDefinition int, int-backed enum left padded with '0'
Int64DataFieldDefinition long, long-backed enum left padded with '0'
DecimalDataFieldDefinition decimal left padded with '0'
TruncatedDecimalDataFieldDefinition decimal DecimalPoints (default 2) implicit decimal places
TimestampDataFieldDefinition DateTime Size forced to 19, YYYY-MM-DD:HH:MM:SS
Int32CollectionDefinition List requires EachFieldSize
EnumCollectionDefinition List where T : Enum one char per entry
VariableDataFieldCollectionDefinition List the variable data fields block

Revisions

At parse/pack time only the definitions up to Header.StandardizedRevision are used so we can avoid confusion with revision 0 since when zero or blank it represents revision 1.

Advanced Section!

Now we will get real! Put one thing in mind, in real world we will always need to build something more complex than the dummies examples we give to you. With this in mind, this section is for you:

MIDs Identifying Customization

We have several MIDs inside Open Protocol documentation, but do you really need all of them? The answer is... NO!

You will probably need only to use a range of MIDs, with this in mind, we did something to make things faster. You can tell us which MIDs we should considerate!

Here is an example:

…

You can also register a whole category at once, and filter it by your role in the communication:

csharp
var interpreter = new MidInterpreter()
                        .UseCommunicationMessages(InterpreterMode.Integrator)
                        .UseTighteningMessages(InterpreterMode.Integrator)
                        .UseAlarmMessages(InterpreterMode.Integrator);

InterpreterMode.Integrator keeps only the MIDs a controller can send you, InterpreterMode.Controller keeps only the ones an integrator can send, and InterpreterMode.Both (the default) keeps everything. There is one Use...Messages extension per category, all of them accepting a mode, an IEnumerable or an IDictionary (see MIDs overriding).

Extra data (MID 0006, 0008 and 0009)

MIDs 0006 (request), 0008 (subscription) and 0009 (unsubscription) carry a free form payload whose layout depends on the MID being requested/subscribed. Those payloads are modelled by ExtraData classes, which use the very same data field attributes as a MID:

csharp
var subscription = new Mid0008();
subscription.SetExtraData(new Mid1201ExtraDataSubscription
{
    SendAlternatives = 1,
    DataIdentifierTimestamp = new DateTime(2026, 8, 7, 13, 45, 0),
    SendObjectData = true
});

var package = subscription.Pack();
//Generated package => 00590008001         12010013000000000012026-08-07:13:45:001

SetExtraData fills SubscriptionMid, WantedRevision, ExtraDataLength and ExtraData for you. On the receiving side, parse the container MID first and then hand its raw ExtraData to the matching class:

csharp
var mid08 = interpreter.Parse(package);
var extraData = (Mid1201ExtraDataSubscription)new Mid1201ExtraDataSubscription(mid08.WantedRevision)
                                                    .Parse(mid08.ExtraData);

int alternatives = extraData.SendAlternatives;
DateTime timestamp = extraData.DataIdentifierTimestamp;

A MID may declare one ExtraData per kind, since request (IExtraDataRequest), subscription (IExtraDataSubscription) and unsubscription (IExtraDataUnsubscription) payloads don't necessarily share the same content.

If necessary you can add ExtraData manually as plain string.

MIDs Overriding

Maybe you have a totally crazy controller that does not implement the Mid as the documentation says or you might want to inject your own Mid inheriting another Mid, so you can customize it and add more properties to handle some conversions. Anyway, if you need that, it's possible to override!

Here is an example:

csharp
//This will override Mid 81 with my custom Mid
var interpreter = new MidInterpreter()
                        .UseAllMessages()
                        .UseTimeMessages(new Dictionary { { Mid0081.MID, typeof(OverridedMid0081) } });

var mid = interpreter.Parse("00390081001         2026-08-07:13:45:00");
//mid is an OverridedMid0081

public class OverridedMid0081 : Mid0081
{
    public string FormattedDate
    {
        get => Time.ToString("dd/MM/yyyy HH:mm:ss");
        set => Time = DateTime.Parse(value);
    }

    public OverridedMid0081()
    {

    }
}

Your type must expose a parameterless constructor — that's the one the interpreter compiles and calls.

Adding MIDs that are not in documentation

Maybe your controller is weird and have unknown MID numbers, MIDs that are not in the documentation and you want to inject into MidInterpreter, there is a way:

…

NOTE: Custom messages might not perform as fast as other MIDs because they don't have optimizations for finding it

Advanced Example

Declared a delegate:

csharp
protected delegate void ReceivedCommandActionDelegate(ReceivedMidEventArgs e);

ReceivedMidEventArgs class:

csharp
public class ReceivedMidEventArgs : EventArgs
{
    public Mid ReceivedMid { get; set; }
}

Created a method to register all those MID types by delegates:

…

What was done is registering in a dictionary the correspondent delegate for a determinated MID, once done that we just need to invoke the delegate everytime you face a desired MID.

When a package income:

csharp
pro

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C#atlascontrollercopcoopen-protocol

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言