forked from engina/PLCNetLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathControl.cs
125 lines (112 loc) · 3.62 KB
/
Control.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using ENDA.PLCNetLib;
namespace plcctrl
{
public class Control
{
IPEndPoint m_ip = null;
TcpClient m_client;
string m_pass;
PLC plc;
public Control(IPEndPoint ip, string pass)
{
m_ip = ip;
plc = new PLC(ip, pass);
plc.Connect();
}
public bool UpdateFW(string path)
{
plc.Cmd("program enable");
Console.Out.WriteLine("Programming enabled.");
TcpClient downloader = new TcpClient();
downloader.Connect(m_ip.Address, 61163);
Socket sock = downloader.Client;
byte[] data = new byte[16];
sock.Receive(data);
string str = ASCIIEncoding.ASCII.GetString(data);
if (!str.StartsWith("Access granted"))
{
Console.Error.WriteLine("Access not granted");
downloader.Close();
return false;
}
Console.Out.Write("Sending firmware ");
FileStream fs = new FileStream(path, FileMode.Open);
data = new byte[1024];
int r = 0;
while((r = fs.Read(data,0,data.Length))!=0)
{
downloader.Client.Send(data, r, 0);
Console.Out.Write(".");
}
data = new byte[22];
sock.Receive(data);
str = ASCIIEncoding.ASCII.GetString(data);
if (!str.StartsWith("Firmware programmed"))
{
Console.Error.WriteLine("Could not program firmware.");
downloader.Close();
return false;
}
Console.Out.WriteLine("\nProgrammed. Rebooting.");
Cmd("reboot");
return true;
}
public bool Prog(string path)
{
plc.Cmd("program enable");
TcpClient downloader = new TcpClient();
downloader.Connect(m_ip.Address, 61163);
Socket sock = downloader.Client;
byte[] data = new byte[16];
sock.Receive(data);
string str = ASCIIEncoding.ASCII.GetString(data);
if (!str.StartsWith("Access granted"))
{
Console.Error.WriteLine("Access not granted");
downloader.Close();
return false;
}
Console.Out.Write("Sending program ");
FileStream fs = new FileStream(path, FileMode.Open);
data = new byte[1024];
int r = 0;
while ((r = fs.Read(data, 0, data.Length)) != 0)
{
downloader.Client.Send(data, r, 0);
Console.Out.Write(".");
}
data = new byte[22];
sock.Receive(data);
str = ASCIIEncoding.ASCII.GetString(data);
if (!str.StartsWith("Programmed"))
{
Console.Error.WriteLine("Could not programmed.");
downloader.Close();
return false;
}
return true;
}
public bool ProgRun(string path)
{
return Prog(path) && Run();
}
public bool Run()
{
return plc.Run();
}
public bool Stop()
{
return plc.Stop();
}
internal void Cmd(string p)
{
plc.Cmd(p);
}
}
}