Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- async function initCommand(port, command, commandData) {
- let seq = ' '
- const encoder = new TextEncoder('windows-1251')
- const decoder = new TextDecoder('windows-1251')
- const dataPrefix = `\x01%c%c%c%s\x05%c%c%c%c\x03`
- let data = new Uint8Array(255)
- let data2 = new Uint8Array(255)
- let checkSum = 0
- let len, i, bytwrite, bytread, tries
- let bcc = new Uint8Array(4)
- let commandString = String.fromCharCode(seq, command, ...commandData)
- let dataString = dataPrefix.replace('%c', seq).replace('%c', command).replace('%s', commandData)
- data = encoder.encode(dataString)
- for (len = 1; data[len] !== 0x05; len++) checkSum += data[len]
- len += 32 - 1
- checkSum = checkSum - '%' - 'c' + len + 0x05
- i = (checkSum & 0xf) + 0x30
- bcc[0] = i
- i = ((checkSum & 0xf0) >> 4) + 0x30
- bcc[1] = i
- i = ((checkSum & 0xf00) >> 8) + 0x30
- bcc[2] = i
- i = ((checkSum & 0xf000) >> 12) + 0x30
- bcc[3] = i
- data2 = encoder.encode(dataString.replace('%c', len).replace('%c', bcc[3]).replace('%c', bcc[2]).replace('%c', bcc[1]).replace('%c', bcc[0]))
- if (seq === '#') seq = ' '
- else seq = '#'
- len = data2.length
- const writer = port.writable.getWriter()
- try {
- for (i = 0; i < len; i++) {
- await writer.write(data2.slice(i, i + 1))
- }
- } finally {
- writer.releaseLock()
- }
- await new Promise((resolve) => setTimeout(resolve, 60))
- data = new Uint8Array(255)
- const reader = port.readable.getReader()
- try {
- for (tries = 0; tries < 5; tries++) {
- const { value, done } = await reader.read()
- if (done) break
- if (value[0] === 0x16) {
- tries--
- await new Promise((resolve) => setTimeout(resolve, 60))
- } else if (value[0] === 0x01) {
- len = 1
- while (value[len - 1] !== 0x03) {
- const { value: chunk, done: chunkDone } = await reader.read()
- if (chunkDone) break
- data.set(chunk, len)
- len += chunk.length
- }
- data[len] = 0
- break
- }
- }
- } finally {
- reader.releaseLock()
- }
- if (data[0] === 0) console.log('ERROR: No bytes to read')
- console.log(decoder.decode(data.slice(4)))
- return data
- }
- /// POVIKUVANJE NA FUNKCIJATA
- const str = '2Е2'
- let port
- try {
- port = await navigator.serial.requestPort()
- if (port.readable || port.writable) {
- await port.close()
- }
- await port.open({ baudRate: 9600 })
- const lines = str
- .split('\n')
- .map((line) => line.trim())
- .filter((line) => line.length > 0)
- for (const line of lines) {
- await initCommand(port, line[0], line.slice(1))
- }
- } catch (error) {
- console.error('ERROR:', error)
- await port.close()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement