0

我有一个 Windows 服务,只要 OPC 服务器(KepServer)的数据发生变化,它就会插入数据库。当我从 Windows 7 的服务任务管理器手动启动服务时,服务插入正确。但服务在系统启动时仅插入一行数据,而所需的行数必须为 20。因为它是 Windows 服务,调试起来很困难,而且也没有给出任何错误。

贾格

操作系统:Windows 7;数据库:SQL Server Express;赢服务:在管理员下运行

我的代码:

Protected Overrides Sub OnStart(ByVal args() As String)
    ' Add code here to start your service. 
    'Create a new OPC Server object

    ConnectedOPCServer = New OPCServer
    ConnectedOPCServer.Connect("KEPware.KEPServerEx.V5")
    Try
        ' Add the group and set its update rate
        ConnectedServerGroups = ConnectedOPCServer.OPCGroups
        ConnectedGroup = ConnectedServerGroups.Add("Test1")
    Catch ex As Exception
        ' Error handling
    End Try

    ' Set the update rate for the group
    ConnectedGroup.UpdateRate = 400

    ' Subscribe the group so that you will be able to get the data change
    ' callbacks from the server
    ConnectedGroup.IsSubscribed = True

    ItemCount = 3
    OPCItemIDs(1) = "Channel2.Device1.EndDate"
    OPCItemIDs(2) = "Channel2.Device1.Material"
    OPCItemIDs(3) = "Channel2.Device1.BatchSchedule"
    ClientHandles(1) = 1
    ClientHandles(2) = 2
    ClientHandles(3) = 3
    Try
        ' Establish a connection to the OPC item interface of the connected group
        OPCItemCollection = ConnectedGroup.OPCItems
        OPCItemCollection.DefaultIsActive = True
        OPCItemCollection.AddItems(ItemCount, OPCItemIDs, ClientHandles, ItemServerHandles, ItemServerErrors)
    Catch ex As Exception
        ' Error handling
    End Try
    EventLog1.WriteEntry("In OnStart")
End Sub

Public Sub ConnectedGroup_DataChange(ByVal TransactionID As Integer, ByVal NumItems As Integer, ByRef ClientHandles As System.Array, ByRef ItemValues As System.Array, ByRef Qualities As System.Array, ByRef TimeStamps As System.Array) Handles ConnectedGroup.DataChange

    'This is my sub which inserts into database in the event of data change from OPC Server
    Const NoOfItems = 3

    Dim ObjOPCItem As OPCAutomation.OPCItem
    Dim Array_Values(NoOfItems) As Object


    For Each ObjOPCItem In OPCItemCollection
        Array_Values(ObjOPCItem.ClientHandle) = ObjOPCItem.Value
    Next
    ObjOPCItem = Nothing

    Dim sql As String

    sql = "INSERT INTO BatchReport (BatchCode,BatchNumber)VALUES(@AV,@AVa);"

    If Array_Values(3) < 20 Then
        Try
            connection.Open()
            dataadapter.InsertCommand = New SqlCommand(sql, connection)
            dataadapter.InsertCommand.Parameters.Add("@AV", SqlDbType.Int, 4).Value = Array_Values(1)
            dataadapter.InsertCommand.Parameters.Add("@AVa", SqlDbType.Int, 4).Value = Array_Values(3)
            dataadapter.InsertCommand.ExecuteNonQuery()
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
        connection.Close()
    End If
End Sub
4

0 回答 0