Skip to main content

How can I toggle the relay (Digital Outputs – DO) of a MOXA device in BVMS?

Question

How can I toggle the relay (Digital Outputs – DO) of a MOXA device in BVMS?

Answer

MOXA devices (such as E1214) can be integrated with BVMS by using their REST API to control digital outputs (DO). Similar integration can be done for any device that supports REST API (other example is IP Horn speakers).

The MOXA E1214 provides Digital Input (DI) and Digital Output (DO) status through its web interface, and a sample scriplet is available below, that demonstrates how to toggle the relay (DO) on the MOXA device:

NONE
// ScriptType: ClientScript
// ScriptLanguage: CS

using System;
using System.Diagnostics;
using System.Collections.Generic;
using log4net;
using Bosch.Vms.Core;
using Bosch.Vms.SDK;
using System.IO;
using System.Net;
using System.Text;

[BvmsScriptClass()]
public class ClientScript : IDisposable
{
    private readonly IClientApi Api;
    private readonly ILog Logger;    
	
	private string deviceIp = "10.10.20.17";
	private string Username = "admin";
    private string Password = "moxa"; 

    public ClientScript(IClientApi api)
    {
        this.Logger = LogManager.GetLogger("ClientScript");
        this.Api = api;        
    }

    public void Dispose()
    {
        // Use this method to cleanup any resources here (consider fully implementing the Dispose pattern).
        // For example, stop and dispose any started timers. Ensure that all threads that were started are stopped here.
        // DO NOT BLOCK in this method for a very long time, as this may block the applications current activity.
    }
	
	public void SetD0(int relayIndex, bool turnOn)
	{
      
    
       if (relayIndex < 0 || relayIndex > 5)
        throw new Exception("Invalid relay index");

    int value = turnOn ? 1 : 0;

    var url = "http://" + deviceIp + "/api/slot/0/io/relay";

    // Base JSON template (all relays OFF by default)
    string json = @"{
      ""slot"": 0,
      ""io"": {
        ""relay"": [
          { ""relayIndex"": 0, ""relayMode"": 0, ""relayStatus"": 0, ""relayTotalCount"": 1, ""relayCurrentCount"": 1, ""relayCurrentCountReset"": 0 },
          { ""relayIndex"": 1, ""relayMode"": 0, ""relayStatus"": 0, ""relayTotalCount"": 4294967295, ""relayCurrentCount"": 4294967295, ""relayCurrentCountReset"": 0 },
          { ""relayIndex"": 2, ""relayMode"": 0, ""relayStatus"": 0, ""relayTotalCount"": 4294967295, ""relayCurrentCount"": 4294967295, ""relayCurrentCountReset"": 0 },
          { ""relayIndex"": 3, ""relayMode"": 0, ""relayStatus"": 0, ""relayTotalCount"": 4294967295, ""relayCurrentCount"": 4294967295, ""relayCurrentCountReset"": 0 },
          { ""relayIndex"": 4, ""relayMode"": 0, ""relayStatus"": 0, ""relayTotalCount"": 4294967295, ""relayCurrentCount"": 4294967295, ""relayCurrentCountReset"": 0 },
          { ""relayIndex"": 5, ""relayMode"": 0, ""relayStatus"": 0, ""relayTotalCount"": 4294967295, ""relayCurrentCount"": 4294967295, ""relayCurrentCountReset"": 0 }
        ]
      }
    }";

    // Replace relayStatus for the selected relay
    string find = "\"relayIndex\": " + relayIndex + ", \"relayMode\": 0, \"relayStatus\": 0";
    string replace = "\"relayIndex\": " + relayIndex + ", \"relayMode\": 0, \"relayStatus\": " + value;

    json = json.Replace(find, replace);
		

        var request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "PUT";
        request.ContentType = "application/json";
		request.Accept = "vdn.dac.v1";
        request.Timeout = 5000;
		
		 
        string svcCredentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(Username + ":" + Password));
		request.Headers.Add("Authorization", "Basic " + svcCredentials);

        
        byte[] body = Encoding.UTF8.GetBytes(json);
        request.ContentLength = body.Length;

        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(body, 0, body.Length);
        }

        using (HttpWebResponse response =
               (HttpWebResponse)request.GetResponse())
        {
            if (response.StatusCode != HttpStatusCode.OK &&
                response.StatusCode != HttpStatusCode.NoContent)
            {
                throw new Exception("Failed to set D0");
            }
        }
    }

	
    [Scriptlet("c2f530c5-ee6a-4ab2-ace6-49778bc3aa4e")]
    public void MoxaRelay_On()
	{
    	try
    	{
			// Turn D0 ON
			SetD0(0,true);
	
			
		}
    	catch (Exception ex)
    	{
			// Handle or log error
			Api.ApplicationManager.ShowMessage("Exception" + ex);
    	}
	}
	
	

    [Scriptlet("ad61303d-dbc9-4c10-a7e4-a94494c375cd")]
    public void MoxaRelay_Off()
    {
       try
    	{
		
			// Turn D0 OFF
			SetD0(0, false);
		}
    	catch (Exception ex)
    	{
			// Handle or log error
			Api.ApplicationManager.ShowMessage("Exception" + ex);
    	}
    }
}

Note

MOXA E1214 has I/O Status on web interface for: 

  • DO - Digital output

  • DI - Digital input

DI can not be toggled via REST API

The correct URI for DO is provided in the MOXA documentation - /api/slot/0/io/relay

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.