티스토리 뷰

Web/MQTT 통신

mqtt_vue_touchdesigner

잉_민 2022. 11. 5. 17:19
<template>
  <div>
    <h1>MQTT 테스트</h1>
    {{ mqttData }}
  </div>
</template>

<script>
import mqtt from 'mqtt'
export default {
  data() {
    return {
      mtopic: 'rasp/1',
      mqttDataList: [] // mqtt를 통해 받은 데이터(리스트로 계속 추가됨)
    }
  },
  mounted() {
    this.createMqtt()
  },
  methods: {
    createMqtt() {
      // mqtt연결
      const mqttClient = mqtt.connect(process.env.VUE_APP_MQTT)
      mqttClient.on('connect', () => {
        // mqtt연결 시 구독한다.
        const topic = this.mtopic // 구독할 topic
        console.log('connect')
        mqttClient.subscribe(topic, {}, (error, res) => {
          if (error) {
            console.error('mqtt client error', error)
          }
        })
      })
      // 메세지 실시간 수신
      mqttClient.on('message', (topic, message) => {
        const mqttData = JSON.parse(message) // json string으로만 받을 수 있음
        // 선택된 devicdId만 수용함
        this.mqttDataList.push(mqttData) // 리스트에 계속 추가함
        console.log('message : ', mqttData) //메세지 출력
      })
    }
  }
}
</script>

 

.env

VUE_APP_MQTT=ws://127.0.0.1:8088

https://kang-ji.tistory.com/241

 

[Vue] vue 환경변수 - .env 파일과 환경변수 설정방법

서버 엔드포인트 API 주소를 환경변수로 관리하는 방법 프로젝트 Root돌더 위치에 .env 파일 생성. 키 = 값 의 형태로 작성한다. (환경변수 파일) .env API_URL = http://localhost:3000/ 기존 axios API 파일 설정

kang-ji.tistory.com

 

(여기가 제일 중요함 .. )

: 기본 mqtt는 1883 포트를 사용함 .

:하지만 우리는 웹이 mqtt값을 보내야하므로 8088 새로운 포트를 만들어줌 이것은 webSockets 통신 방식을 통해 내보내짐.

모스퀴토.conf 경로  /usr/local/etc/mosquitto/mosquitto.conf 

mosquitto.conf

allow_anonymous true

#listener
listener 1883

# protocol mqtt
listener 8088
protocol websockets

***모스퀴토 서비스 재시작하여 바뀐 값을 적용시킨다.

윈도우

01 Mosquitto 중단하기

Mosquitto가 시작된 터미널 윈도우에서 ctrl+C를 누르면 Mosquitto가 종료되고 명령 프롬프트로 돌아옵니다.

02 Mosquitto 다시 시작하기

명령어 프롬프트에서 다음 명령어를 실행합니다.

cd c:\Program Files\mosquitto
mosquitto -c mosquitto.conf -v
systemctl status mosquitto.service

systemctl reload mosquitto.service
systemctl restart mosquitto.service

systemctl status mosquitto.service


// mac

모스키토 설치
brew install mosquitto

모스키토 서비스 실행
brew services start mosquitto

모스키토 서비스 중지
brew services stop mosquitto

비서비스 실행
/usr/local/sbin/mosquitto -c /usr/local/etc/mosquitto/mosquitto.conf

lemonheim~$ /usr/local/sbin/mosquitto -c /usr/local/etc/mosquitto/mosquitto.conf
1515670129: mosquitto version 1.4.14 (build date 2017-10-22 16:34:39+0100) starting
1515670129: Config loaded from /usr/local/etc/mosquitto/mosquitto.conf.
1515670129: Opening ipv6 listen socket on port 1883.
1515670129: Opening ipv4 listen socket on port 1883.

메세지 구독
mosquitto_sub -h [주소] -p [포트] -t [주제, 방제목]

/usr/local/opt/mosquitto/bin/mosquitto_sub -h 127.0.0.1 -p 1883 -t topic

메시지 발행(퍼블리싱)
mosquitto_pub -h [주소] -p [포트] -t [주제, 방제목] -m [메세지]

/usr/local/opt/mosquitto/bin/mosquitto_pub -h 127.0.0.1 -p 1883 -t topic -m "test messgae"

https://ing-min.tistory.com/61

 

FRONT(Vue.js)_MQTT를 활용하여 라즈베리파이 신호 받기

https://ing-min.tistory.com/49 https://ing-min.tistory.com/92 : 참고 링크 1-1. Desktop 모스키토 실행 (모스키토 config 수정해준다) : 포트 설정 / ... # listener port-number [ip address/host name/unix socket path] #listener listener 188

ing-min.tistory.com

 

드디어 오류 안뜬다.

(websocket connection to "000" failed ) 이런 오류 뜨면 웹소켓 문제이거나 포트문제이거나 ip문제 ..

-> 모스키토 config 파일 수정하면 해결됨.

 


터디에서 값을 보내보자

(receive)

a.subscribe('1',qos=0)

 

mqtt Box - 테스트 시뮬레이션

 

publish  값보내기

토큰이 같이야한다.

# me - this DAT
# project1 컴포지션에서 mqttclient1 오퍼레이터를 a 로 지정하고
a= op('mqttclient1')
msg = 'b' + '"' + str("hi123") + '"'

# Called when connection established
# dat - the OP which is cooking
def onConnect(dat):
	print('connect')
	a.subscribe('1',qos=0)
	a.publish('1',eval(msg),qos=0,retain=True)
	print("send OK")

	return

# Called when connection failed
# dat - the OP which is cooking
# msg - reason for failure
def onConnectFailure(dat, msg):
	return

# Called when current connection lost
# dat - the OP which is cooking
# msg - reason for failure
def onConnectionLost(dat, msg):
	return

 

a.publish('1',eval(msg),qos=0,retain=True)
print("send OK")

 


TD 테이블 값을 보내보자

오류

Uncaught SyntaxError: Unexpected token r in JSON at position 0

해결

var num = JSON.parse('{"searchNum":1234}');
console.log(num.searchNum);

위와 같이 바깥 문자열 부분은 작은따옴표(single quote)로 묶고, JSON 객체 안의 key 값의 문자열은 큰따옴표로 묶어 주게 되면 오류는 해결된답니다!

https://domdom.tistory.com/entry/%EC%98%A4%EB%A5%98%ED%95%B4%EA%B2%B0-Uncaught-SyntaxError-Unexpected-token-in-JSON-at-position-1

 

[오류해결] Uncaught SyntaxError: Unexpected token ' in JSON at position 1

Uncaught SyntaxError: Unexpected token ' in JSON at position 1 라는 오류를 혹시 보신적 있으신가요?? 저는 JSON.parse 함수를 사용할 때 자주보는 오류인 것 같아요! 코드가 한 줄이라면 바로 어떤 이유에..

blog.domdomi.world

 

오류

[WDS] Disconnected!

ERROR_SSL_PROTOCOL_ERROR

해결

"serve": "vue-cli-service serve", // to "serve": "vue-cli-service serve --host localhost",

https://it-jm.tistory.com/94

 

vue3 [WDS] Disconnected! 해결방법 [해결완료]

코딩애플님의 강의를 보고 따라 했다. https://www.youtube.com/watch?v=0BbF7UxKKvg&t=303s 다 좋은데!!!!! 왜 항상 이런 시련은 나에게만 오는 것일까? 해당 문제는 Vue의 장점이라고 하는 자동 렌더링이 안 되

it-jm.tistory.com

오류

chotto를 json형식으로 바꿔야하는데 이부분을 모르겠음..

https://forum.derivative.ca/t/mqtt-dat-using-json-messages-not-working/9766

 

MQTT DAT using JSON messages - not working

We are getting JSON strings via MTQQ and want to parse them into a DAT. Right now in the MQTT callback we getting the message string, parsing it with TDJSON using textToJSON() and jsonToDat() writing to a table DAT. The table ‘{ “A”:1, “B”:2}’

forum.derivative.ca

후... 때려쳐

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
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
글 보관함