Saturday, May 14, 2016

IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

/** An actor that slices the input bits and output a consecutive subset
 of the input bits.

 Copyright (c) 1998-2010 The Regents of the University of California.
 All rights reserved.
 Permission is hereby granted, without written agreement and without
 license or royalty fees, to use, copy, modify, and distribute this
 software and its documentation for any purpose, provided that the above
 copyright notice and the following two paragraphs appear in all copies
 of this software.

 IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
 FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
 ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
 THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
 SUCH DAMAGE.

 THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
 PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
 CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
 ENHANCEMENTS, OR MODIFICATIONS.

 PT_COPYRIGHT_VERSION_2
 COPYRIGHTENDKEY

 */
package ptolemy.actor.lib.vhdl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Arrays;

import ptolemy.actor.TypedIOPort;
import ptolemy.data.FixToken;
import ptolemy.data.IntToken;
import ptolemy.data.StringToken;
import ptolemy.data.expr.Parameter;
import ptolemy.data.expr.StringParameter;
import ptolemy.data.type.BaseType;
import ptolemy.kernel.CompositeEntity;
import ptolemy.kernel.util.IllegalActionException;
import ptolemy.kernel.util.NameDuplicationException;
import ptolemy.math.FixPoint;
import ptolemy.math.FixPointQuantization;
import ptolemy.math.Overflow;
import ptolemy.math.Precision;
import ptolemy.math.Rounding;

///////////////////////////////////////////////////////////////////
//// Slice

/**
 Produce an output token on each firing with a FixPoint value that is
 equal to the slicing of the bits of the input token value. The bit width of
 the output token value is determined by taking the difference of parameters
 start and end. The width parameter specifies the bit width of the input
 value. The output FixPoint value is unsigned, and all its bits are integer
 bits. The input can have any scalar type.

 @author Man-Kit Leung
 @version $Id: Slice.java 57040 2010-01-27 20:52:32Z cxh $
 @since Ptolemy II 6.0
 @Pt.ProposedRating Red (mankit)
 @Pt.AcceptedRating Red (mankit)
 */
public class Slice extends FixTransformer {
    /** Construct an actor with the given container and name.
     *  @param container The container.
     *  @param name The name of this actor.
     *  @exception IllegalActionException If the actor cannot be contained
     *   by the proposed container.
     *  @exception NameDuplicationException If the container already has an
     *   actor with this name.
     */
    public Slice(CompositeEntity container, String name)
            throws NameDuplicationException, IllegalActionException {
        super(container, name);

        input = new TypedIOPort(this, "input", true, false);
        input.setMultiport(true);
        input.setTypeEquals(BaseType.FIX);

        start = new Parameter(this, "start");
        end = new Parameter(this, "end");
        lsb = new StringParameter(this, "lsb");
        lsb.setExpression("LSB");
        lsb.addChoice("LSB");
        lsb.addChoice("MSB");
    }

    ///////////////////////////////////////////////////////////////////
    ////                     ports and parameters                  ////

    /**
     * The input port.
     */
    public TypedIOPort input;

    /**
     * The start index for the portion of the bits to be sliced.
     */
    public Parameter start;

    /**
     * The end index for the portion of the bits to be sliced.
     */
    public Parameter end;

    /**
     * Whether start and end index assumes LSB or MSB representation.
     */
    public Parameter lsb;

    ///////////////////////////////////////////////////////////////////
    ////                         public methods                    ////

    /** Output a consecutive subset of the input bits.
     *  If there is no input, then produce no output.
     *  @exception IllegalActionException If there is no director.
     */
    public void fire() throws IllegalActionException {
        super.fire();
        if (input.hasToken(0)) {
            FixToken in = (FixToken) input.get(0);
            int widthValue = in.fixValue().getPrecision().getNumberOfBits();
            int startValue = ((IntToken) start.getToken()).intValue();
            int endValue = ((IntToken) end.getToken()).intValue() + 1;
            boolean lsbValue = ((StringToken) lsb.getToken()).stringValue()
                    .equals("LSB");

            int newStartValue = (lsbValue) ? widthValue - endValue : startValue;
            int newEndValue = (lsbValue) ? widthValue - startValue : endValue;
            int shiftBits = (lsbValue) ? startValue : widthValue - endValue;

            char[] mask = new char[widthValue];
            Arrays.fill(mask, '0');
            Arrays.fill(mask, newStartValue, newEndValue, '1');

            BigDecimal value = new BigDecimal(in.fixValue().getUnscaledValue()
                    .and(new BigInteger(new String(mask), 2)).shiftRight(
                            shiftBits));
            Precision precision = new Precision(
                    ((Parameter) getAttribute("outputPrecision"))
                            .getExpression());
            if ((newEndValue - newStartValue) != precision.getNumberOfBits()) {
                throw new IllegalActionException(this, "Bit width of "
                        + (newEndValue - newStartValue)
                        + " is not equal to precision " + precision);
            }

            Overflow overflow = Overflow
                    .getName(((Parameter) getAttribute("outputOverflow"))
                            .getExpression().toLowerCase());

            Rounding rounding = Rounding
                    .getName(((Parameter) getAttribute("outputRounding"))
                            .getExpression().toLowerCase());

            FixPoint result = new FixPoint(value, new FixPointQuantization(
                    precision, overflow, rounding));

            sendOutput(output, 0, new FixToken(result));
        }
    }
}

BOOST SIEMENS

OPCHANDLE hClient;
    FILETIME ftTimeStamp;
    WORD wQuality;
    WORD wReserved;
    VARIANT vDataValue;

http://msdn.microsoft.com/en-us/library/ms220948(v=vs.80).aspx
http://vld.codeplex.com/downloads/get/342350
http://stackoverflow.com/questions/395123/raii-and-smart-pointers-in-c
http://www.microsoft.com/en-us/download/details.aspx?id=20028 
http://www.cplusplus.com/forum/general/8070/ 


#define _CRTDBG_MAP_ALLOC
#include 
#include  

//LEAKS
 _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

$IpValue=[EDITA1]$Devices=[EDITA2]$Target=[TARGETDIR]


1) Create AgentConfigurationEx, then call "thread" 
2) thread reads all the configurations, spawns OPC clients per configuration
3) call Agent.main()



 # ResetAtMidnight determines whether service is reset at midnite
 ResetAtMidnight=false
 
 #User=.,auduser,SUNRISE

 Language=English

 # Synchronous read of data, if so how ofen (ServerRate) in ms 
 ServerRate = 1000
 QueryServerPeriod=5000
 AutoReconnectMaxAttempts=0 



 for(int i=0; i< _machines.size(); i++)
 {
  if(_machines[i]->IsConnected() )
  {
   try
   {
    // static boost::mutex _alarm_mutex; - declare as static in shared class...
    //boost::mutex::scoped_lock  lock(_alarm_mutex);
    _machines[i]->_CriticalSection.Lock();
    _machines[i]->ExportValues();
    _machines[i]->_CriticalSection.Unlock();

   }
   catch(...)
   {
    GLogger << INFO << "MtcOpcAdapter::gatherDeviceData() exception "  << std::endl;
   }
  }
 }
 /*
  Threading to allow service to behave properly at startup/shutdown
 */
 CWorkerThread<> _workerthread;
 CWorkerThread<> _enderthread;
 struct CStartThread : public IWorkerThreadClient
 {
  CStartThread()
  { 
   _hEvent.Attach(CreateEvent(NULL, TRUE, FALSE, NULL)); 
  }
  HRESULT Execute(DWORD_PTR dwParam, HANDLE hObject);
  HRESULT CloseHandle(HANDLE){ return S_OK; }
  CHandle _hEvent;
 } _StartThread;

 struct CEndThread : public IWorkerThreadClient
 {
  CEndThread()
  { 
   _hEvent.Attach(CreateEvent(NULL, TRUE, FALSE, NULL)); 
  }
  HRESULT Execute(DWORD_PTR dwParam, HANDLE hObject);
  HRESULT CloseHandle(HANDLE){ return S_OK; }
  CHandle _hEvent;
 } _EndThread;
 
 // OPC Specific threading to allow bad opc servers to reset
 CWorkerThread<> _resetthread;
 struct CResetThread : public IWorkerThreadClient
 {
  HRESULT Execute(DWORD_PTR dwParam, HANDLE hObject);
  HRESULT CloseHandle(HANDLE){ ::CloseHandle(_hTimer); return S_OK; }
  HANDLE _hTimer;
 } _ResetThread;
TODO:

1) SHDR Tags to finish:

1. uuid
2. manufacturer
3. station
4. serialNumber

0x80041008 WBEM_E_INVALID_PARAMETER

his is what I did in my vbs script to open a firewall exception for the service. I couldn't use the standard interactive pop-up for a service (that asks for permission to open the firewall), since it doesn't have a UI.

set oShell  = CreateObject("WScript.shell")
oShell.run "cmd /C netsh advfirewall firewall add rule program=""C:\Program Files (x86)\foo\bar\prog.exe"" name=""my-service"" dir=in action=allow"  
I added this vbs script to the "Commit" CustomAction of the Setup&Deployment Project, leaving the properties as defaults.

To debug problems with the vbs stage, I ran the msi from DOS using

msiexec /i mysetup.msi /L* install.log
Note that I originally used "Wscript.CreateObject" but that failed. This worked.

UINT result = 0;
TCHAR szQuery[] = "SELECT DefaultDir FROM Directory";
PMSIHANDLE hDB = NULL;
PMSIHANDLE hView = NULL;
PMSIHANDLE hRecord = NULL;
hDB = MsiGetActiveDatabase( hModule );
result = MsiDatabaseOpenView( hDB, szQuery, &hView );
result = MsiViewExecute( hView, hRecord );
while (MsiViewFetch( hView, &hRecord ) == ERROR_SUCCESS)
{
TCHAR szCurDir[MAX_PATH] = {0};
DWORD dwDirLen = MAX_PATH;
if (MsiRecordGetString( hRecord, 1, szCurDir, &dwDirLen) != ERROR_SUCCESS )
break; // fail. break out of the while loop.
// Do something. This sample code just pops up a message box. 
MsiMessageBox(hModule, szCurDir, MB_OK);
} 


2) Connecting to the Siemens 840D to receive shutdown notifications.
#import "IregieSvr.dll"

 CComPtr server;
 
 OutputDebugString("Connecting to Siemens 840D Regie Server");
 CComVariant v1=hwndMainFrame;
 CComVariant v2;
 ::ShowWindow(hwndMainFrame, SW_MINIMIZE);
 ::ShowWindow(hwndMainFrame, SW_SHOW);
 if(FAILED(hr=server.CoCreateInstance(__uuidof(RegieSvr), NULL, CLSCTX_SERVER)))
  throw CString (_T("CoCreateInstance Siemens 830D RegieSvr FAILED"));
 if(FAILED(hr=server->InitSvr(v1,v2)))
  throw CString (_T("InitSvr(v1,v2) FAILED"));
 if(FAILED(hr=server->InitCompleteEx()))
  throw CString (_T("InitCompleteEx FAILED"));

  std::string ipaddr="127.0.0.1,127.0.0.2";
  std::string devices="M1,M3";

  std::string contents; 
  ReadFile(::ExeDirectory()+"AgentShdr.ini", contents);

  ReplacePattern(contents, "ServerMachineName", "\n", "ServerMachineName=" + ipaddr + "\n");
  ReplacePattern(contents, "MTConnectDevice", "\n", "MTConnectDevice=" + devices + "\n");

  std::vector ips=TrimmedTokenize(ipaddr,",");
  std::vector devs=TrimmedTokenize(devices,",");
  if(ips.size() != devs.size())
   ::MessageBox(NULL, "Mismatched # ips and devices", "Error", MB_OK);
  std::string tagsection="SIEMENS";
  for(int i=1; i< ips.size(); i++)
  {
   tagsection+=",SIEMENS";
  }
  ReplacePattern(contents, "OpcTags", "\n", "OpcTags=" + tagsection + "\n");
  WriteFile(::ExeDirectory()+"AgentShdr1.ini",contents);

Man in the Rain