Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ExpansionManager.cpp « CAN « src - github.com/Duet3D/RepRapFirmware.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 53fa5acc33d70a110adaae5ff92005d66fa5eb69 (plain)
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*
 * ExpansionManager.cpp
 *
 *  Created on: 4 Feb 2020
 *      Author: David
 */

#include "ExpansionManager.h"

#if SUPPORT_CAN_EXPANSION

#include <CAN/CanInterface.h>
#include <Platform/RepRap.h>
#include <Platform/Platform.h>
#include <GCodes/GCodeBuffer/GCodeBuffer.h>

ExpansionBoardData::ExpansionBoardData() noexcept : typeName(nullptr), state(BoardState::unknown), numDrivers(0)
{
	mcuTemp.min = mcuTemp.max = mcuTemp.current = vin.max = vin.min = vin.current = v12.max = v12.min = v12.current = 0.0;
}

#if SUPPORT_OBJECT_MODEL

// Object model table and functions
// Note: if using GCC version 7.3.1 20180622 and lambda functions are used in this table, you must compile this file with option -std=gnu++17.
// Otherwise the table will be allocate in RAM instead of flash, which wastes too much RAM.

// Macro to build a standard lambda function that includes the necessary type conversions
#define OBJECT_MODEL_FUNC(...) OBJECT_MODEL_FUNC_BODY(ExpansionManager, __VA_ARGS__)

constexpr ObjectModelTableEntry ExpansionManager::objectModelTable[] =
{
	// 0. boards[] members
	{ "canAddress",			OBJECT_MODEL_FUNC((int32_t)(&(self->FindIndexedBoard(context.GetLastIndex())) - self->boards)),					ObjectModelEntryFlags::none },
	{ "firmwareFileName",	OBJECT_MODEL_FUNC(self->FindIndexedBoard(context.GetLastIndex()).typeName, ExpansionDetail::firmwareFileName),	ObjectModelEntryFlags::none },
	{ "firmwareVersion",	OBJECT_MODEL_FUNC(self->FindIndexedBoard(context.GetLastIndex()).typeName, ExpansionDetail::firmwareVersion),	ObjectModelEntryFlags::none },
	{ "maxMotors",			OBJECT_MODEL_FUNC((int32_t)self->FindIndexedBoard(context.GetLastIndex()).numDrivers),							ObjectModelEntryFlags::verbose },
	{ "mcuTemp",			OBJECT_MODEL_FUNC(self, 1),																						ObjectModelEntryFlags::live },
	{ "shortName",			OBJECT_MODEL_FUNC(self->FindIndexedBoard(context.GetLastIndex()).typeName, ExpansionDetail::shortName),			ObjectModelEntryFlags::none },
	{ "state",				OBJECT_MODEL_FUNC(self->FindIndexedBoard(context.GetLastIndex()).state.ToString()),								ObjectModelEntryFlags::none },
	{ "v12",				OBJECT_MODEL_FUNC(self, 3),																						ObjectModelEntryFlags::live },
	{ "vIn",				OBJECT_MODEL_FUNC(self, 2),																						ObjectModelEntryFlags::live },

	// 1. mcuTemp members
	{ "current",			OBJECT_MODEL_FUNC(self->FindIndexedBoard(context.GetLastIndex()).mcuTemp.current, 1),							ObjectModelEntryFlags::live },
	{ "max",				OBJECT_MODEL_FUNC(self->FindIndexedBoard(context.GetLastIndex()).mcuTemp.max, 1),								ObjectModelEntryFlags::none },
	{ "min",				OBJECT_MODEL_FUNC(self->FindIndexedBoard(context.GetLastIndex()).mcuTemp.min, 1),								ObjectModelEntryFlags::none },

	// 2. vIn members
	{ "current",			OBJECT_MODEL_FUNC(self->FindIndexedBoard(context.GetLastIndex()).vin.current, 1),								ObjectModelEntryFlags::live },
	{ "max",				OBJECT_MODEL_FUNC(self->FindIndexedBoard(context.GetLastIndex()).vin.max, 1),									ObjectModelEntryFlags::none },
	{ "min",				OBJECT_MODEL_FUNC(self->FindIndexedBoard(context.GetLastIndex()).vin.min, 1),									ObjectModelEntryFlags::none },

	// 3. v12 members
	{ "current",			OBJECT_MODEL_FUNC(self->FindIndexedBoard(context.GetLastIndex()).v12.current, 1),								ObjectModelEntryFlags::live },
	{ "max",				OBJECT_MODEL_FUNC(self->FindIndexedBoard(context.GetLastIndex()).v12.max, 1),									ObjectModelEntryFlags::none },
	{ "min",				OBJECT_MODEL_FUNC(self->FindIndexedBoard(context.GetLastIndex()).v12.min, 1),									ObjectModelEntryFlags::none },
};

constexpr uint8_t ExpansionManager::objectModelTableDescriptor[] =
{
	4,				// number of sections
	9,				// section 0: boards[]
	3,				// section 1: mcuTemp
	3,				// section 2: vIn
	3				// section 3: v12
};

DEFINE_GET_OBJECT_MODEL_TABLE(ExpansionManager)

#endif

ExpansionManager::ExpansionManager() noexcept : numExpansionBoards(0), numBoardsFlashing(0), lastIndexSearched(0), lastAddressFound(0)
{
	// the boards table array is initialised by its constructor
	boards[0].numDrivers = NumDirectDrivers;
}

// Update the state of a board
void ExpansionManager::UpdateBoardState(CanAddress address, BoardState newState) noexcept
{
	ExpansionBoardData& board = boards[address];
	TaskCriticalSectionLocker lock;

	const BoardState oldState = board.state;
	if (newState != oldState)
	{
		board.state = newState;
		if (oldState == BoardState::unknown)
		{
			++numExpansionBoards;
			lastIndexSearched = 0;
		}
		else if (oldState == BoardState::flashing && numBoardsFlashing != 0)
		{
			--numBoardsFlashing;
		}

		if (newState == BoardState::flashing)
		{
			++numBoardsFlashing;
		}
		else if (newState == BoardState::unknown && numExpansionBoards != 0)
		{
			--numExpansionBoards;
			lastIndexSearched = 0;
		}
		reprap.BoardsUpdated();
	}
}

// Process an announcement from an expansion board. Don't free the message buffer that it arrived in
void ExpansionManager::ProcessAnnouncement(CanMessageBuffer *buf) noexcept
{
	const CanAddress src = buf->id.Src();
	if (src <= CanId::MaxCanAddress)
	{
		ExpansionBoardData& board = boards[src];
		String<StringLength100> boardTypeAndFirmwareVersion;
		boardTypeAndFirmwareVersion.copy(buf->msg.announce.boardTypeAndFirmwareVersion, CanMessageAnnounce::GetMaxTextLength(buf->dataLength));
		UpdateBoardState(src, BoardState::unknown);
		if (board.typeName == nullptr || strcmp(board.typeName, boardTypeAndFirmwareVersion.c_str()) != 0)
		{
			const char *newTypeName = nullptr;
			for (const ExpansionBoardData& data : boards)
			{
				if (data.typeName != nullptr && strcmp(boardTypeAndFirmwareVersion.c_str(), data.typeName) == 0)
				{
					newTypeName = data.typeName;
					break;
				}
			}
			if (newTypeName == nullptr)
			{
				char * const temp = new char[boardTypeAndFirmwareVersion.strlen() + 1];
				strcpy(temp, boardTypeAndFirmwareVersion.c_str());
				newTypeName = temp;
			}
			board.typeName = newTypeName;
			board.numDrivers = buf->msg.announce.numDrivers;
		}
		UpdateBoardState(src, BoardState::running);
	}
	buf->SetupResponseMessage<CanMessageAcknowledgeAnnounce>(0, CanInterface::GetCanAddress(), src);
	CanInterface::SendResponseNoFree(buf);
}

// Return a pointer to the expansion board, if it is present
const ExpansionBoardData *ExpansionManager::GetBoardDetails(uint8_t address) const noexcept
{
	return (address < ARRAY_SIZE(boards) && boards[address].state == BoardState::running) ? &boards[address] : nullptr;
}

// Tell an expansion board to update
GCodeResult ExpansionManager::UpdateRemoteFirmware(uint32_t boardAddress, GCodeBuffer& gb, const StringRef& reply) THROWS(GCodeException)
{
	CanInterface::CheckCanAddress(boardAddress, gb);

	const unsigned int moduleNumber = (gb.Seen('S')) ? gb.GetLimitedUIValue('S', 4) : 0;
	if (moduleNumber != (unsigned int)FirmwareModule::main && moduleNumber != (unsigned int)FirmwareModule::bootloader)
	{
		reply.printf("Unknown module number %u", moduleNumber);
		return GCodeResult::error;
	}

	// Ask the board for its type and check we have the firmware file for it
	CanMessageBuffer * const buf1 = CanInterface::AllocateBuffer(&gb);
	CanRequestId rid1 = CanInterface::AllocateRequestId(boardAddress);
	auto msg1 = buf1->SetupRequestMessage<CanMessageReturnInfo>(rid1, CanInterface::GetCanAddress(), (CanAddress)boardAddress);

	msg1->type = (moduleNumber == (unsigned int)FirmwareModule::bootloader) ? CanMessageReturnInfo::typeBootloaderName : CanMessageReturnInfo::typeBoardName;
	{
		const GCodeResult rslt = CanInterface::SendRequestAndGetStandardReply(buf1, rid1, reply);
		if (rslt != GCodeResult::ok)
		{
			return rslt;
		}
	}

	String<StringLength50> firmwareFilename;
	firmwareFilename.copy((moduleNumber == 3) ? "Duet3Bootloader-" : "Duet3Firmware_");
	firmwareFilename.cat(reply.c_str());
	reply.Clear();
	firmwareFilename.cat(".bin");

	// Do not ask Linux for a file here because that would create a deadlock.
	// If blocking calls to Linux are supposed to be made from the Spin loop, the Linux interface,
	// or at least the code doing SPI data transfers, has to be moved to a separate task first
#if HAS_MASS_STORAGE
	// It's fine to check if the file exists on the local SD though
	if (
# if HAS_LINUX_INTERFACE
			!reprap.UsingLinuxInterface() &&
# endif
			!reprap.GetPlatform().FileExists(FIRMWARE_DIRECTORY, firmwareFilename.c_str()))
	{
		reply.printf("Firmware file %s not found", firmwareFilename.c_str());
		return GCodeResult::error;
	}
#endif

	CanMessageBuffer * const buf2 = CanInterface::AllocateBuffer(&gb);
	const CanRequestId rid2 = CanInterface::AllocateRequestId(boardAddress);
	auto msg2 = buf2->SetupRequestMessage<CanMessageUpdateYourFirmware>(rid2, CanInterface::GetCanAddress(), (CanAddress)boardAddress);
	msg2->boardId = (uint8_t)boardAddress;
	msg2->invertedBoardId = (uint8_t)~boardAddress;
	msg2->module = moduleNumber;
	const GCodeResult rslt = CanInterface::SendRequestAndGetStandardReply(buf2, rid2, reply);
	if (rslt == GCodeResult::ok)
	{
		UpdateBoardState(boardAddress, BoardState::flashing);
	}
	return rslt;
}

void ExpansionManager::UpdateFinished(CanAddress address) noexcept
{
	UpdateBoardState(address, BoardState::resetting);
}

void ExpansionManager::UpdateFailed(CanAddress address) noexcept
{
	UpdateBoardState(address, BoardState::flashFailed);
}

GCodeResult ExpansionManager::ResetRemote(uint32_t boardAddress, GCodeBuffer& gb, const StringRef& reply) THROWS(GCodeException)
{
	CanInterface::CheckCanAddress(boardAddress, gb);
	CanMessageBuffer * const buf = CanInterface::AllocateBuffer(&gb);
	const CanRequestId rid = CanInterface::AllocateRequestId(boardAddress);
	buf->SetupRequestMessage<CanMessageReset>(rid, CanInterface::GetCanAddress(), (uint8_t)boardAddress);
	return CanInterface::SendRequestAndGetStandardReply(buf, rid, reply);
}

const ExpansionBoardData& ExpansionManager::FindIndexedBoard(unsigned int index) const noexcept
{
	if (index == 0 || index > numExpansionBoards)
	{
		return boards[0];
	}
	if (lastIndexSearched > index)
	{
		lastIndexSearched = 0;
	}

	TaskCriticalSectionLocker lock;
	unsigned int address = (lastIndexSearched == 0) ? 0 : lastAddressFound;
	unsigned int currentIndex = lastIndexSearched;
	while (currentIndex < index)
	{
		++address;
		if (address == ARRAY_SIZE(boards))
		{
			return boards[0];
		}
		if (boards[address].state != BoardState::unknown)
		{
			++currentIndex;
		}
	}

	lastIndexSearched = index;
	lastAddressFound = address;
	return boards[address];
}

void ExpansionManager::EmergencyStop() noexcept
{
	CanMessageBuffer *buf;
	while ((buf = CanMessageBuffer::Allocate()) == nullptr)
	{
		delay(1);
	}

//	debugPrintf("Allocated buffer\n");
	// Send an individual message to each known expansion board
	for (CanAddress addr = 1; addr <= CanId::MaxCanAddress; ++addr)
	{
		if (boards[addr].state == BoardState::running)
		{
			buf->SetupRequestMessage<CanMessageEmergencyStop>(0, CanInterface::GetCanAddress(), addr);
			CanInterface::SendMessageNoReplyNoFree(buf);
		}
	}
//	debugPrintf("sent individual messages\n");

	// Finally, send a broadcast message in case we missed any, and free the buffer
	buf->SetupBroadcastMessage<CanMessageEmergencyStop>(CanInterface::GetCanAddress());
	CanInterface::SendBroadcastNoFree(buf);

	CanMessageBuffer::Free(buf);
//	debugPrintf("sent broadcast\n");

	delay(10);							// allow time for the broadcast to be sent
	CanInterface::Shutdown();
}

#endif

// End