gomcprotocol

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 26, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

README

gomcprotocol

日本語版はこちら

A Go library for communicating with Mitsubishi PLCs using the MC Protocol (SLMP).

Features

  • 3E frame — TCP and UDP transport, Binary and ASCII mode
  • 4E frame — TCP, Binary and ASCII mode, with serial number tracking
  • Batch read/write: words and bits
  • Random read/write: multiple devices in a single request
  • Remote control: Run, Stop, Pause, Latch Clear, Reset
  • Goroutine-safe: requests on the same client instance are serialized internally

REST Wrapper API

A REST API wrapper for this library is available at Moge800/gomc-rest. Use it when you want to expose MC Protocol communication over HTTP from another application or service.

Installation

go get github.com/moge800/gomcprotocol@latest

# use the latest v1.x release
go get github.com/moge800/gomcprotocol@v1
import "github.com/moge800/gomcprotocol"

Quick Start

3E frame (TCP)
package main

import (
    "fmt"
    mc "github.com/moge800/gomcprotocol"
)

func main() {
    c, err := mc.New3EClient("192.168.0.1", 5007, mc.ModeBinary)
    if err != nil {
        panic(err)
    }
    if err := c.Connect(); err != nil {
        panic(err)
    }
    defer c.Close()

    // Read 5 words from D100
    words, err := c.ReadWords("D", 100, 5)
    if err != nil {
        panic(err)
    }
    fmt.Println(words)

    // Write to D200
    if err := c.WriteWords("D", 200, []uint16{1, 2, 3}); err != nil {
        panic(err)
    }
}
3E frame (UDP)
c, err := mc.New3EClientUDP("192.168.0.1", 5007, mc.ModeBinary)
4E frame
c, err := mc.New4EClient("192.168.0.1", 5007, mc.ModeBinary)

API Reference

Client3E
Method Description
New3EClient(host, port, mode) Create a 3E TCP client
New3EClientUDP(host, port, mode) Create a 3E UDP client
Connect() Establish connection
Close() Close connection
ReadWords(device, start, count) Read word values
WriteWords(device, start, values) Write word values
ReadBits(device, start, count) Read bit values
WriteBits(device, start, values) Write bit values
RandomRead(words, dwords) Read multiple devices at once
RandomWrite(words, wordVals, dwords, dwordVals) Write multiple devices at once
RandomWriteBits(devices, values) Write multiple bit devices at once
RemoteRun(clearMode, force) Start PLC remotely
RemoteStop() Stop PLC remotely
RemotePause(force) Pause PLC remotely
RemoteLatchClear() Clear latch (PLC must be stopped)
RemoteReset() Reset PLC (connection will close)

Client4E provides the same methods as Client3E, created via New4EClient.

Requests issued concurrently on the same client instance are serialized internally, so only one MC Protocol request/response exchange is active on that connection at a time.

Modes
Constant Description
ModeBinary Binary framing (compact, recommended)
ModeASCII ASCII framing (human-readable)
Supported Devices
Device Type Notes
D Word Data register
W Word Link register
R Word File register
ZR Word File register (extended)
SW Word Link special register
TN Word Timer current value
STN Word Retentive timer current value
CN Word Counter current value
Z Word Index register
X Bit Input
Y Bit Output
M Bit Internal relay
L Bit Latch relay
V Bit Edge relay
S Bit Step relay
DX Bit Direct access input
DY Bit Direct access output
TC Bit Timer coil
TS Bit Timer contact
STC Bit Retentive timer coil
STS Bit Retentive timer contact
CC Bit Counter coil
CS Bit Counter contact
B Bit Link relay
F Bit Annunciator
SB Bit Link special relay
SM Bit Special relay
SD Word Special register

Device names are case-insensitive ("d" and "D" both work).

Random Access
// Read D100 (word) and D200 (word) and D300 (dword) in one request
words, dwords, err := c.RandomRead(
    []mc.DeviceAddr{{"D", 100}, {"D", 200}},
    []mc.DeviceAddr{{"D", 300}},
)

// Write D100=10, D200=20 (words) and D300=100000 (dword)
err = c.RandomWrite(
    []mc.DeviceAddr{{"D", 100}, {"D", 200}},
    []uint16{10, 20},
    []mc.DeviceAddr{{"D", 300}},
    []uint32{100000},
)

// Write bits to M0, M10, Y5
err = c.RandomWriteBits(
    []mc.DeviceAddr{{"M", 0}, {"M", 10}, {"Y", 5}},
    []bool{true, false, true},
)
Error Handling
words, err := c.ReadWords("D", 100, 5)
if err != nil {
    if mcErr, ok := err.(*mc.MCProtocolError); ok {
        // PLC returned a non-zero end code
        fmt.Printf("PLC error: 0x%04X\n", mcErr.EndCode)
    } else {
        // Network or connection error
        fmt.Println("connection error:", err)
    }
}

PLC Setup

The PLC must have Ethernet communication enabled with SLMP (MC Protocol) configured.
Default port is typically 5007 for Q/iQ-R series.

Examples

Runnable examples are in the examples/ directory:

Directory Description
01_basic_read Read word devices (minimal)
02_basic_write Write words and read back
03_bit_operations Read/write bit devices (X, M, Y)
04_random_access RandomRead/RandomWrite across multiple devices
05_remote_control Stop → LatchClear → Run sequence
06_monitor Polling loop with change detection and auto-reconnect

License

Apache License, Version 2.0

Documentation

Overview

Package gomcprotocol implements Mitsubishi MC Protocol clients for 3E and 4E frames over TCP and UDP transports.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client3E

type Client3E struct {
	// contains filtered or unexported fields
}

Client3E is a 3E frame MC Protocol client (TCP or UDP). Safe for concurrent use; requests are serialized by an internal mutex.

func New3EClient

func New3EClient(host string, port int, mode Mode) (*Client3E, error)

New3EClient creates a new 3E frame client. Call Connect before use.

func New3EClientUDP

func New3EClientUDP(host string, port int, mode Mode) (*Client3E, error)

New3EClientUDP creates a new 3E frame client using UDP transport. Call Connect before use.

func (*Client3E) Close

func (c *Client3E) Close() error

Close closes the connection.

func (*Client3E) Connect

func (c *Client3E) Connect() error

Connect establishes the connection to the PLC (TCP or UDP).

func (*Client3E) RandomRead

func (c *Client3E) RandomRead(words, dwords []DeviceAddr) ([]uint16, []uint32, error)

RandomRead reads word (2-byte) and dword (4-byte) values from multiple devices in a single request (command 0x0403).

func (*Client3E) RandomWrite

func (c *Client3E) RandomWrite(words []DeviceAddr, wordVals []uint16, dwords []DeviceAddr, dwordVals []uint32) error

RandomWrite writes word (2-byte) and dword (4-byte) values to multiple devices in a single request (command 0x1402, subcmd 0x0000).

func (*Client3E) RandomWriteBits

func (c *Client3E) RandomWriteBits(devices []DeviceAddr, values []bool) error

RandomWriteBits writes individual bit values to multiple devices in a single request (command 0x1402, subcmd 0x0001).

func (*Client3E) ReadBits

func (c *Client3E) ReadBits(device string, start, count int) ([]bool, error)

ReadBits reads count bit values from device starting at address start.

func (*Client3E) ReadWords

func (c *Client3E) ReadWords(device string, start, count int) ([]uint16, error)

ReadWords reads count word values from device starting at address start.

func (*Client3E) RemoteLatchClear

func (c *Client3E) RemoteLatchClear() error

RemoteLatchClear clears the latch remotely (command 0x1005). The PLC must be stopped before calling this.

func (*Client3E) RemotePause

func (c *Client3E) RemotePause(force bool) error

RemotePause pauses the PLC CPU remotely (command 0x1003).

func (*Client3E) RemoteReset

func (c *Client3E) RemoteReset() error

RemoteReset resets the PLC remotely (command 0x1006). The PLC must be stopped before calling this. The connection may be closed by the PLC before a response is received.

func (*Client3E) RemoteRun

func (c *Client3E) RemoteRun(clearMode int, force bool) error

RemoteRun starts the PLC CPU remotely (command 0x1001).

clearMode: 0 = no clear, 1 = clear except latch, 2 = clear all
force:     true to execute even if another device is controlling remotely

func (*Client3E) RemoteStop

func (c *Client3E) RemoteStop() error

RemoteStop stops the PLC CPU remotely (command 0x1002).

func (*Client3E) SetTimeout

func (c *Client3E) SetTimeout(d time.Duration)

SetTimeout sets the per-request I/O deadline and the connect timeout. A value of 0 or less disables both the per-request deadline and the connect timeout (Connect will block until the OS times out). Default is 5 seconds.

func (*Client3E) WriteBits

func (c *Client3E) WriteBits(device string, start int, values []bool) error

WriteBits writes bit values to device starting at address start.

func (*Client3E) WriteWords

func (c *Client3E) WriteWords(device string, start int, values []uint16) error

WriteWords writes values to device starting at address start.

type Client4E

type Client4E struct {
	// contains filtered or unexported fields
}

Client4E is a 4E frame MC Protocol client (TCP only). The 4E frame extends 3E by adding a serial number and reserved field. Safe for concurrent use; requests are serialized by an internal mutex.

func New4EClient

func New4EClient(host string, port int, mode Mode) (*Client4E, error)

New4EClient creates a new 4E frame client. Call Connect before use.

func (*Client4E) Close

func (c *Client4E) Close() error

Close closes the TCP connection.

func (*Client4E) Connect

func (c *Client4E) Connect() error

Connect establishes the TCP connection to the PLC.

func (*Client4E) RandomRead

func (c *Client4E) RandomRead(words, dwords []DeviceAddr) ([]uint16, []uint32, error)

RandomRead reads word and dword values from multiple devices (command 0x0403).

func (*Client4E) RandomWrite

func (c *Client4E) RandomWrite(words []DeviceAddr, wordVals []uint16, dwords []DeviceAddr, dwordVals []uint32) error

RandomWrite writes word and dword values to multiple devices (command 0x1402, subcmd 0x0000).

func (*Client4E) RandomWriteBits

func (c *Client4E) RandomWriteBits(devices []DeviceAddr, values []bool) error

RandomWriteBits writes individual bit values to multiple devices (command 0x1402, subcmd 0x0001).

func (*Client4E) ReadBits

func (c *Client4E) ReadBits(device string, start, count int) ([]bool, error)

ReadBits reads count bit values from device starting at address start.

func (*Client4E) ReadWords

func (c *Client4E) ReadWords(device string, start, count int) ([]uint16, error)

ReadWords reads count word values from device starting at address start.

func (*Client4E) RemoteLatchClear added in v0.2.0

func (c *Client4E) RemoteLatchClear() error

RemoteLatchClear clears the latch remotely (command 0x1005). The PLC must be stopped before calling this.

func (*Client4E) RemotePause added in v0.2.0

func (c *Client4E) RemotePause(force bool) error

RemotePause pauses the PLC CPU remotely (command 0x1003).

func (*Client4E) RemoteReset added in v0.2.0

func (c *Client4E) RemoteReset() error

RemoteReset resets the PLC remotely (command 0x1006). The PLC must be stopped before calling this. The connection may be closed by the PLC before a response is received.

func (*Client4E) RemoteRun added in v0.2.0

func (c *Client4E) RemoteRun(clearMode int, force bool) error

RemoteRun starts the PLC CPU remotely (command 0x1001).

clearMode: 0 = no clear, 1 = clear except latch, 2 = clear all
force:     true to execute even if another device is controlling remotely

func (*Client4E) RemoteStop added in v0.2.0

func (c *Client4E) RemoteStop() error

RemoteStop stops the PLC CPU remotely (command 0x1002).

func (*Client4E) SetTimeout

func (c *Client4E) SetTimeout(d time.Duration)

SetTimeout sets the per-request I/O deadline and the connect timeout. A value of 0 or less disables both the per-request deadline and the connect timeout (Connect will block until the OS times out). Default is 5 seconds.

func (*Client4E) WriteBits

func (c *Client4E) WriteBits(device string, start int, values []bool) error

WriteBits writes bit values to device starting at address start.

func (*Client4E) WriteWords

func (c *Client4E) WriteWords(device string, start int, values []uint16) error

WriteWords writes values to device starting at address start.

type DeviceAddr

type DeviceAddr struct {
	Device string
	Addr   int
}

DeviceAddr identifies a single device point for random-access operations.

type MCProtocolConnectionError

type MCProtocolConnectionError struct {
	// contains filtered or unexported fields
}

MCProtocolConnectionError is returned on network-level failures.

func (*MCProtocolConnectionError) Error

func (e *MCProtocolConnectionError) Error() string

type MCProtocolError

type MCProtocolError struct {
	EndCode uint16
}

MCProtocolError is returned when the PLC responds with a non-zero end code.

func (*MCProtocolError) Error

func (e *MCProtocolError) Error() string

type Mode

type Mode int

Mode selects binary or ASCII framing.

const (
	ModeBinary Mode = iota // binary (3E/4E) framing
	ModeASCII              // ASCII (3E/4E) framing
)

Directories

Path Synopsis
examples
01_basic_read command
01_basic_read: PLCからワードデバイスを読み取る最小限のサンプル。
01_basic_read: PLCからワードデバイスを読み取る最小限のサンプル。
02_basic_write command
02_basic_write: ワードデバイスへの書き込みと読み返しのサンプル。
02_basic_write: ワードデバイスへの書き込みと読み返しのサンプル。
03_bit_operations command
03_bit_operations: ビットデバイス(M, X, Y)の読み書きサンプル。
03_bit_operations: ビットデバイス(M, X, Y)の読み書きサンプル。
04_random_access command
04_random_access: バラバラなアドレスをまとめて1リクエストで読み書きするサンプル。
04_random_access: バラバラなアドレスをまとめて1リクエストで読み書きするサンプル。
05_remote_control command
05_remote_control: PLCのリモート操作(停止・ラッチクリア・起動)サンプル。
05_remote_control: PLCのリモート操作(停止・ラッチクリア・起動)サンプル。
06_monitor command
06_monitor: 複数デバイスを定期ポーリングし、値が変化したら表示するサンプル。
06_monitor: 複数デバイスを定期ポーリングし、値が変化したら表示するサンプル。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL